Example #1
0
    def handle(self, *args, **options):
        verbose = options.get('verbosity') > 1
        only_empty = options.get('only_empty')
        copy_content = options.get('copy_content')
        from_lang = options.get('from_lang')
        to_lang = options.get('to_lang')
        try:
            site = int(options.get('site', None))
        except Exception:
            site = settings.SITE_ID

        try:
            assert from_lang in get_language_list(site)
            assert to_lang in get_language_list(site)
        except AssertionError:
            raise CommandError('Both languages have to be present in settings.LANGUAGES and settings.CMS_LANGUAGES')

        for page in Page.objects.on_site(site).drafts():
            # copy title
            if from_lang in page.get_languages():

                title = page.get_title_obj(to_lang, fallback=False)
                if isinstance(title, EmptyTitle):
                    title = page.get_title_obj(from_lang)
                    if verbose:
                        self.stdout.write('copying title %s from language %s\n' % (title.title, from_lang))
                    title.id = None
                    title.publisher_public_id = None
                    title.publisher_state = 0
                    title.language = to_lang
                    title.save()
                if copy_content:
                    # copy plugins using API
                    if verbose:
                        self.stdout.write('copying plugins for %s from %s\n' % (page.get_page_title(from_lang), from_lang))
                    copy_plugins_to_language(page, from_lang, to_lang, only_empty)
            else:
                if verbose:
                    self.stdout.write('Skipping page %s, language %s not defined\n' % (page.get_page_title(page.get_languages()[0]), from_lang))

        if copy_content:
            for static_placeholder in StaticPlaceholder.objects.all():
                plugin_list = []
                for plugin in static_placeholder.draft.get_plugins():
                    if plugin.language == from_lang:
                        plugin_list.append(plugin)

                if plugin_list:
                    if verbose:
                        self.stdout.write(
                            'copying plugins from static_placeholder "%s" in "%s" to "%s"\n' % (
                                static_placeholder.name, from_lang, to_lang)
                        )
                    copy_plugins_to(plugin_list, static_placeholder.draft, to_lang)

        self.stdout.write('all done')
Example #2
0
    def test_setup_filled(self):

        # Tests starts with no page and no config
        self.assertFalse(Page.objects.exists())
        self.assertFalse(BlogConfig.objects.exists())

        langs = get_language_list()
        home = None
        for lang in langs:
            with override(lang):
                if not home:
                    home = create_page(
                        'a new home', language=lang,
                        template='blog.html', in_navigation=True, published=True
                    )
                else:
                    create_title(
                        language=lang, title='a new home', page=home
                    )
                    home.publish(lang)

        # importing cms_app triggers the auto setup
        from djangocms_blog import cms_app  # NOQA

        # Home and blog, published and draft
        self.assertEqual(Page.objects.count(), 4)
        self.assertEqual(BlogConfig.objects.count(), 1)

        home = Page.objects.get_home()
        for lang in langs:
            self.assertEqual(home.get_title(lang), 'a new home')
    def _setup_filled(self, site_id=1, home_final=4, blog_final=2, configs_final=1, configs_init=0, pages_init=0):
        site = Site.objects.get(pk=site_id)

        # Tests starts with a set of pages / configs
        self.assertEqual(Page.objects.count(), pages_init)
        if self.config:
            self.assertEqual(self.config.objects.count(), configs_init)
        self.assertEqual(Page.objects.filter(application_urls=self.app_name).count(), configs_init * 2)

        langs = get_language_list()
        home = None
        for lang in langs:
            with override(lang):
                if not home:
                    home = create_page(
                        "a new home", language=lang, site=site, template="page.html", in_navigation=True, published=True
                    )
                else:
                    create_title(language=lang, title="a new home", page=home)
                    home.publish(lang)

        # importing cms_app triggers the auto setup
        __import__(self.module, fromlist=(str("cms_app"),))

        # Final set of pages / configs
        self.assertEqual(Page.objects.count(), home_final)
        if self.config:
            self.assertEqual(self.config.objects.count(), configs_final)
        self.assertEqual(Page.objects.filter(application_urls=self.app_name).count(), blog_final)

        home = Page.objects.get_home(site)
        for lang in langs:
            self.assertEqual(home.get_title(), "a new home")
    def populate(self):
        # setup the extension toolbar with permissions and sanity checks
        current_page_menu = self._setup_extension_toolbar()

        # if it's all ok
        if current_page_menu and self.toolbar.edit_mode:
            # create a sub menu labelled "Workflows" at position 1 in the menu
            sub_menu = self._get_sub_menu(current_page_menu,
                                          'submenu_label',
                                          _('Workflow'),
                                          position=1)

            # retrieves the instances of the current title extension (if any) and the toolbar item URL
            urls = self.get_title_extension_admin()

            # we now also need to get the title set (i.e. different language titles) for this page
            page = self._get_page()
            titles = page.title_set.filter(
                language__in=get_language_list(page.site_id))

            # cycle through the list
            for (title_extension, url), title in zip(urls, titles):

                # adds toolbar items
                sub_menu.add_modal_item(_('for "{title}" ({lang})').format(
                    title=title.title, lang=title.language),
                                        url=url,
                                        disabled=not self.toolbar.edit_mode)
Example #5
0
    def setUpClass(cls):
        from django.contrib.sites.models import Site
        cls.request_factory = RequestFactory()
        cls.user = create_user(cls._admin_user_username,
                               cls._admin_user_email,
                               cls._admin_user_password,
                               is_staff=True,
                               is_superuser=True)
        cls.user_staff = create_user(cls._staff_user_username,
                                     cls._staff_user_email,
                                     cls._staff_user_password,
                                     is_staff=True,
                                     is_superuser=False)
        cls.user_normal = create_user(cls._user_user_username,
                                      cls._user_user_email,
                                      cls._user_user_password,
                                      is_staff=False,
                                      is_superuser=False)
        cls.site_1 = Site.objects.all().first()

        try:
            from cms.utils import get_language_list
            cls.languages = get_language_list()
        except ImportError:
            cls.languages = [x[0] for x in settings.LANGUAGES]
        super(BaseTestCaseMixin, cls).setUpClass()
Example #6
0
def render_admin_menu_item(request,
                           page,
                           template=None,
                           language=None,
                           open_nodes=()):
    """
    Renders requested page item for the tree. This is used in case when item
    must be reloaded over ajax.
    """
    if not template:
        template = "admin/cms/page/tree/menu_fragment.html"

    if not page.pk:
        # Not found - tree will remove item
        return HttpResponse(NOT_FOUND_RESPONSE)

    # languages
    from cms.utils import permissions
    languages = get_language_list(page.site_id)
    context = {
        'has_add_permission':
        permissions.has_page_add_permission_from_request(request),
        'site_languages':
        languages,
        'open_nodes':
        open_nodes,
    }
    filtered = 'filtered' in request.GET or 'filtered' in request.POST
    context.update(
        get_admin_menu_item_context(request, page, filtered, language))
    return render_to_string(template, context)
Example #7
0
    def test_setup_filled(self):

        # Tests starts with no page and no config
        self.assertFalse(Page.objects.exists())
        self.assertFalse(BlogConfig.objects.exists())

        langs = get_language_list()
        home = None
        for lang in langs:
            with override(lang):
                if not home:
                    home = create_page('a new home',
                                       language=lang,
                                       template='blog.html',
                                       in_navigation=True,
                                       published=True)
                else:
                    create_title(language=lang, title='a new home', page=home)
                    home.publish(lang)

        # importing cms_app triggers the auto setup
        from djangocms_blog import cms_app  # NOQA

        # Home and blog, published and draft
        self.assertEqual(Page.objects.count(), 4)
        self.assertEqual(BlogConfig.objects.count(), 1)

        home = Page.objects.get_home()
        for lang in langs:
            self.assertEqual(home.get_title(lang), 'a new home')
Example #8
0
def render_admin_menu_item(request, page, template=None):
    """
    Renders requested page item for the tree. This is used in case when item
    must be reloaded over ajax.
    """
    if not template:
        template = "admin/cms/page/menu_fragment.html"

    if not page.pk:
        return HttpResponse(
            NOT_FOUND_RESPONSE)  # Not found - tree will remove item

    # languages
    languages = get_language_list(page.site_id)
    context = RequestContext(
        request, {
            'has_add_permission': permissions.has_page_add_permission(request),
            'site_languages': languages,
        })

    filtered = 'filtered' in request.REQUEST
    context.update(get_admin_menu_item_context(request, page, filtered))
    # add mimetype to help out IE
    return render_to_response(template,
                              context,
                              mimetype="text/html; charset=utf-8")
Example #9
0
def render_admin_menu_item(request, page, template=None, language=None):
    """
    Renders requested page item for the tree. This is used in case when item
    must be reloaded over ajax.
    """
    if not template:
        template = "admin/cms/page/tree/menu_fragment.html"

    if not page.pk:
        return HttpResponse(NOT_FOUND_RESPONSE) # Not found - tree will remove item

    # languages
    from cms.utils import permissions
    languages = get_language_list(page.site_id)
    context = RequestContext(request, {
        'has_add_permission': permissions.has_page_add_permission(request),
        'site_languages': languages,
    })

    filtered = 'filtered' in request.REQUEST
    context.update(get_admin_menu_item_context(request, page, filtered, language))
    # add mimetype to help out IE
    if DJANGO_1_4:
        return render_to_response(template, context, mimetype="text/html; charset=utf-8")
    else:
        return render_to_response(template, context, content_type="text/html; charset=utf-8")
Example #10
0
    def populate(self):
        # setup the extension toolbar with permissions and sanity checks
        current_page_menu = self._setup_extension_toolbar()

        # if it's all ok
        if current_page_menu and self.toolbar.edit_mode_active:
            # create a sub menu labelled "Ratings" at position 1 in the menu
            sub_menu = self._get_sub_menu(
                current_page_menu, 'submenu_label', 'MSEO', position=1
            )

            # retrieves the instances of the current title extension (if any)
            # and the toolbar item URL
            urls = self.get_title_extension_admin()

            # we now also need to get the titleset (i.e. different language titles)
            # for this page
            page = self._get_page()
            titleset = page.title_set.filter(
                language__in=get_language_list(page.node.site_id))

            # create a 3-tuple of (title_extension, url, title)
            nodes = [(title_extension, url, title) for (
                (title_extension, url), title) in zip(urls, titleset)
            ]

            # cycle through the list of nodes
            for title_extension, url, title in nodes:
                language = get_language_object(title.language)['name']
                # adds toolbar items
                sub_menu.add_modal_item(
                    _('%s options') % language, url=url, disabled=not self.toolbar.edit_mode_active
                )
Example #11
0
    def setUpClass(cls):
        from django.contrib.sites.models import Site
        cls.request_factory = RequestFactory()
        cls.user = create_user('admin', '*****@*****.**', 'admin',
                               is_staff=True, is_superuser=True)
        cls.user_staff = create_user('staff', '*****@*****.**', 'staff',
                                     is_staff=True)
        cls.user_normal = create_user('normal', '*****@*****.**', 'normal')
        cls.site_1 = Site.objects.get(pk=1)

        try:
            from cms.utils import get_language_list
            cls.languages = get_language_list()
        except ImportError:
            cls.languages = [x[0] for x in settings.LANGUAGES]
Example #12
0
class BaseTest(BaseTestCase):
    """
    Base class with utility function
    """
    languages = get_language_list()

    def get_pages(self):
        from cms.api import create_page, create_title
        page = create_page(u'page one', 'page.html', language='en')
        page_2 = create_page(u'page two', 'page.html', language='en')
        create_title(language='fr', title=u'page un', page=page)
        create_title(language='it', title=u'pagina uno', page=page)
        for lang in self.languages:
            page.publish(lang)
        page_2.publish('en')
        return page.get_draft_object(), page_2.get_draft_object()
Example #13
0
    def setUpClass(cls):
        from django.contrib.sites.models import Site
        super(BaseTestCase, cls).setUpClass()
        cls.request_factory = RequestFactory()
        cls.user = create_user('admin', '*****@*****.**', 'admin',
                               is_staff=True, is_superuser=True)
        cls.user_staff = create_user('staff', '*****@*****.**', 'staff',
                                     is_staff=True)
        cls.user_normal = create_user('normal', '*****@*****.**', 'normal')
        cls.site_1 = Site.objects.get(pk=1)

        try:
            from cms.utils import get_language_list
            cls.languages = get_language_list()
        except ImportError:
            cls.languages = [x[0] for x in settings.LANGUAGES]
    def _setup_filled(self,
                      site_id=1,
                      home_final=4,
                      blog_final=2,
                      configs_final=1,
                      configs_init=0,
                      pages_init=0):
        site = Site.objects.get(pk=site_id)
        set_home = hasattr(Page, 'set_as_homepage')
        # Tests starts with a set of pages / configs
        self.assertEqual(Page.objects.count(), pages_init)
        if self.config:
            self.assertEqual(self.config.objects.count(), configs_init)
        self.assertEqual(
            Page.objects.filter(application_urls=self.app_name).count(),
            configs_init * 2)

        langs = get_language_list()
        home = None
        for lang in langs:
            with override(lang):
                if not home:
                    home = create_page('a new home',
                                       language=lang,
                                       site=site,
                                       template='page.html',
                                       in_navigation=True,
                                       published=True)
                    if set_home:
                        home.set_as_homepage()
                else:
                    create_title(language=lang, title='a new home', page=home)
                    home.publish(lang)

        # importing cms_app triggers the auto setup
        __import__(self.module, fromlist=(str('cms_apps'), ))

        # Final set of pages / configs
        self.assertEqual(Page.objects.count(), home_final)
        if self.config:
            self.assertEqual(self.config.objects.count(), configs_final)
        self.assertEqual(
            Page.objects.filter(application_urls=self.app_name).count(),
            blog_final)

        home = Page.objects.get_home(site)
        self.assertEqual(home.get_title(), 'a new home')
    def populate(self):
        current_page_menu = self._setup_extension_toolbar()
        if current_page_menu:
            urls = self.get_title_extension_admin()
            page = self._get_page()
            titleset = page.title_set.filter(
                language__in=get_language_list(page.node.site_id))

            nodes = [(title_extension, url, title.title)
                     for ((title_extension, url),
                          title) in zip(urls, titleset)]

            for title_extension, url, title in nodes:
                current_page_menu.add_modal_item(
                    _('Teaser for {}'.format(title)),
                    url=url,
                    disabled=not self.toolbar.edit_mode_active)
Example #16
0
def render_admin_menu_item(request, page, template=None, language=None):
    """
    Renders requested page item for the tree. This is used in case when item
    must be reloaded over ajax.
    """
    if not template:
        template = "admin/cms/page/tree/menu_fragment.html"

    if not page.pk:
        return HttpResponse(NOT_FOUND_RESPONSE)  # Not found - tree will remove item

    # languages
    from cms.utils import permissions

    languages = get_language_list(page.site_id)
    context = {"has_add_permission": permissions.has_page_add_permission(request), "site_languages": languages}
    filtered = "filtered" in request.GET or "filtered" in request.POST
    context.update(get_admin_menu_item_context(request, page, filtered, language))
    return render(request, template, context)
    def items(self):
        items = []
        self.url_cache.clear()
        for lang in get_language_list():
            self.url_cache[lang] = {}
            posts = Post.objects.translated(lang).language(lang).published()
            for post in posts:
                # check if the post actually has a url before appending
                # if a post is published but the associated app config is not
                # then this post will not have a url
                try:
                    with smart_override(post.get_current_language()):
                        self.url_cache[lang][post] = post.get_absolute_url()
                except NoReverseMatch:
                    # couldn't determine the url of the post so pass on it
                    continue

                items.append(post)

        return items
Example #18
0
    def items(self):
        items = []
        self.url_cache.clear()
        for lang in get_language_list():
            self.url_cache[lang] = {}
            posts = Post.objects.translated(lang).language(lang).published()
            for post in posts:
                # check if the post actually has a url before appending
                # if a post is published but the associated app config is not
                # then this post will not have a url
                try:
                    with smart_override(post.get_current_language()):
                        self.url_cache[lang][post] = post.get_absolute_url()
                except NoReverseMatch:
                    # couldn't determine the url of the post so pass on it
                    continue

                items.append(post)

        return items
Example #19
0
    def _setup_pages(cls, setup_config=False):
        """
        Create the page structure.

        It created a home page (if not exists) and a sub-page, and attach the Apphook to the
        sub-page.
        Pages titles are provided by ``AutoCMSAppMixin.auto_setup``

        :param setup_config: boolean to control whether creating the ApphookConfig instance
        """
        from cms.exceptions import NoHomeFound
        from cms.models import Page
        from cms.utils import get_language_list
        from django.utils.translation import override

        config = None
        if setup_config:
            config = cls._create_config()

        langs = get_language_list()
        app_page = None
        for lang in langs:
            with override(lang):
                if config:
                    if cls.auto_setup['config_translated_fields']:
                        cls._create_config_translation(config, lang)
                    namespace = config.namespace
                elif cls.app_name:
                    namespace = cls.app_name
                else:
                    namespace = None
                try:
                    home = Page.objects.get_home().get_draft_object()
                except NoHomeFound:
                    home = None
                home = cls._create_page(home, lang, cls.auto_setup['home title'])
                app_page = cls._create_page(
                    app_page, lang, cls.auto_setup['page title'], cls.__name__, home, namespace
                )
Example #20
0
    def get_title_extension_admin(self, language=None):
        """
        Get the admin urls for the title extensions menu items, depending on whether a TitleExtension instance exists
        for each Title in the current page.
        A single language can be passed to only work on a single title.

        Return a list of tuples of the title extension and the url; the extension is None if no instance exists,
        the url is None is no admin is registered for the extension.
        """
        page = self._get_page()
        urls = []
        if language:
            titles = page.get_title_obj(language),
        else:
            titles = page.title_set.filter(
                language__in=get_language_list(page.site_id))
        # Titles
        for title in titles:
            try:
                title_extension = self.model.objects.get(
                    extended_object_id=title.pk)
            except self.model.DoesNotExist:
                title_extension = None
            try:
                model_name = self.model.__name__.lower()
                if title_extension:
                    admin_url = admin_reverse(
                        '%s_%s_change' %
                        (self.model._meta.app_label, model_name),
                        args=(title_extension.pk, ))
                else:
                    admin_url = "%s?extended_object=%s" % (admin_reverse(
                        '%s_%s_add' %
                        (self.model._meta.app_label, model_name)), title.pk)
            except NoReverseMatch:  # pragma: no cover
                admin_url = None
            if admin_url:
                urls.append((title_extension, admin_url))
        return urls
Example #21
0
    def setUpClass(cls):
        from django.contrib.sites.models import Site
        cls.request_factory = RequestFactory()
        cls.user = create_user(
            cls._admin_user_username, cls._admin_user_email, cls._admin_user_password,
            is_staff=True, is_superuser=True
        )
        cls.user_staff = create_user(
            cls._staff_user_username, cls._staff_user_email, cls._staff_user_password,
            is_staff=True, is_superuser=False
        )
        cls.user_normal = create_user(
            cls._user_user_username, cls._user_user_email, cls._user_user_password,
            is_staff=False, is_superuser=False
        )
        cls.site_1 = Site.objects.all().first()

        try:
            from cms.utils import get_language_list
            cls.languages = get_language_list()
        except ImportError:
            cls.languages = [x[0] for x in settings.LANGUAGES]
        super(BaseTestCaseMixin, cls).setUpClass()
Example #22
0
    def get_title_extension_admin(self, language=None):
        """
        Get the admin urls for the title extensions menu items, depending on whether a TitleExtension instance exists
        for each Title in the current page.
        A single language can be passed to only work on a single title.

        Return a list of tuples of the title extension and the url; the extension is None if no instance exists,
        the url is None is no admin is registered for the extension.
        """
        page = self._get_page()
        urls = []
        if language:
            titles = (page.get_title_obj(language),)
        else:
            titles = page.title_set.filter(language__in=get_language_list(page.site_id))
        # Titles
        for title in titles:
            try:
                title_extension = self.model.objects.get(extended_object_id=title.pk)
            except self.model.DoesNotExist:
                title_extension = None
            try:
                model_name = self.model.__name__.lower()
                if title_extension:
                    admin_url = admin_reverse(
                        "%s_%s_change" % (self.model._meta.app_label, model_name), args=(title_extension.pk,)
                    )
                else:
                    admin_url = "%s?extended_object=%s" % (
                        admin_reverse("%s_%s_add" % (self.model._meta.app_label, model_name)),
                        title.pk,
                    )
            except NoReverseMatch:  # pragma: no cover
                admin_url = None
            if admin_url:
                urls.append((title_extension, admin_url))
        return urls
Example #23
0
    def populate(self):
        current_page_menu = self._setup_extension_toolbar()
        if not current_page_menu or not self.page:
            return

        languages = get_language_list(self.current_site.pk)
        is_single_lang = len(languages) < 2
        position = self.get_item_position(current_page_menu)
        urls = self.get_title_extension_admin()
        page = self._get_page()
        titleset = page.title_set.filter(language__in=languages)

        if hasattr(self.toolbar, 'edit_mode_active'):
            not_edit_mode = not self.toolbar.edit_mode_active
        else:
            not_edit_mode = not self.toolbar.edit_mode

        extended_menu = current_page_menu if is_single_lang else (
            current_page_menu.get_or_create_menu(
                key='{0}_menu'.format(self.model._meta.db_table),
                verbose_name=self.model._meta.verbose_name,
                position=position,
                disabled=not_edit_mode))

        nodes = [(title_extension, url, title)
                 for ((title_extension, url), title) in zip(urls, titleset)]

        for title_extension, url, title in nodes:
            item_position = position if is_single_lang else None
            language_str = get_language_info(title.language)['name_translated']
            name = '{0}{1}'.format(
                '' if is_single_lang else (language_str + ' '),
                self.model._meta.verbose_name)
            extended_menu.add_modal_item(name,
                                         url=url,
                                         disabled=not_edit_mode,
                                         position=item_position)
Example #24
0
def render_admin_menu_item(request, page, template=None, language=None,
                           open_nodes=()):
    """
    Renders requested page item for the tree. This is used in case when item
    must be reloaded over ajax.
    """
    if not template:
        template = "admin/cms/page/tree/menu_fragment.html"

    if not page.pk:
        # Not found - tree will remove item
        return HttpResponse(NOT_FOUND_RESPONSE)

    # languages
    from cms.utils import permissions
    languages = get_language_list(page.site_id)
    context = {
        'has_add_permission': permissions.has_page_add_permission_from_request(request),
        'site_languages': languages,
        'open_nodes': open_nodes,
    }
    filtered = 'filtered' in request.GET or 'filtered' in request.POST
    context.update(get_admin_menu_item_context(request, page, filtered, language))
    return render_to_string(template, context)
Example #25
0
def render_admin_rows(request, pages, site, filtered=False, language=None):
    """
    Used for rendering the page tree, inserts into context everything what
    we need for single item
    """
    user = request.user
    site = Site.objects.get_current()
    lang = get_language_from_request(request)
    permissions_on = get_cms_setting('PERMISSION')

    user_can_add = page_permissions.user_can_add_subpage
    user_can_move = page_permissions.user_can_move_page
    user_can_change = page_permissions.user_can_change_page
    user_can_change_advanced_settings = page_permissions.user_can_change_page_advanced_settings
    user_can_publish = page_permissions.user_can_publish_page

    template = get_template('admin/cms/page/tree/menu.html')

    if not language:
        language = get_language_from_request(request)

    filtered = filtered or request.GET.get('q')

    if filtered:
        # When the tree is filtered, it's displayed as a flat structure
        # therefore there's no concept of open nodes.
        open_nodes = []
    else:
        open_nodes = list(map(int, request.GET.getlist('openNodes[]')))

    languages = get_language_list(site.pk)

    page_ids = []

    for page in pages:
        page_ids.append(page.pk)

        if page.publisher_public_id:
            page_ids.append(page.publisher_public_id)

    cms_title_cache = defaultdict(dict)

    cms_page_titles = Title.objects.filter(
        page__in=page_ids,
        language__in=languages
    )

    for cms_title in cms_page_titles.iterator():
        cms_title_cache[cms_title.page_id][cms_title.language] = cms_title

    def render_page_row(page):
        page_cache = cms_title_cache[page.pk]

        for language in languages:
            page_cache.setdefault(language, EmptyTitle(language=language))

        page.title_cache = cms_title_cache[page.pk]

        if page.publisher_public_id:
            publisher_cache = cms_title_cache[page.publisher_public_id]

            for language in languages:
                publisher_cache.setdefault(language, EmptyTitle(language=language))
            page.publisher_public.title_cache = publisher_cache

        has_move_page_permission = user_can_move(user, page)

        metadata = ""

        if permissions_on and not has_move_page_permission:
            # jstree metadata generator
            md = [('valid_children', False), ('draggable', False)]
            # 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)) + "}"

        if filtered:
            children = page.children.none()
        else:
            children = page.get_children()

        context = {
            'request': request,
            'page': page,
            'site': site,
            'lang': lang,
            'filtered': filtered,
            'metadata': metadata,
            'page_languages': page.get_languages(),
            'preview_language': lang,
            'has_add_page_permission': user_can_add(user, target=page),
            'has_change_permission': user_can_change(user, page),
            'has_change_advanced_settings_permission': user_can_change_advanced_settings(user, page),
            'has_publish_permission': user_can_publish(user, page),
            'has_move_page_permission': has_move_page_permission,
            'children': children,
            'site_languages': languages,
            'open_nodes': open_nodes,
            'cms_current_site': site,
            'is_popup': (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET)
        }
        return template.render(context)

    rendered = (render_page_row(page) for page in pages)
    return ''.join(rendered)
Example #26
0
    def set_items(self, request):
        site = self.current_site()
        # Get all the pages, ordered by tree ID (it's convenient to build the
        # tree using a stack now)
        pages = self.get_query_set(request).drafts().order_by('tree_id',  'lft').select_related('publisher_public')

        # Get lists of page IDs for which the current user has
        # "permission to..." on the current site.
        if get_cms_setting('PERMISSION'):
            perm_edit_ids = Page.permissions.get_change_id_list(request.user, site)
            perm_publish_ids = Page.permissions.get_publish_id_list(request.user, site)
            perm_advanced_settings_ids = Page.permissions.get_advanced_settings_id_list(request.user, site)
            restricted_ids = Page.permissions.get_restricted_id_list(site)
            if perm_edit_ids and perm_edit_ids != Page.permissions.GRANT_ALL:
                pages = pages.filter(pk__in=perm_edit_ids)

        root_pages = []
        pages = list(pages)
        all_pages = pages[:] # That is, basically, a copy.

        # Unfortunately we cannot use the MPTT builtin code for pre-caching
        # the children here, because MPTT expects the tree to be 'complete'
        # and otherwise complaints about 'invalid item order'
        cache_tree_children(pages)
        ids = dict((page.id, page) for page in pages)

        for page in pages:

            children = list(page.get_children())

            # If the parent page is not among the nodes shown, this node should
            # be a "root node". The filtering for this has already been made, so
            # using the ids dictionary means this check is constant time
            page.root_node = page.parent_id not in ids

            if get_cms_setting('PERMISSION'):
                # caching the permissions
                page.permission_edit_cache = perm_edit_ids == Page.permissions.GRANT_ALL or page.pk in perm_edit_ids
                page.permission_publish_cache = perm_publish_ids == Page.permissions.GRANT_ALL or page.pk in perm_publish_ids
                page.permission_advanced_settings_cache = perm_advanced_settings_ids == Page.permissions.GRANT_ALL or page.pk in perm_advanced_settings_ids
                page.permission_user_cache = request.user
                page.permission_restricted = page.pk in restricted_ids
            if page.root_node or self.is_filtered():
                page.last = True
                if len(children):
                    # TODO: WTF!?!
                    # The last one is not the last... wait, what?
                    # children should NOT be a queryset. If it is, check that
                    # your django-mptt version is 0.5.1
                    children[-1].last = False
                page.menu_level = 0
                root_pages.append(page)
                if page.parent_id:
                    page.get_cached_ancestors(ascending=True)
                else:
                    page.ancestors_ascending = []

            # Because 'children' is the reverse-FK accessor for the 'parent'
            # FK from Page->Page, we have to use wrong English here and set
            # an attribute called 'childrens'. We are aware that this is WRONG
            # but what should we do?

            # If the queryset is filtered, do NOT set the 'childrens' attribute
            # since *ALL* pages will be in the 'root_pages' list and therefore
            # be displayed. (If the queryset is filtered, the result is not a
            # tree but rather a flat list).
            if self.is_filtered():
                page.childrens = []
            else:
                page.childrens = children

        for page in all_pages:
            page.title_cache = {}
            page.all_languages = []
            if page.publisher_public_id:
                page.publisher_public.title_cache = {}
                page.publisher_public.all_languages = []
                ids[page.publisher_public_id] = page.publisher_public

        titles = Title.objects.filter(page__in=ids)
        insort = bisect.insort # local copy to avoid globals lookup in the loop
        for title in titles:
            page = ids[title.page_id]
            page.title_cache[title.language] = title
            if not title.language in page.all_languages:
                insort(page.all_languages, title.language)
        site_id = self.current_site()
        languages = get_language_list(site_id)
        for page in all_pages:
            for lang in languages:
                if not lang in page.title_cache:
                    page.title_cache[lang] = EmptyTitle(lang)
        self.root_pages = root_pages
    def handle(self, *args, **options):
        verbose = options.get('verbosity') > 1
        only_empty = options.get('only_empty')
        copy_content = options.get('copy_content')
        from_lang = options.get('from_lang')
        to_lang = options.get('to_lang')
        try:
            site = int(options.get('site', None))
        except Exception:
            site = settings.SITE_ID

        try:
            assert from_lang in get_language_list(site)
            assert to_lang in get_language_list(site)
        except AssertionError:
            raise CommandError(
                'Both languages have to be present in settings.LANGUAGES and settings.CMS_LANGUAGES'
            )

        for page in Page.objects.on_site(site).drafts():
            # copy title
            if from_lang in page.get_languages():

                title = page.get_title_obj(to_lang, fallback=False)
                if isinstance(title, EmptyTitle):
                    title = page.get_title_obj(from_lang)
                    if verbose:
                        self.stdout.write(
                            'copying title %s from language %s\n' %
                            (title.title, from_lang))
                    title.id = None
                    title.publisher_public_id = None
                    title.publisher_state = 0
                    title.language = to_lang
                    title.save()
                if copy_content:
                    # copy plugins using API
                    if verbose:
                        self.stdout.write(
                            'copying plugins for %s from %s\n' %
                            (page.get_page_title(from_lang), from_lang))
                    copy_plugins_to_language(page, from_lang, to_lang,
                                             only_empty)
            else:
                if verbose:
                    self.stdout.write(
                        'Skipping page %s, language %s not defined\n' %
                        (page.get_page_title(
                            page.get_languages()[0]), from_lang))

        if copy_content:
            for static_placeholder in StaticPlaceholder.objects.all():
                plugin_list = []
                for plugin in static_placeholder.draft.get_plugins():
                    if plugin.language == from_lang:
                        plugin_list.append(plugin)

                if plugin_list:
                    if verbose:
                        self.stdout.write(
                            'copying plugins from static_placeholder "%s" in "%s" to "%s"\n'
                            % (static_placeholder.name, from_lang, to_lang))
                    copy_plugins_to(plugin_list, static_placeholder.draft,
                                    to_lang)

        self.stdout.write('all done')
Example #28
0
 def items(self):
     items = []
     for lang in get_language_list():
         items.extend(Post.objects.translated(lang).language(lang).published())
     return items
Example #29
0
    def _setup_pages(cls, config):
        """
        Create the page structure.

        It created a home page (if not exists) and a sub-page, and attach the Apphook to the
        sub-page.
        Pages titles are provided by ``AutoCMSAppMixin.auto_setup``

        :param setup_config: boolean to control whether creating the ApphookConfig instance
        """
        from cms.exceptions import NoHomeFound
        from cms.models import Page
        from cms.utils import get_language_list
        from django.conf import settings
        from django.utils.translation import override

        app_page = None
        get_url = False
        if getattr(settings, 'ALDRYN_SEARCH_CMS_PAGE', False):
            from aldryn_search.search_indexes import TitleIndex

            def fake_url(self, obj):
                return ''

            get_url = TitleIndex.get_url
            TitleIndex.get_url = fake_url
        site = Site.objects.get_current()
        auto_sites = cls.auto_setup.get('sites', True)
        if auto_sites is True or site.pk in auto_sites:
            if getattr(cls, 'app_config', False):
                configs = cls.app_config.objects.all()
                if not configs.exists():
                    config = cls._create_config()
                else:
                    config = configs.first()

            langs = get_language_list(site.pk)
            if not Page.objects.on_site(
                    site.pk).filter(application_urls=cls.__name__).exists():
                for lang in langs:
                    with override(lang):
                        if config:
                            if cls.auto_setup['config_translated_fields']:
                                cls._create_config_translation(config, lang)
                            namespace = config.namespace
                        elif cls.app_name:
                            namespace = cls.app_name
                        else:
                            namespace = None
                        try:
                            home = Page.objects.get_home(
                                site.pk).get_draft_object()
                        except NoHomeFound:
                            home = None
                        set_home = hasattr(Page, 'set_as_homepage')
                        home = cls._create_page(home,
                                                lang,
                                                cls.auto_setup['home title'],
                                                site=site,
                                                set_home=set_home)
                        app_page = cls._create_page(
                            app_page,
                            lang,
                            cls.auto_setup['page title'],
                            cls.__name__,
                            home,
                            namespace,
                            site=site)
        if get_url:
            TitleIndex.get_url = get_url
def render_admin_rows(request, pages, site, filtered=False, language=None):
    """
    Used for rendering the page tree, inserts into context everything what
    we need for single item
    """
    user = request.user
    site = Site.objects.get_current()
    lang = get_language_from_request(request)
    permissions_on = get_cms_setting('PERMISSION')

    user_can_add = page_permissions.user_can_add_subpage
    user_can_move = page_permissions.user_can_move_page
    user_can_change = page_permissions.user_can_change_page
    user_can_change_advanced_settings = page_permissions.user_can_change_page_advanced_settings
    user_can_publish = page_permissions.user_can_publish_page

    template = get_template('admin/cms/page/tree/menu.html')
    bin_template = get_template('admin/bin_menu.html')

    if not language:
        language = get_language_from_request(request)

    filtered = filtered or request.GET.get('q')

    if filtered:
        # When the tree is filtered, it's displayed as a flat structure
        # therefore there's no concept of open nodes.
        open_nodes = []
    else:
        open_nodes = list(map(int, request.GET.getlist('openNodes[]')))

    languages = get_language_list(site.pk)

    page_ids = []

    for page in pages:
        page_ids.append(page.pk)

        if page.publisher_public_id:
            page_ids.append(page.publisher_public_id)

    cms_title_cache = defaultdict(dict)

    cms_page_titles = Title.objects.filter(page__in=page_ids,
                                           language__in=languages)

    for cms_title in cms_page_titles.iterator():
        # if cms_title.title.startswith(BIN_NAMING_PREFIX):
        #    for lang in languages:
        #        cms_title_cache[cms_title.page_id][lang] = cms_title
        # else:
        cms_title_cache[cms_title.page_id][cms_title.language] = cms_title

    def render_page_row(page):
        page_cache = cms_title_cache[page.pk]

        for language in languages:
            page_cache.setdefault(language, EmptyTitle(language=language))

        page.title_cache = cms_title_cache[page.pk]

        if page.publisher_public_id:
            publisher_cache = cms_title_cache[page.publisher_public_id]

            for language in languages:
                publisher_cache.setdefault(language,
                                           EmptyTitle(language=language))
            page.publisher_public.title_cache = publisher_cache

        if filtered:
            children = page.children.none()
        else:
            children = page.get_children()

        is_bin = page.title_set.filter(
            title__startswith=BIN_NAMING_PREFIX).exists()

        if is_bin:
            context = {
                'request':
                request,
                'page':
                page,
                'site':
                site,
                'lang':
                lang,
                'filtered':
                filtered,
                'metadata':
                '',
                'page_languages':
                None,
                'preview_language':
                None,
                'has_add_page_permission':
                False,
                'has_change_permission':
                False,
                'has_change_advanced_settings_permission':
                False,
                'has_publish_permission':
                False,
                'has_move_page_permission':
                False,
                'children':
                children,
                'site_languages':
                languages,
                'open_nodes': [],  #open_nodes,
                'cms_current_site':
                site,
                'is_popup': (IS_POPUP_VAR in request.POST
                             or IS_POPUP_VAR in request.GET)
            }
            return bin_template.render(context)

        has_move_page_permission = user_can_move(user, page)

        metadata = ""

        if permissions_on and not has_move_page_permission:
            # jstree metadata generator
            md = [('valid_children', False), ('draggable', False)]
            # 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)) + "}"

        context = {
            'request':
            request,
            'page':
            page,
            'site':
            site,
            'lang':
            lang,
            'filtered':
            filtered,
            'metadata':
            metadata,
            'page_languages':
            page.get_languages(),
            'preview_language':
            lang,
            'has_add_page_permission':
            user_can_add(user, target=page),
            'has_change_permission':
            user_can_change(user, page),
            'has_change_advanced_settings_permission':
            user_can_change_advanced_settings(user, page),
            'has_publish_permission':
            user_can_publish(user, page),
            'has_move_page_permission':
            has_move_page_permission,
            'children':
            children,
            'site_languages':
            languages,
            'open_nodes':
            open_nodes,
            'cms_current_site':
            site,
            'is_popup': (IS_POPUP_VAR in request.POST
                         or IS_POPUP_VAR in request.GET)
        }
        return template.render(context)

    rendered = (render_page_row(page) for page in pages)
    return ''.join(rendered)
Example #31
0
 def items(self):
     items = []
     for lang in get_language_list():
         items.extend(
             Post.objects.translated(lang).language(lang).published())
     return items