Ejemplo n.º 1
0
def set_blog_page_cache(response):
    from django.core.cache import cache

    if not get_cms_setting('PAGE_CACHE'):
        return response
    request = response._request
    save_cache = True
    for placeholder in getattr(request, 'placeholders', []):
        if not placeholder.cache_placeholder:
            save_cache = False
            break
    if hasattr(request, 'toolbar'):
        if request.toolbar.edit_mode or request.toolbar.show_toolbar:
            save_cache = False
    if request.user.is_authenticated():
        save_cache = False
    if not save_cache:
        add_never_cache_headers(response)
        return response
    else:
        version = _get_cache_version()
        ttl = get_cms_setting('CACHE_DURATIONS')['content']

        cache.set(
            _blog_page_cache_key(request),
            (response.content, response._headers),
            ttl,
            version=version
        )
        # See note in invalidate_cms_page_cache()
        _set_cache_version(version)
Ejemplo n.º 2
0
 def add_structure_mode(self):
     switcher = self.toolbar.add_button_list('Mode Switcher', side=self.toolbar.RIGHT,
                                             extra_classes=['cms_toolbar-item-cms-mode-switcher'])
     switcher.add_button(_("Structure"), '?%s' % get_cms_setting('CMS_TOOLBAR_URL__BUILD'), active=self.toolbar.build_mode,
                         disabled=not self.toolbar.build_mode)
     switcher.add_button(_("Content"), '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON'), active=not self.toolbar.build_mode,
                         disabled=self.toolbar.build_mode)
Ejemplo n.º 3
0
    def test_get_placeholder_cache_key(self):
        version, vary_on_list = _get_placeholder_cache_version(self.placeholder, 'en', 1)
        desired_key = '{prefix}|render_placeholder|id:{id}|lang:{lang}|site:{site}|tz:{tz}|v:{version}|country-code:{cc}'.format(  # noqa
            prefix=get_cms_setting('CACHE_PREFIX'),
            id=self.placeholder.pk,
            lang='en',
            site=1,
            tz=get_timezone_name(),
            version=version,
            cc='_',
        )
        _set_placeholder_cache_version(self.placeholder, 'en', 1, version, vary_on_list=vary_on_list, duration=1)
        actual_key = _get_placeholder_cache_key(self.placeholder, 'en', 1, self.en_request)
        self.assertEqual(actual_key, desired_key)

        en_key = _get_placeholder_cache_key(self.placeholder, 'en', 1, self.en_request)
        de_key = _get_placeholder_cache_key(self.placeholder, 'de', 1, self.de_request)
        self.assertNotEqual(en_key, de_key)

        en_us_key = _get_placeholder_cache_key(self.placeholder, 'en', 1, self.en_us_request)
        self.assertNotEqual(en_key, en_us_key)

        desired_key = '{prefix}|render_placeholder|id:{id}|lang:{lang}|site:{site}|tz:{tz}|v:{version}|country-code:{cc}'.format(  # noqa
            prefix=get_cms_setting('CACHE_PREFIX'),
            id=self.placeholder.pk,
            lang='en',
            site=1,
            tz=get_timezone_name(),
            version=version,
            cc='US',
        )
        self.assertEqual(en_us_key, desired_key)
Ejemplo n.º 4
0
 def add_structure_mode_item(self, extra_classes=('cms_toolbar-item-cms-mode-switcher',)):
     build_mode = self.toolbar.build_mode
     build_url = '?%s' % get_cms_setting('CMS_TOOLBAR_URL__BUILD')
     edit_url = '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')
     switcher = self.toolbar.add_button_list('Mode Switcher', side=self.toolbar.RIGHT, extra_classes=extra_classes)
     switcher.add_button(_('Structure'), build_url, active=build_mode, disabled=not build_mode)
     switcher.add_button(_('Content'), edit_url, active=not build_mode, disabled=build_mode)
Ejemplo n.º 5
0
    def test_templates(self):
        """
        Test the inheritance magic for templates
        """
        parent = create_page("parent", "nav_playground.html", "en")
        child = create_page("child", "nav_playground.html", "en", parent=parent)
        grand_child = create_page("child", "nav_playground.html", "en", parent=child)
        child.template = constants.TEMPLATE_INHERITANCE_MAGIC
        grand_child.template = constants.TEMPLATE_INHERITANCE_MAGIC
        child.save()
        grand_child.save()

        # kill template cache
        delattr(grand_child, '_template_cache')
        with self.assertNumQueries(1):
            self.assertEqual(child.template, constants.TEMPLATE_INHERITANCE_MAGIC)
            self.assertEqual(parent.get_template_name(), grand_child.get_template_name())

        # test template cache
        with self.assertNumQueries(0):
            grand_child.get_template()

        parent.template = constants.TEMPLATE_INHERITANCE_MAGIC
        parent.save()
        self.assertEqual(parent.template, constants.TEMPLATE_INHERITANCE_MAGIC)
        self.assertEqual(parent.get_template(), get_cms_setting('TEMPLATES')[0][0])
        self.assertEqual(parent.get_template_name(), get_cms_setting('TEMPLATES')[0][1])
Ejemplo n.º 6
0
    def add_admin_menu(self):
        if not self._admin_menu:
            self._admin_menu = self.toolbar.get_or_create_menu(ADMIN_MENU_IDENTIFIER, self.current_site.name)
            # Users button
            self.add_users_button(self._admin_menu)

            # sites menu
            if get_cms_setting('PERMISSION'):
                sites_queryset = get_user_sites_queryset(self.request.user)
            else:
                sites_queryset = Site.objects.all()

            if len(sites_queryset) > 1:
                sites_menu = self._admin_menu.get_or_create_menu('sites', _('Sites'))
                sites_menu.add_sideframe_item(_('Admin Sites'), url=admin_reverse('sites_site_changelist'))
                sites_menu.add_break(ADMIN_SITES_BREAK)
                for site in sites_queryset:
                    sites_menu.add_link_item(site.name, url='http://%s' % site.domain,
                                             active=site.pk == self.current_site.pk)

            # admin
            self._admin_menu.add_sideframe_item(_('Administration'), url=admin_reverse('index'))
            self._admin_menu.add_break(ADMINISTRATION_BREAK)

            # cms users
            self._admin_menu.add_sideframe_item(_('User settings'), url=admin_reverse('cms_usersettings_change'))
            self._admin_menu.add_break(USER_SETTINGS_BREAK)

            # Disable toolbar
            self._admin_menu.add_link_item(_('Disable toolbar'), url='?%s' % get_cms_setting('CMS_TOOLBAR_URL__DISABLE'))
            self._admin_menu.add_break(TOOLBAR_DISABLE_BREAK)

            # logout
            self.add_logout_button(self._admin_menu)
Ejemplo n.º 7
0
def get_admin_menu_item_context(request, page, filtered=False):
    """
    Used for rendering the page tree, inserts into context everything what
    we need for single item
    """
    has_add_page_permission = page.has_add_permission(request)
    has_move_page_permission = page.has_move_page_permission(request)
    
    site = Site.objects.get_current()
    lang = get_language_from_request(request)
    #slug = page.get_slug(language=lang, fallback=True) # why was this here ??
    metadata = ""
    if get_cms_setting('PERMISSION'):
        # jstree metadata generator 
        md = []
        
        #if not has_add_page_permission:
        if not has_move_page_permission:
            md.append(('valid_children', False))
            md.append(('draggable', False))
        if md:
            # just turn it into simple javascript object
            metadata = "{" + ", ".join(map(lambda e: "%s: %s" %(e[0], 
                isinstance(e[1], bool) and str(e[1]) or e[1].lower() ), md)) + "}"
        
    has_add_on_same_level_permission = False
    opts = Page._meta
    if get_cms_setting('PERMISSION'):
        perms = has_global_page_permission(request, page.site_id, can_add=True)
        if (request.user.has_perm(opts.app_label + '.' + opts.get_add_permission()) and perms):
            has_add_on_same_level_permission = True

    if page.delete_requested():
        css_class = "publisher_delete_requested"
    elif not page.published:
        css_class = "publisher_draft"
    else:
        css_class = publisher_classes.get(page.publisher_state, "")

    if not has_add_on_same_level_permission and page.parent_id:
        has_add_on_same_level_permission = permissions.has_generic_permission(page.parent_id, request.user, "add", page.site)
    #has_add_on_same_level_permission = has_add_page_on_same_level_permission(request, page)
    context = {
        'page': page,
        'site': site,
        'lang': lang,
        'filtered': filtered,
        'metadata': metadata,
        'css_class': css_class,
        
        'has_change_permission': page.has_change_permission(request),
        'has_publish_permission': page.has_publish_permission(request),
        'has_delete_permission': page.has_delete_permission(request),
        'has_move_page_permission': has_move_page_permission,
        'has_add_page_permission': has_add_page_permission,
        'has_add_on_same_level_permission': has_add_on_same_level_permission,
        'CMS_PERMISSION': get_cms_setting('PERMISSION'),
        'CMS_SHOW_END_DATE': get_cms_setting('SHOW_END_DATE'),
    }
    return context
Ejemplo n.º 8
0
def get_admin_menu_item_context(request, page, filtered=False, language=None):
    """
    Used for rendering the page tree, inserts into context everything what
    we need for single item
    """
    has_add_page_permission = page.has_add_permission(request)
    has_move_page_permission = page.has_move_page_permission(request)

    site = Site.objects.get_current()
    lang = get_language_from_request(request)
    metadata = ""
    if get_cms_setting("PERMISSION"):
        # jstree metadata generator
        md = []

        if not has_move_page_permission:
            md.append(("valid_children", False))
            md.append(("draggable", False))
        if md:
            # just turn it into simple javascript object
            metadata = (
                "{"
                + ", ".join(map(lambda e: "%s: %s" % (e[0], isinstance(e[1], bool) and str(e[1]) or e[1].lower()), md))
                + "}"
            )

    has_add_on_same_level_permission = False
    opts = Page._meta
    if get_cms_setting("PERMISSION"):
        if hasattr(request.user, "_global_add_perm_cache"):
            global_add_perm = request.user._global_add_perm_cache
        else:
            global_add_perm = GlobalPagePermission.objects.user_has_add_permission(request.user, page.site_id).exists()
            request.user._global_add_perm_cache = global_add_perm
        if request.user.has_perm(opts.app_label + "." + get_permission_codename("add", opts)) and global_add_perm:
            has_add_on_same_level_permission = True
    from cms.utils import permissions

    if not has_add_on_same_level_permission and page.parent_id:
        has_add_on_same_level_permission = permissions.has_generic_permission(
            page.parent_id, request.user, "add", page.site_id
        )
    context = {
        "page": page,
        "site": site,
        "lang": lang,
        "filtered": filtered,
        "metadata": metadata,
        "preview_language": language,
        "has_change_permission": page.has_change_permission(request),
        "has_publish_permission": page.has_publish_permission(request),
        "has_delete_permission": page.has_delete_permission(request),
        "has_move_page_permission": has_move_page_permission,
        "has_add_page_permission": has_add_page_permission,
        "has_add_on_same_level_permission": has_add_on_same_level_permission,
        "CMS_PERMISSION": get_cms_setting("PERMISSION"),
    }
    return context
Ejemplo n.º 9
0
def get_admin_menu_item_context(request, page, filtered=False, language=None):
    """
    Used for rendering the page tree, inserts into context everything what
    we need for single item
    """
    has_add_page_permission = page.has_add_permission(request)
    has_move_page_permission = page.has_move_page_permission(request)

    site = Site.objects.get_current()
    lang = get_language_from_request(request)
    #slug = page.get_slug(language=lang, fallback=True) # why was this here ??
    metadata = ""
    if get_cms_setting('PERMISSION'):
        # jstree metadata generator 
        md = []

        #if not has_add_page_permission:
        if not has_move_page_permission:
            md.append(('valid_children', False))
            md.append(('draggable', False))
        if md:
            # just turn it into simple javascript object
            metadata = "{" + ", ".join(map(lambda e: "%s: %s" % (e[0],
            isinstance(e[1], bool) and str(e[1]) or e[1].lower() ), md)) + "}"

    has_add_on_same_level_permission = False
    opts = Page._meta
    if get_cms_setting('PERMISSION'):
        if hasattr(request.user, '_global_add_perm_cache'):
            global_add_perm = request.user._global_add_perm_cache
        else:
            global_add_perm = GlobalPagePermission.objects.user_has_add_permission(
                request.user, page.site_id).exists()
            request.user._global_add_perm_cache = global_add_perm
        if request.user.has_perm(opts.app_label + '.' + opts.get_add_permission()) and global_add_perm:
            has_add_on_same_level_permission = True
    from cms.utils import permissions
    if not has_add_on_same_level_permission and page.parent_id:
        has_add_on_same_level_permission = permissions.has_generic_permission(page.parent_id, request.user, "add",
                                                                              page.site_id)
        #has_add_on_same_level_permission = has_add_page_on_same_level_permission(request, page)
    context = {
        'page': page,
        'site': site,
        'lang': lang,
        'filtered': filtered,
        'metadata': metadata,
        'preview_language': language,
        'has_change_permission': page.has_change_permission(request),
        'has_publish_permission': page.has_publish_permission(request),
        'has_delete_permission': page.has_delete_permission(request),
        'has_move_page_permission': has_move_page_permission,
        'has_add_page_permission': has_add_page_permission,
        'has_add_on_same_level_permission': has_add_on_same_level_permission,
        'CMS_PERMISSION': get_cms_setting('PERMISSION'),
    }
    return context
Ejemplo n.º 10
0
 def test_templates(self):
     """
     Tests that the plain CMS_TEMPLATES works as usual
     """
     original_files = [template[0] for template in settings.CMS_TEMPLATES]
     files = [template[0] for template in get_cms_setting('TEMPLATES')]
     if get_cms_setting('TEMPLATE_INHERITANCE'):
         original_files.append(constants.TEMPLATE_INHERITANCE_MAGIC)
     self.assertEqual(len(files), 6)
     self.assertEqual(set(files), set(original_files))
Ejemplo n.º 11
0
    def test_toolbar_staff(self):
        page = create_page('test', 'nav_playground.html', 'en', published=True)
        request = self.get_page_request(page, self.get_superuser())
        toolbar = CMSToolbar(request)

        items = toolbar.get_items({})
        # Logo + edit-mode + templates + page-menu + admin-menu + logout
        self.assertEqual(len(items), 6)

        # check the logo is there
        logo = items[0]
        self.assertIsInstance(logo, Anchor)

        # check the edit-mode switcher is there and the switcher is turned off
        edit = items[1]
        self.assertIsInstance(edit, Switcher)
        self.assertFalse(toolbar.edit_mode)

        # check templates
        templates = items[2]
        self.assertIsInstance(templates, List)
        self.assertEqual(len(templates.raw_items), len(get_cms_setting('TEMPLATES')))
        base = reverse('admin:cms_page_change_template', args=(page.pk,))
        for item, template in zip(templates.raw_items, get_cms_setting('TEMPLATES')):
            self.assertEqual(item.url, '%s?template=%s' % (base, template[0]))

        # check page menu
        pagemenu = items[3]
        self.assertIsInstance(pagemenu, List)
        self.assertEqual(len(pagemenu.raw_items), 4)

        overview, addchild, addsibling, delete = pagemenu.raw_items
        self.assertEqual(overview.url, reverse('admin:cms_page_changelist'))
        self.assertEqual(addchild.serialize_url({}, toolbar),
            reverse('admin:cms_page_add') + '?position=last-child&target=%s' % page.pk)
        self.assertEqual(addsibling.serialize_url({}, toolbar),
            reverse('admin:cms_page_add') + '?position=last-child')
        self.assertEqual(delete.serialize_url({}, toolbar),
            reverse('admin:cms_page_delete', args=(page.pk,)))

        # check the admin-menu
        admin = items[4]
        self.assertIsInstance(admin, List)
        self.assertEqual(len(admin.raw_items), 3) # page settings, history and admin
        self.assertIsInstance(admin.raw_items[0], ListItem)
        self.assertIsInstance(admin.raw_items[1], ListItem)
        self.assertIsInstance(admin.raw_items[2], ListItem)

        # check the logout button
        logout = items[-1]
        self.assertIsInstance(logout, GetButton)
        self.assertEqual(logout.url, '?cms-toolbar-logout')
Ejemplo n.º 12
0
 def test_multisite(self):
     """
     Checking that templates can be loaded by the template loader
     """
     templates = get_cms_setting('TEMPLATES')
     for template in templates:
         if template[0] != constants.TEMPLATE_INHERITANCE_MAGIC:
             self.assertTrue(template[0].find('%s/' % SITE_PATH[1]) >= -1)
     with self.settings(SITE_ID=2):
         templates = get_cms_setting('TEMPLATES')
         for template in templates:
             if template[0] != constants.TEMPLATE_INHERITANCE_MAGIC:
                 self.assertTrue(template[0].find('%s/' % SITE_PATH[2]) >= -1)
Ejemplo n.º 13
0
    def get_absolute_url(self, link):
        cache_key = '{0}anylink-page-url:{1}:{2}'.format(
            get_cms_setting('CACHE_PREFIX'), str(link.page_id), get_language())

        url = cache.get(cache_key)
        if url is None:
            url = link.page.get_absolute_url()
            cache.set(cache_key, url, get_cms_setting('CACHE_DURATIONS')['content'])

        if link.anchor:
            parsed = urlparse.urlparse(url)
            parsed = parsed._replace(fragment=link.anchor)
            url = parsed.geturl()

        return url
Ejemplo n.º 14
0
    def populate(self):
        # always use draft if we have a page
        self.page = get_page_draft(self.request.current_page)
        if not self.page:
            # Nothing to do
            return

        # check global permissions if CMS_PERMISSIONS is active
        if get_cms_setting('PERMISSION'):
            has_global_current_page_change_permission = has_page_change_permission(self.request)
        else:
            has_global_current_page_change_permission = False
            # check if user has page edit permission
        can_change = self.request.current_page and self.request.current_page.has_change_permission(self.request)

        if has_global_current_page_change_permission or can_change:
            try:
                icon_extension = MenuExtension.objects.get(extended_object_id=self.page.id)
            except MenuExtension.DoesNotExist:
                icon_extension = None
            try:
                if icon_extension:
                    url = reverse('admin:app_menuextension_change', args=(icon_extension.pk,))
                else:
                    url = reverse('admin:app_menuextension_add') + '?extended_object=%s' % self.page.pk
            except NoReverseMatch:
                pass
            else:
                not_edit_mode = not self.toolbar.edit_mode
                current_page_menu = self.toolbar.get_or_create_menu('page')
                current_page_menu.add_modal_item(_('Menu Settings'), url=url, disabled=not_edit_mode)
Ejemplo n.º 15
0
def get_placeholder_conf(setting, placeholder, template=None, default=None):
    """
    Returns the placeholder configuration for a given setting. The key would for
    example be 'plugins' or 'name'.

    If a template is given, it will try
    CMS_PLACEHOLDER_CONF['template placeholder'] and
    CMS_PLACEHOLDER_CONF['placeholder'], if no template is given only the latter
    is checked.
    """
    if placeholder:
        keys = []
        if template:
            keys.append("%s %s" % (template, placeholder))
        keys.append(placeholder)
        for key in keys:
            conf = get_cms_setting('PLACEHOLDER_CONF').get(key)
            if not conf:
                continue
            value = conf.get(setting)
            if value is not None:
                return value
            inherit = conf.get('inherit')
            if inherit:
                if ' ' in inherit:
                    inherit = inherit.split(' ')
                else:
                    inherit = (None, inherit,)
                value = get_placeholder_conf(setting, inherit[1], inherit[0], default)
                if value is not None:
                    return value
    return default
Ejemplo n.º 16
0
    def _setup_extension_toolbar(self):
        """
        Does all the sanity check for the current environment:

            * that a page exists
            * permissions check on the current page

        It returns the page menu or None if the above conditions are not met
        """
        page = self._get_page()
        if not page:
            # Nothing to do
            return
        # check global permissions if CMS_PERMISSIONS is active
        if get_cms_setting('PERMISSION'):
            has_global_current_page_change_permission = has_page_change_permission(self.request)
        else:
            has_global_current_page_change_permission = True
            # check if user has page edit permission
        can_change = (self.request.current_page and
                      self.request.current_page.has_change_permission(self.request))
        current_page_menu = self.toolbar.get_or_create_menu('page')
        if can_change and has_global_current_page_change_permission:
            return current_page_menu
        else:
            return
Ejemplo n.º 17
0
    def test_cache_invalidation(self):

        # Ensure that we're testing in an environment WITHOUT the MW cache...
        exclude = [
            'django.middleware.cache.UpdateCacheMiddleware',
            'django.middleware.cache.FetchFromCacheMiddleware'
        ]
        overrides = dict()
        if getattr(settings, 'MIDDLEWARE', None):
            overrides['MIDDLEWARE'] = [mw for mw in settings.MIDDLEWARE if mw not in exclude]
        else:
            overrides['MIDDLEWARE_CLASSES'] = [mw for mw in settings.MIDDLEWARE_CLASSES if mw not in exclude]
        with self.settings(**overrides):
            # Silly to do these tests if this setting isn't True
            page_cache_setting = get_cms_setting('PAGE_CACHE')
            self.assertTrue(page_cache_setting)
            page1 = create_page('test page 1', 'nav_playground.html', 'en',
                                published=True)

            placeholder = page1.placeholders.get(slot="body")
            add_plugin(placeholder, "TextPlugin", 'en', body="First content")
            page1.publish('en')
            response = self.client.get('/en/')
            self.assertContains(response, 'First content')
            response = self.client.get('/en/')
            self.assertContains(response, 'First content')
            add_plugin(placeholder, "TextPlugin", 'en', body="Second content")
            page1.publish('en')
            response = self.client.get('/en/')
            self.assertContains(response, 'Second content')
Ejemplo n.º 18
0
    def test_clean_overwrite_url(self):
        user = AnonymousUser()
        user.is_superuser = True
        user.pk = 1
        request = type('Request', (object,), {'user': user})
        with SettingsOverride():
            data = {
                'title': 'TestPage',
                'slug': 'test-page',
                'language': 'en',
                'overwrite_url': '/overwrite/url/',
                'site': Site.objects.get_current().pk,
                'template': get_cms_setting('TEMPLATES')[0][0],
                'published': True
            }

            form = PageForm(data)
            self.assertTrue(form.is_valid(), form.errors.as_text())
            # WTF? WHY DOES form.save() not handle this stuff???
            instance = form.save()
            instance.permission_user_cache = user
            instance.permission_advanced_settings_cache = True
            Title.objects.set_or_create(request, instance, form, 'en')
            form = PageForm(data, instance=instance)
            self.assertTrue(form.is_valid(), form.errors.as_text())
Ejemplo n.º 19
0
    def get_value(self, context, page_lookup, lang, site):
        from django.core.cache import cache

        site_id = get_site_id(site)
        request = context.get('request', False)

        if not request:
            return ''

        if lang is None:
            lang = get_language_from_request(request)

        cache_key = _get_cache_key('page_url', page_lookup, lang, site_id) + \
            '_type:absolute_url'

        url = cache.get(cache_key)

        if not url:
            page = _get_page_by_untyped_arg(page_lookup, request, site_id)
            if page:
                url = page.get_absolute_url(language=lang)
                cache.set(cache_key, url,
                          get_cms_setting('CACHE_DURATIONS')['content'])
        if url:
            return url
        return ''
Ejemplo n.º 20
0
    def setUp(self):
        super(CMSRequestBasedTest, self).setUp()
        self.template = get_cms_setting('TEMPLATES')[0][0]
        self.language = settings.LANGUAGES[0][0]
        self.root_page = api.create_page(
            'root page',
            self.template,
            self.language,
            published=True
        )
        self.app_config = FaqConfig.objects.create(namespace='aldryn_faq',
                                                   permalink_type='Bp',
                                                   non_permalink_handling=301)
        self.page = api.create_page(
            'faq',
            self.template,
            self.language,
            published=True,
            parent=self.root_page,
            apphook='FaqApp',
            apphook_namespace=self.app_config.namespace
        )
        self.placeholder = self.page.placeholders.all()[0]

        for page in [self.root_page, self.page]:
            for language, _ in settings.LANGUAGES[1:]:
                api.create_title(language, page.get_slug(), page)
                page.publish(language)
Ejemplo n.º 21
0
    def test_hide_untranslated(self):
        TESTLANG = get_primary_lanaguage()
        TESTLANG2 = get_secondary_lanaguage()
        page = create_page("mlpage-%s" % TESTLANG, "nav_playground.html", TESTLANG)
        create_title(TESTLANG2, "mlpage-%s" % TESTLANG2, page, slug=page.get_slug())
        page2 = create_page("mlpage-2-%s" % TESTLANG, "nav_playground.html", TESTLANG, parent=page)
        page.publish(TESTLANG)
        page.publish(TESTLANG2)
        page2.publish(TESTLANG)

        menu = CMSMenu()
        lang_settings = copy.deepcopy(get_cms_setting('LANGUAGES'))

        request_1 = self.get_request('/%s/' % TESTLANG, TESTLANG)
        request_2 = self.get_request('/%s/' % TESTLANG2, TESTLANG2)

        lang_settings[1][1]['hide_untranslated'] = False
        with SettingsOverride(CMS_LANGUAGES=lang_settings):
            list_1 = [node.id for node in menu.get_nodes(request_1)]
            list_2 = [node.id for node in menu.get_nodes(request_2)]
            self.assertEqual(list_1, list_2)
            self.assertEqual(len(list_1), 2)

        lang_settings[1][1]['hide_untranslated'] = True
        with SettingsOverride(CMS_LANGUAGES=lang_settings):
            list_1 = [node.id for node in menu.get_nodes(request_1)]
            list_2 = [node.id for node in menu.get_nodes(request_2)]
            self.assertNotEqual(list_1, list_2)
            self.assertEqual(len(list_2), 1)
            self.assertEqual(len(list_1), 2)
Ejemplo n.º 22
0
def clear_permission_cache():
    version = get_cache_version()
    if version > 1:
        cache.incr(get_cache_version_key())
    else:
        cache.set(get_cache_version_key(), 2,
                get_cms_setting('CACHE_DURATIONS')['permissions'])
Ejemplo n.º 23
0
    def _build_nodes(self, request, site_id):
        """
        This is slow. Caching must be used.
        One menu is built per language and per site.

        Namespaces: they are ID prefixes to avoid node ID clashes when plugging
        multiple trees together.

        - We iterate on the list of nodes.
        - We store encountered nodes in a dict (with namespaces):
            done_nodes[<namespace>][<node's id>] = node
        - When a node has a parent defined, we lookup that parent in done_nodes
            if it's found:
                set the node as the node's parent's child (re-read this)
            else:
                the node is put at the bottom of the list
        """
        # Before we do anything, make sure that the menus are expanded.
        self._expand_menus()
        # Cache key management
        lang = get_language()
        prefix = getattr(settings, "CMS_CACHE_PREFIX", "menu_cache_")
        key = "%smenu_nodes_%s_%s" % (prefix, lang, site_id)
        if request.user.is_authenticated():
            key += "_%s_user" % request.user.pk
        cached_nodes = cache.get(key, None)
        if cached_nodes:
            return cached_nodes

        final_nodes = []
        for menu_class_name in self.menus:
            menu = self.menus[menu_class_name]
            try:
                if isinstance(menu, type):
                    menu = menu()
                nodes = menu.get_nodes(request)
            except NoReverseMatch:
                # Apps might raise NoReverseMatch if an apphook does not yet
                # exist, skip them instead of crashing
                nodes = []
                toolbar = getattr(request, 'toolbar', None)
                if toolbar and toolbar.is_staff:
                    messages.error(request,
                        _('Menu %s cannot be loaded. Please, make sure all '
                          'its urls exist and can be resolved.') %
                        menu_class_name)
                logger.error("Menu %s could not be loaded." %
                    menu_class_name, exc_info=True)
            # nodes is a list of navigation nodes (page tree in cms + others)
            final_nodes += _build_nodes_inner_for_one_menu(
                nodes, menu_class_name)

        cache.set(key, final_nodes, get_cms_setting('CACHE_DURATIONS')['menus'])
        # We need to have a list of the cache keys for languages and sites that
        # span several processes - so we follow the Django way and share through
        # the database. It's still cheaper than recomputing every time!
        # This way we can selectively invalidate per-site and per-language,
        # since the cache shared but the keys aren't
        CacheKey.objects.get_or_create(key=key, language=lang, site=site_id)
        return final_nodes
Ejemplo n.º 24
0
def check_sekizai(output):
    with output.section("Sekizai") as section:
        if is_installed('sekizai'):
            section.success("Sekizai is installed")
        else:
            section.error("Sekizai is not installed, could not find 'sekizai' in INSTALLED_APPS")
        if DJANGO_1_7:
            if 'sekizai.context_processors.sekizai' in settings.TEMPLATE_CONTEXT_PROCESSORS:
                section.success("Sekizai template context processor is installed")
            else:
                section.error("Sekizai template context processor is not installed, could not find 'sekizai.context_processors.sekizai' in TEMPLATE_CONTEXT_PROCESSORS")
        else:
            processors = list(chain(*[template['OPTIONS'].get('context_processors', []) for template in settings.TEMPLATES]))
            if 'sekizai.context_processors.sekizai' in processors:
                section.success("Sekizai template context processor is installed")
            else:
                section.error("Sekizai template context processor is not installed, could not find 'sekizai.context_processors.sekizai' in TEMPLATES option context_processors")

        for template, _ in get_cms_setting('TEMPLATES'):
            if template == constants.TEMPLATE_INHERITANCE_MAGIC:
                continue
            if validate_template(template, ['js', 'css']):
                section.success("Sekizai namespaces 'js' and 'css' found in %r" % template)
            else:
                section.error("Sekizai namespaces 'js' and 'css' not found in %r" % template)
        if section.successful:
            section.finish_success("Sekizai configuration okay")
        else:
            section.finish_error("Sekizai configuration has errors")
Ejemplo n.º 25
0
def check_sekizai(output):
    with output.section("Sekizai") as section:
        sekizai_installed = is_installed('sekizai')

        if sekizai_installed:
            section.success("Sekizai is installed")
        else:
            section.error("Sekizai is not installed, could not find 'sekizai' in INSTALLED_APPS")
        processors = list(
            chain(*[template['OPTIONS'].get('context_processors', []) for template in settings.TEMPLATES]))
        if 'sekizai.context_processors.sekizai' in processors:
            section.success("Sekizai template context processor is installed")
        else:
            section.error("Sekizai template context processor is not installed, could not find "
                          "'sekizai.context_processors.sekizai' in TEMPLATES option context_processors")

        if not sekizai_installed:
            # sekizai is not installed.
            # we can't reliable check templates
            # because template loading won't work
            return

        for template, _ in get_cms_setting('TEMPLATES'):
            if template == constants.TEMPLATE_INHERITANCE_MAGIC:
                continue
            if validate_template(template, ['js', 'css']):
                section.success("Sekizai namespaces 'js' and 'css' found in %r" % template)
            else:
                section.error("Sekizai namespaces 'js' and 'css' not found in %r" % template)
        if section.successful:
            section.finish_success("Sekizai configuration okay")
        else:
            section.finish_error("Sekizai configuration has errors")
Ejemplo n.º 26
0
def _get_placeholder(current_page, page, context, name):
    from django.core.cache import cache
    placeholder_cache = getattr(current_page, '_tmp_placeholders_cache', {})
    if page.pk in placeholder_cache:
        placeholder = placeholder_cache[page.pk].get(name, None)
        if placeholder:
            return placeholder
    placeholder_cache[page.pk] = {}
    placeholders = page.rescan_placeholders().values()
    fetch_placeholders = []
    request = context['request']
    if not get_cms_setting('PLACEHOLDER_CACHE') or (hasattr(request, 'toolbar') and request.toolbar.edit_mode):
        fetch_placeholders = placeholders
    else:
        for placeholder in placeholders:
            cache_key = placeholder.get_cache_key(get_language())
            cached_value = cache.get(cache_key)
            if not cached_value is None:
                restore_sekizai_context(context, cached_value['sekizai'])
                placeholder.content_cache = cached_value['content']
            else:
                fetch_placeholders.append(placeholder)
            placeholder.cache_checked = True
    if fetch_placeholders:
        assign_plugins(context['request'], fetch_placeholders, page.get_template(),  get_language())
    for placeholder in placeholders:
        placeholder_cache[page.pk][placeholder.slot] = placeholder
        placeholder.page = page
    current_page._tmp_placeholders_cache = placeholder_cache
    placeholder = placeholder_cache[page.pk].get(name, None)
    if page.application_urls and not placeholder:
        raise PlaceholderNotFound(
            '"%s" placeholder not found in an apphook application. Please use a static placeholder instead.' % name)
    return placeholder
Ejemplo n.º 27
0
def check_i18n(output):
    with output.section("Internationalization") as section:
        if isinstance(getattr(settings, 'CMS_LANGUAGES', {}), dict):
            section.success("New style CMS_LANGUAGES")
        else:
            section.warn("Old style (tuple based) CMS_LANGUAGES, please switch to the new (dictionary based) style")
        if getattr(settings, 'LANGUAGE_CODE', '').find('_') > -1:
            section.warn("LANGUAGE_CODE must contain a valid language code, not a locale (e.g.: 'en-us' instead of "
                         "'en_US'): '%s' provided" % getattr(settings, 'LANGUAGE_CODE', ''))
        for lang in getattr(settings, 'LANGUAGES', ()):
            if lang[0].find('_') > -1:
                section.warn("LANGUAGES must contain valid language codes, not locales (e.g.: 'en-us' instead of "
                             "'en_US'): '%s' provided" % lang[0])
        if settings.SITE_ID == hash(settings.SITE_ID):
            for site, items in get_cms_setting('LANGUAGES').items():
                if type(site) == int:
                    for lang in items:
                        if lang['code'].find('_') > -1:
                            section.warn("CMS_LANGUAGES entries must contain valid language codes, not locales (e.g.: "
                                         "'en-us' instead of 'en_US'): '%s' provided" % lang['code'])
        else:
            section.error("SITE_ID must be an integer, not %r" % settings.SITE_ID)
        for deprecated in ['CMS_HIDE_UNTRANSLATED', 'CMS_LANGUAGE_FALLBACK', 'CMS_LANGUAGE_CONF', 'CMS_SITE_LANGUAGES',
                           'CMS_FRONTEND_LANGUAGES']:
            if hasattr(settings, deprecated):
                section.warn("Deprecated setting %s found. This setting is now handled in the new style "
                             "CMS_LANGUAGES and can be removed" % deprecated)
Ejemplo n.º 28
0
def get_placeholder_content(context, request, current_page, name, inherit, default):
    from django.core.cache import cache
    edit_mode = getattr(request, 'toolbar', None) and getattr(request.toolbar, 'edit_mode')
    pages = [current_page]
    # don't display inherited plugins in edit mode, so that the user doesn't
    # mistakenly edit/delete them. This is a fix for issue #1303. See the discussion
    # there for possible enhancements
    if inherit and not edit_mode:
        pages = chain([current_page], current_page.get_cached_ancestors(ascending=True))
    for page in pages:
        placeholder = _get_placeholder(current_page, page, context, name)
        if placeholder is None:
            continue
        if not edit_mode and get_cms_setting('PLACEHOLDER_CACHE'):
            if hasattr(placeholder, 'content_cache'):
                return mark_safe(placeholder.content_cache)
            if not hasattr(placeholder, 'cache_checked'):
                cache_key = placeholder.get_cache_key(get_language())
                cached_value = cache.get(cache_key)
                if not cached_value is None:
                    restore_sekizai_context(context, cached_value['sekizai'])
                    return mark_safe(cached_value['content'])
        if not get_plugins(request, placeholder, page.get_template()):
            continue
        content = render_placeholder(placeholder, context, name)
        if content:
            return content
            # if we reach this point, we have an empty or non-existant placeholder
            # call _get_placeholder again to get the placeholder properly rendered
            # in frontend editing
    placeholder = _get_placeholder(current_page, current_page, context, name)
    return render_placeholder(placeholder, context, name, default=default)
Ejemplo n.º 29
0
 def setUp(self):
     self.template = get_cms_setting('TEMPLATES')[0][0]
     self.language = settings.LANGUAGES[0][0]
     self.page = api.create_page('page', self.template, self.language, published=True)
     self.placeholder = self.page.placeholders.all()[0]
     self.superuser = self.create_superuser()
     self.random = Randomness()
Ejemplo n.º 30
0
def _get_cache_key(name, page_lookup, lang, site_id):
    if isinstance(page_lookup, Page):
        page_key = str(page_lookup.pk)
    else:
        page_key = str(page_lookup)
    page_key = _clean_key(page_key)
    return get_cms_setting('CACHE_PREFIX') + name + '__page_lookup:' + page_key + '_site:' + str(site_id) + '_lang:' + str(lang)
Ejemplo n.º 31
0
    def add_structure_mode_item(
        self, extra_classes=('cms-toolbar-item-cms-mode-switcher', )):
        build_mode = self.toolbar.build_mode
        build_url = '?%s' % get_cms_setting('CMS_TOOLBAR_URL__BUILD')
        edit_url = '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')

        if self.request.user.has_perm("cms.use_structure"):
            switcher = self.toolbar.add_button_list(
                'Mode Switcher',
                side=self.toolbar.RIGHT,
                extra_classes=extra_classes)
            switcher.add_button(_('Structure'),
                                build_url,
                                active=build_mode,
                                disabled=False)
            switcher.add_button(_('Content'),
                                edit_url,
                                active=not build_mode,
                                disabled=False)
Ejemplo n.º 32
0
 def test_get_placeholder_cache_version_key(self):
     cache_version_key = '{prefix}|placeholder_cache_version|id:{id}|lang:{lang}|site:{site}'.format(
         prefix=get_cms_setting('CACHE_PREFIX'),
         id=self.placeholder.pk,
         lang='en',
         site=1,
     )
     self.assertEqual(
         _get_placeholder_cache_version_key(self.placeholder, 'en', 1),
         cache_version_key)
Ejemplo n.º 33
0
def set_placeholder_cache(placeholder, lang, content):
    """
    Caches the rendering of a placeholder
    """
    from django.core.cache import cache
    cache.set(_placeholder_cache_key(placeholder, lang),
              content,
              get_cms_setting('CACHE_DURATIONS')['content'],
              version=_get_cache_version())
    _set_cache_version(_get_cache_version())
Ejemplo n.º 34
0
def is_restricted(page, request):
    if get_cms_setting('PERMISSION'):
        if hasattr(page, 'permission_restricted'):
            text = bool(page.permission_restricted)
        else:
            all_perms = list(get_any_page_view_permissions(request, page))
            text = bool(all_perms)
        return text
    else:
        return boolean_icon(None)
Ejemplo n.º 35
0
    def test_invalidate_restart(self):
        # Clear the entire cache for a clean slate
        cache.clear()

        # Ensure that we're testing in an environment WITHOUT the MW cache...
        exclude = [
            'django.middleware.cache.UpdateCacheMiddleware',
            'django.middleware.cache.FetchFromCacheMiddleware'
        ]
        mw_classes = [
            mw for mw in settings.MIDDLEWARE_CLASSES if mw not in exclude
        ]

        with self.settings(MIDDLEWARE_CLASSES=mw_classes):

            # Silly to do these tests if this setting isn't True
            page_cache_setting = get_cms_setting('PAGE_CACHE')
            self.assertTrue(page_cache_setting)

            # Create a test page
            page1 = create_page('test page 1',
                                'nav_playground.html',
                                'en',
                                published=True)

            # Add some content
            placeholder = page1.placeholders.filter(slot="body")[0]
            add_plugin(placeholder, "TextPlugin", 'en', body="English")
            add_plugin(placeholder, "TextPlugin", 'de', body="Deutsch")

            # Create a request object
            request = self.get_request(page1.get_path(), 'en')

            # Ensure that user is NOT authenticated
            self.assertFalse(request.user.is_authenticated())

            # Test that the page is initially uncached
            with self.assertNumQueries(FuzzyInt(1, 20)):
                response = self.client.get('/en/')
            self.assertEqual(response.status_code, 200)

            #
            # Test that subsequent requests of the same page are cached by
            # asserting that they require fewer queries.
            #
            with self.assertNumQueries(0):
                response = self.client.get('/en/')
            self.assertEqual(response.status_code, 200)
            old_plugins = plugin_pool.plugins
            plugin_pool.clear()
            plugin_pool.discover_plugins()
            plugin_pool.plugins = old_plugins
            with self.assertNumQueries(FuzzyInt(1, 20)):
                response = self.client.get('/en/')
                self.assertEqual(response.status_code, 200)
Ejemplo n.º 36
0
    def test_get_placeholder_cache_key(self):
        version, vary_on_list = _get_placeholder_cache_version(
            self.placeholder, 'en', 1)
        desired_key = '{prefix}|render_placeholder|id:{id}|lang:{lang}|site:{site}|tz:{tz}|v:{version}|country-code:{cc}'.format(  # noqa
            prefix=get_cms_setting('CACHE_PREFIX'),
            id=self.placeholder.pk,
            lang='en',
            site=1,
            tz=get_timezone_name(),
            version=version,
            cc='_',
        )
        _set_placeholder_cache_version(self.placeholder,
                                       'en',
                                       1,
                                       version,
                                       vary_on_list=vary_on_list,
                                       duration=1)
        actual_key = _get_placeholder_cache_key(self.placeholder, 'en', 1,
                                                self.en_request)
        self.assertEqual(actual_key, desired_key)

        en_key = _get_placeholder_cache_key(self.placeholder, 'en', 1,
                                            self.en_request)
        de_key = _get_placeholder_cache_key(self.placeholder, 'de', 1,
                                            self.de_request)
        self.assertNotEqual(en_key, de_key)

        en_us_key = _get_placeholder_cache_key(self.placeholder, 'en', 1,
                                               self.en_us_request)
        self.assertNotEqual(en_key, en_us_key)

        desired_key = '{prefix}|render_placeholder|id:{id}|lang:{lang}|site:{site}|tz:{tz}|v:{version}|country-code:{cc}'.format(  # noqa
            prefix=get_cms_setting('CACHE_PREFIX'),
            id=self.placeholder.pk,
            lang='en',
            site=1,
            tz=get_timezone_name(),
            version=version,
            cc='US',
        )
        self.assertEqual(en_us_key, desired_key)
Ejemplo n.º 37
0
    def add_admin_menu(self):
        admin_menu = self.toolbar.get_or_create_menu(ADMIN_MENU_IDENTIFIER,
                                                     self.current_site.name)

        # Users button
        self.add_users_button(admin_menu)

        # sites menu
        if get_cms_setting('PERMISSION'):
            sites_queryset = get_user_sites_queryset(self.request.user)
        else:
            sites_queryset = Site.objects.all()

        if len(sites_queryset) > 1:
            sites_menu = admin_menu.get_or_create_menu('sites', _('Sites'))
            sites_menu.add_sideframe_item(
                _('Admin Sites'), url=admin_reverse('sites_site_changelist'))
            sites_menu.add_break(ADMIN_SITES_BREAK)
            for site in sites_queryset:
                sites_menu.add_link_item(
                    site.name,
                    url='http://%s' % site.domain,
                    active=site.pk == self.current_site.pk)

        # admin
        admin_menu.add_sideframe_item(_('Administration'),
                                      url=admin_reverse('index'))
        admin_menu.add_break(ADMINISTRATION_BREAK)

        # cms users
        admin_menu.add_sideframe_item(
            _('User settings'), url=admin_reverse('cms_usersettings_change'))
        admin_menu.add_break(USER_SETTINGS_BREAK)

        # Disable toolbar
        admin_menu.add_link_item(_('Disable toolbar'),
                                 url='?%s' %
                                 get_cms_setting('CMS_TOOLBAR_URL__DISABLE'))
        admin_menu.add_break(TOOLBAR_DISABLE_BREAK)

        # logout
        self.add_logout_button(admin_menu)
Ejemplo n.º 38
0
def set_permission_cache(user, key, value):
    """
    Helper method for storing values in cache. Stores used keys so
    all of them can be cleaned when clean_permission_cache gets called.
    """
    from django.core.cache import cache
    # store this key, so we can clean it when required
    cache_key = get_cache_key(user, key)
    cache.set(cache_key, value,
              get_cms_setting('CACHE_DURATIONS')['permissions'],
              version=get_cache_permission_version())
Ejemplo n.º 39
0
    def test_templates(self):
        """
        Test the inheritance magic for templates
        """
        parent = create_page("parent", "nav_playground.html", "en")
        child = create_page("child", "nav_playground.html", "en", parent=parent)
        grand_child = create_page("grand child", "nav_playground.html", "en", parent=child)
        child2 = create_page("child2", "col_two.html", "en", parent=parent)
        grand_child2 = create_page("grand child2", "nav_playground.html", "en", parent=child2)
        child.template = constants.TEMPLATE_INHERITANCE_MAGIC
        grand_child.template = constants.TEMPLATE_INHERITANCE_MAGIC
        child.save()
        grand_child.save()
        grand_child2.template = constants.TEMPLATE_INHERITANCE_MAGIC
        grand_child2.save()

        # kill template cache
        delattr(grand_child, '_template_cache')
        with self.assertNumQueries(1):
            self.assertEqual(child.template, constants.TEMPLATE_INHERITANCE_MAGIC)
            self.assertEqual(parent.get_template_name(), grand_child.get_template_name())

        # test template cache
        with self.assertNumQueries(0):
            grand_child.get_template()

        # kill template cache
        delattr(grand_child2, '_template_cache')
        with self.assertNumQueries(1):
            self.assertEqual(child2.template, 'col_two.html')
            self.assertEqual(child2.get_template_name(), grand_child2.get_template_name())

        # test template cache
        with self.assertNumQueries(0):
            grand_child2.get_template()

        parent.template = constants.TEMPLATE_INHERITANCE_MAGIC
        parent.save()
        self.assertEqual(parent.template, constants.TEMPLATE_INHERITANCE_MAGIC)
        self.assertEqual(parent.get_template(), get_cms_setting('TEMPLATES')[0][0])
        self.assertEqual(parent.get_template_name(), get_cms_setting('TEMPLATES')[0][1])
Ejemplo n.º 40
0
    def setUp(self):
        # prepare root page
        self.template = get_cms_setting('TEMPLATES')[0][0]
        self.language = settings.LANGUAGES[0][0]
        self.root_page = api.create_page(
            'root page', self.template, self.language, published=True)

        # create translations for all languages
        for language, _ in settings.LANGUAGES[1:]:
            api.create_title(
                language, self.root_page.get_slug(), self.root_page)
            self.root_page.publish(language)
Ejemplo n.º 41
0
 def setUp(self):
     self.template = get_cms_setting('TEMPLATES')[0][0]
     self.language = settings.LANGUAGES[0][0]
     self.page = api.create_page('page',
                                 self.template,
                                 self.language,
                                 published=True)
     api.create_title('de', 'page de', self.page)
     self.page.publish('de')
     self.placeholder = self.page.placeholders.all()[0]
     self.superuser = self.create_superuser()
     super(DefaultSetupMixin, self).setUp()
Ejemplo n.º 42
0
    def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
        """
        We just need the popup interface here
        """
        context.update({
            'preview': not "no_preview" in request.GET,
            'is_popup': True,
            'plugin': self.cms_plugin_instance,
            'CMS_MEDIA_URL': get_cms_setting('MEDIA_URL'),
        })

        return super(CMSPluginBase, self).render_change_form(request, context, add, change, form_url, obj)
    def add_admin_menu(self):
        if not self._admin_menu:
            self._admin_menu = self.toolbar.get_or_create_menu(
                ADMIN_MENU_IDENTIFIER, self.current_site.name)
            # Users button
            self.add_users_button(self._admin_menu)

            # sites menu
            sites_queryset = get_user_sites_queryset(self.request.user)

            if len(sites_queryset) > 1:
                sites_menu = self._admin_menu.get_or_create_menu(
                    'sites', _('Sites'))
                sites_menu.add_sideframe_item(
                    _('Admin Sites'),
                    url=admin_reverse('sites_site_changelist'))
                sites_menu.add_break(ADMIN_SITES_BREAK)
                for site in sites_queryset:
                    sites_menu.add_link_item(
                        site.name,
                        url='http://%s' % site.domain,
                        active=site.pk == self.current_site.pk)

            # admin
            self._admin_menu.add_sideframe_item(_('Administration'),
                                                url=admin_reverse('index'))
            self._admin_menu.add_break(ADMINISTRATION_BREAK)

            # clipboard
            if self.toolbar.edit_mode or self.toolbar.build_mode:
                # True if the clipboard exists and there's plugins in it.
                clipboard_is_bound = self.get_clipboard_plugins().exists()

                self._admin_menu.add_link_item(
                    _('Clipboard...'),
                    url='#',
                    extra_classes=['cms-clipboard-trigger'],
                    disabled=not clipboard_is_bound)
                self._admin_menu.add_link_item(
                    _('Clear clipboard'),
                    url='#',
                    extra_classes=['cms-clipboard-empty'],
                    disabled=not clipboard_is_bound)
                self._admin_menu.add_break(CLIPBOARD_BREAK)

            # Disable toolbar
            self._admin_menu.add_link_item(
                _('Disable toolbar'),
                url='?%s' % get_cms_setting('CMS_TOOLBAR_URL__DISABLE'))
            self._admin_menu.add_break(TOOLBAR_DISABLE_BREAK)

            # logout
            self.add_logout_button(self._admin_menu)
Ejemplo n.º 44
0
def _set_cache_version(version):
    '''
    Set the cache version to the specified value.
    '''

    from django.core.cache import cache

    cache.set(
        CMS_PAGE_CACHE_VERSION_KEY,
        version,
        get_cms_setting('CACHE_DURATIONS')['content']
    )
Ejemplo n.º 45
0
def _get_placeholder_cache_key(placeholder,
                               lang,
                               site_id,
                               request,
                               soft=False):
    """
    Returns the fully-addressed cache key for the given placeholder and
    the request.

    The kwarg «soft» should be set to True if getting the cache key to then
    read from the cache. If instead the key retrieval is to support a cache
    write, let «soft» be False.
    """
    prefix = get_cms_setting('CACHE_PREFIX')
    version, vary_on_list = _get_placeholder_cache_version(
        placeholder, lang, site_id)
    main_key = '{prefix}|render_placeholder|id:{id}|lang:{lang}|site:{site}|tz:{tz}|v:{version}'.format(
        prefix=prefix,
        id=placeholder.pk,
        lang=lang,
        site=site_id,
        tz=get_timezone_name(),
        version=version,
    )

    if not soft:
        # We are about to write to the cache, so we want to get the latest
        # vary_cache_on headers and the correct cache expiration, ignoring any
        # we already have. If the placeholder has already been rendered, this
        # will be very efficient (zero-additional queries) due to the caching
        # of all its plugins during the rendering process anyway.
        vary_on_list = placeholder.get_vary_cache_on(request)
        duration = placeholder.get_cache_expiration(request, now())
        # Update the main placeholder cache version
        _set_placeholder_cache_version(placeholder, lang, site_id, version,
                                       vary_on_list, duration)

    sub_key_list = []
    for key in vary_on_list:
        value = request.META.get(get_header_name(key)) or '_'
        sub_key_list.append(key + ':' + value)

    cache_key = main_key
    if sub_key_list:
        cache_key += '|' + '|'.join(sub_key_list)

    if len(cache_key) > 250:
        cache_key = '{prefix}|{hash}'.format(
            prefix=prefix,
            hash=hashlib.sha1(cache_key.encode('utf-8')).hexdigest(),
        )

    return cache_key
Ejemplo n.º 46
0
    def test_site_publish(self):
        self._login_context.__exit__(None, None, None)
        pages = {"2": list(range(0, 5)), "3": list(range(0, 5))}
        lang_settings = copy.deepcopy(get_cms_setting('LANGUAGES'))
        lang_settings[3][1]['public'] = True

        with self.settings(CMS_LANGUAGES=lang_settings, LANGUAGE_CODE="de"):
            with self.settings(SITE_ID=self.site2.pk):
                pages["2"][0] = create_page("page_2", "nav_playground.html", "de",
                                            site=self.site2)
                pages["2"][0].publish('de')
                pages["2"][1] = create_page("page_2_1", "nav_playground.html", "de",
                                            parent=pages["2"][0], site=self.site2)
                pages["2"][2] = create_page("page_2_2", "nav_playground.html", "de",
                                            parent=pages["2"][0], site=self.site2)
                pages["2"][3] = create_page("page_2_1_1", "nav_playground.html", "de",
                                            parent=pages["2"][1], site=self.site2)
                pages["2"][4] = create_page("page_2_1_2", "nav_playground.html", "de",
                                            parent=pages["2"][1], site=self.site2)

                for page in pages["2"]:
                    page.publish('de')
                for page in pages["2"]:
                    if page.is_home:
                        page_url = "/de/"
                    else:
                        page_url = page.get_absolute_url(language='de')
                    response = self.client.get(page_url)
                    self.assertEqual(response.status_code, 200)

            with self.settings(SITE_ID=self.site3.pk):
                pages["3"][0] = create_page("page_3", "nav_playground.html", "de",
                                            site=self.site3)
                pages["3"][0].publish('de')
                pages["3"][1] = create_page("page_3_1", "nav_playground.html", "de",
                                            parent=pages["3"][0], site=self.site3)
                pages["3"][2] = create_page("page_3_2", "nav_playground.html", "de",
                                            parent=pages["3"][0], site=self.site3)
                pages["3"][3] = create_page("page_3_1_1", "nav_playground.html", "de",
                                            parent=pages["3"][1], site=self.site3)
                pages["3"][4] = create_page("page_3_1_2", "nav_playground.html", "de",
                                            parent=pages["3"][1], site=self.site3)

                for page in pages["3"]:
                    page.publish('de')
                for page in pages["3"]:
                    if page.is_home:
                        page_url = "/de/"
                    else:
                        page_url = page.get_absolute_url(language='de')
                    response = self.client.get(page_url)
                    self.assertEqual(response.status_code, 200)
Ejemplo n.º 47
0
 def test_wrong_plugin_language(self):
     page = create_page("page", "nav_playground.html", "en", published=True)
     ph_en = page.placeholders.get(slot="body")
     add_plugin(ph_en, "TextPlugin", "en", body="I'm the first")
     title = Title(title="page", slug="page", language="ru", page=page)
     title.save()
     # add wrong plugin language
     add_plugin(ph_en, "TextPlugin", "ru", body="I'm the second")
     page.publish('en')
     superuser = self.get_superuser()
     with self.login_user_context(superuser):
         response = self.client.get('/en/?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON'))
         self.assertEqual(response.status_code, 200)
Ejemplo n.º 48
0
 def has_page_change_permission(self):
     if not hasattr(self, 'page_change_permission'):
         if not self.page and not get_cms_setting('PERMISSION'):
             # We can't check permissions for an individual page
             # and can't check global cms permissions because
             # user opted out of them.
             # So just check django auth permissions.
             user = self.request.user
             can_change = has_auth_page_permission(user, action='change')
         else:
             can_change = can_change_page(self.request)
         self.page_change_permission = can_change
     return self.page_change_permission
Ejemplo n.º 49
0
 def setUp(self):
     self.template = get_cms_setting('TEMPLATES')[0][0]
     self.language = settings.LANGUAGES[0][0]
     self.page = api.create_page('page',
                                 self.template,
                                 self.language,
                                 published=True,
                                 apphook='BlogApp',
                                 apphook_namespace='Blog')
     api.create_title('fr', 'french page', self.page)
     self.page.publish('fr')
     self.placeholder = self.page.placeholders.all()[0]
     self.user = User.objects.create(first_name='Peter', last_name='Muster')
Ejemplo n.º 50
0
 def test_language_fallback(self):
     """
     Test language fallbacks in details view
     """
     from cms.views import details
     p1 = create_page("page", "nav_playground.html", "en", published=True)
     request = self.get_request('/de/', 'de')
     response = details(request, p1.get_path())
     self.assertEqual(response.status_code, 302)
     self.assertEqual(response['Location'], '/en/')
     lang_settings = copy.deepcopy(get_cms_setting('LANGUAGES'))
     lang_settings[1][0]['fallbacks'] = []
     lang_settings[1][1]['fallbacks'] = []
     with self.settings(CMS_LANGUAGES=lang_settings):
         response = self.client.get("/de/")
         self.assertEqual(response.status_code, 404)
     lang_settings = copy.deepcopy(get_cms_setting('LANGUAGES'))
     lang_settings[1][0]['redirect_on_fallback'] = False
     lang_settings[1][1]['redirect_on_fallback'] = False
     with self.settings(CMS_LANGUAGES=lang_settings):
         response = self.client.get("/de/")
         self.assertEqual(response.status_code, 302)
Ejemplo n.º 51
0
    def populate(self):
        # always use draft if we have a page
        self.page = get_page_draft(self.request.current_page)
        if not self.page:
            # Nothing to do
            return

        # check global permissions if CMS_PERMISSIONS is active
        if get_cms_setting('PERMISSION'):
            if not has_page_change_permission:
                has_global_current_page_change_permission = has_page_permission(
                    self.request.user, self.request.current_page, 'change'
                )
            else:
                has_global_current_page_change_permission = has_page_change_permission(
                    self.request
                )
        else:
            has_global_current_page_change_permission = False
            # check if user has page edit permission
        if not has_page_change_permission:
            can_change = (self.request.current_page and
                          self.request.current_page.has_change_permission(self.request.user))
        else:
            can_change = (self.request.current_page and
                          self.request.current_page.has_change_permission(self.request))
        if has_global_current_page_change_permission or can_change:
            not_edit_mode = not self.toolbar.edit_mode
            current_page_menu = self.toolbar.get_or_create_menu('page')
            position = current_page_menu.find_first(
                Break, identifier=PAGE_MENU_THIRD_BREAK) - 1
            # Page tags
            try:
                page_extension = PageSitemapProperties.objects.get(extended_object_id=self.page.pk)
            except PageSitemapProperties.DoesNotExist:
                page_extension = None
            try:
                if page_extension:
                    url = reverse('admin:djangocms_page_sitemap_pagesitemapproperties_change',
                                  args=(page_extension.pk,))
                else:
                    url = "%s?extended_object=%s" % (
                        reverse('admin:djangocms_page_sitemap_pagesitemapproperties_add'),
                        self.page.pk)
            except NoReverseMatch:  # pragma: no cover
                # not in urls
                pass
            else:
                current_page_menu.add_modal_item(PAGE_SITEMAP_MENU_TITLE,
                                                 url=url, disabled=not_edit_mode,
                                                 position=position)
Ejemplo n.º 52
0
    def test_untranslated_language_url(self):
        """ Tests page_language_url templatetag behavior when used on a page
          without the requested translation, both when CMS_HIDE_UNTRANSLATED is
          True and False.
          When True it should return the root page URL if the current page is
           untranslated (PR #1125)

        """
        page_1 = create_page('Page 1', 'nav_playground.html', 'en', published=True,
                             in_navigation=True, reverse_id='page1')
        create_title("de", "Seite 1", page_1, slug="seite-1")
        page_1.publish('en')
        page_1.publish('de')
        page_2 = create_page('Page 2', 'nav_playground.html', 'en', page_1, published=True,
                             in_navigation=True, reverse_id='page2')
        create_title("de", "Seite 2", page_2, slug="seite-2")
        page_2.publish('en')
        page_2.publish('de')
        page_3 = create_page('Page 3', 'nav_playground.html', 'en', page_2, published=True,
                             in_navigation=True, reverse_id='page3')
        tpl = "{% load menu_tags %}{% page_language_url 'de' %}"
        lang_settings = deepcopy(get_cms_setting('LANGUAGES'))
        lang_settings[1][1]['hide_untranslated'] = False
        with self.settings(CMS_LANGUAGES=lang_settings):
            context = self.get_context(page_2.get_absolute_url())
            context['request'].current_page = page_2
            res = self.render_template_obj(tpl, context.__dict__, context['request'])
            self.assertEqual(res, "/de/seite-2/")

            # Default configuration has CMS_HIDE_UNTRANSLATED=False
            context = self.get_context(page_2.get_absolute_url())
            context['request'].current_page = page_2.publisher_public
            res = self.render_template_obj(tpl, context.__dict__, context['request'])
            self.assertEqual(res, "/de/seite-2/")

            context = self.get_context(page_3.get_absolute_url())
            context['request'].current_page = page_3.publisher_public
            res = self.render_template_obj(tpl, context.__dict__, context['request'])
            self.assertEqual(res, "/de/page-3/")
        lang_settings[1][1]['hide_untranslated'] = True

        with self.settings(CMS_LANGUAGES=lang_settings):
            context = self.get_context(page_2.get_absolute_url())
            context['request'].current_page = page_2.publisher_public
            res = self.render_template_obj(tpl, context.__dict__, context['request'])
            self.assertEqual(res, "/de/seite-2/")

            context = self.get_context(page_3.get_absolute_url())
            context['request'].current_page = page_3.publisher_public
            res = self.render_template_obj(tpl, context.__dict__, context['request'])
            self.assertEqual(res, "/de/")
Ejemplo n.º 53
0
    def setUp(self):
        self.template = get_cms_setting('TEMPLATES')[0][0]
        self.language = settings.LANGUAGES[0][0]
        self.page = api.create_page('page',
                                    self.template,
                                    self.language,
                                    published=True)
        self.placeholder = self.page.placeholders.all()[0]
        self.superuser = self.create_superuser()

        self.img = create_image()
        self.image_name = 'test_file.jpg'
        self.filename = os.path.join(settings.MEDIA_ROOT, self.image_name)
        self.img.save(self.filename, 'JPEG')
Ejemplo n.º 54
0
 def test_site_preview(self):
     page = create_page("page",
                        "nav_playground.html",
                        "de",
                        site=self.site2,
                        published=True)
     with self.login_user_context(self.get_superuser()):
         response = self.client.get(
             admin_reverse('cms_page_preview_page', args=[page.pk, 'de']))
         self.assertEqual(response.status_code, 302)
         self.assertEqual(
             response._headers['location'][1],
             'http://sample2.com/de/?%s&language=de' %
             get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON'))
Ejemplo n.º 55
0
    def get_page_request(self, page, user, path=None, edit=False, lang_code='en', disable=False):
        path = path or page and page.get_absolute_url()
        if edit:
            path += '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')
        request = RequestFactory().get(path)
        request.session = {}
        request.user = user
        request.LANGUAGE_CODE = lang_code
        request.GET = request.GET.copy()

        if edit:
            request.GET['edit'] = None
        else:
            request.GET['edit_off'] = None

        if disable:
            request.GET[get_cms_setting('CMS_TOOLBAR_URL__DISABLE')] = None
        request.current_page = page
        mid = ToolbarMiddleware()
        mid.process_request(request)
        if hasattr(request, 'toolbar'):
            request.toolbar.populate()
        return request
Ejemplo n.º 56
0
def _show_placeholder_for_page(context, placeholder_name, page_lookup, lang=None,
                               site=None, cache_result=True):
    """
    Shows the content of a page with a placeholder name and given lookup
    arguments in the given language.
    This is useful if you want to have some more or less static content that is
    shared among many pages, such as a footer.

    See _get_page_by_untyped_arg() for detailed information on the allowed types
    and their interpretation for the page_lookup argument.
    """
    validate_placeholder_name(placeholder_name)

    request = context.get('request', False)
    site_id = get_site_id(site)

    if not request:
        return {'content': ''}
    if lang is None:
        lang = get_language_from_request(request)

    if cache_result:
        base_key = _get_cache_key('_show_placeholder_for_page', page_lookup, lang, site_id)
        cache_key = _clean_key('%s_placeholder:%s' % (base_key, placeholder_name))
        cached_value = cache.get(cache_key)
        if isinstance(cached_value, dict): # new style
            _restore_sekizai(context, cached_value['sekizai'])
            return {'content': mark_safe(cached_value['content'])}
        elif isinstance(cached_value, basestring): # old style
            return {'content': mark_safe(cached_value)}

    page = _get_page_by_untyped_arg(page_lookup, request, site_id)
    if not page:
        return {'content': ''}
    try:
        placeholder = page.placeholders.get(slot=placeholder_name)
    except PlaceholderModel.DoesNotExist:
        if settings.DEBUG:
            raise
        return {'content': ''}
    watcher = Watcher(context)
    content = render_placeholder(placeholder, context, placeholder_name)
    changes = watcher.get_changes()
    if cache_result:
        cache.set(cache_key, {'content': content, 'sekizai': changes}, get_cms_setting('CACHE_DURATIONS')['content'])

    if content:
        return {'content': mark_safe(content)}
    return {'content': ''}
Ejemplo n.º 57
0
def _get_cache_key(request):
    #md5 key of current path
    cache_key = "%s:%d:%s" % (
        get_cms_setting("CACHE_PREFIX"), settings.SITE_ID,
        hashlib.md5(iri_to_uri(
            request.get_full_path()).encode('utf-8')).hexdigest())
    if settings.USE_TZ:
        # The datetime module doesn't restrict the output of tzname().
        # Windows is known to use non-standard, locale-dependant names.
        # User-defined tzinfo classes may return absolutely anything.
        # Hence this paranoid conversion to create a valid cache key.
        tz_name = force_text(get_current_timezone_name(), errors='ignore')
        cache_key += '.%s' % tz_name.encode(
            'ascii', 'ignore').decode('ascii').replace(' ', '_')
    return cache_key
Ejemplo n.º 58
0
    def test_custom_templates_loading(self):
        """
        Checking that templates can be loaded by the template loader
        """
        templates = get_cms_setting('TEMPLATES')
        for template in templates:
            if template[0] != constants.TEMPLATE_INHERITANCE_MAGIC:
                tpl = loader.get_template(template[0])

                if DJANGO_1_7:
                    tpl_name = tpl.name
                else:
                    tpl_name = tpl.template.name

                self.assertEqual(tpl_name, template[0])
Ejemplo n.º 59
0
def has_page_change_permission(request):
    """
    Return true if the current user has permission to change this page.
    To be granted this permission, you need the cms.change_page permission.
    In addition, if CMS_PERMISSION is enabled you also need to either have
    global can_change permission or just on this page.
    """
    from cms.utils.plugins import current_site
    opts = Page._meta
    return request.user.is_superuser or (
        request.user.has_perm(opts.app_label + '.' +
                              opts.get_change_permission()) and
        (not get_cms_setting('PERMISSION') or has_global_page_permission(
            request, current_site(request), can_change=True)
         or has_any_page_change_permissions(request)))
Ejemplo n.º 60
0
def is_restricted(page, request):
    if get_cms_setting('PERMISSION'):
        if hasattr(page, 'permission_restricted'):
            icon = boolean_icon(bool(page.permission_restricted))
        else:
            all_perms = list(get_any_page_view_permissions(request, page))
            icon = boolean_icon(bool(all_perms))
        return mark_safe(ugettext('<span>%(icon)s</span>') % {
            'icon': icon,
        })
    else:
        icon = boolean_icon(None)
        return mark_safe(ugettext('<span>%(icon)s</span>') % {
            'icon': icon,
        })