Example #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)
Example #2
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
Example #3
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)
Example #4
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)
Example #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])
Example #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)
Example #7
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)
Example #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
Example #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
Example #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))
Example #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')
Example #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)
Example #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
Example #14
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")
Example #15
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
Example #16
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 ''
Example #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')
Example #18
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
Example #19
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)
Example #20
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'])
Example #21
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)
Example #22
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)
Example #23
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
Example #24
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)
Example #25
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())
Example #26
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)
Example #27
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
Example #28
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()
Example #29
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")
Example #30
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)