Example #1
0
    def test_get_nodes(self):
        # Test that the EN version of the menu has only category1 and its
        # question1, and is shown in English.
        request = self.get_page_request(
            None, self.user, path='/en/', lang_code='en')
        try:
            renderer = menu_pool.get_renderer(request)
            menu = FaqCategoryMenu(renderer=renderer)
        except AttributeError:
            menu = FaqCategoryMenu()
        category1 = self.reload(self.category1, 'en')
        question1 = self.reload(self.question1, 'en')
        self.assertEqualItems(
            [menuitem.title for menuitem in menu.get_nodes(request)],
            [category1.name, question1.title]
        )

        # Test that the DE version has 2 categories and their questions that
        # they are shown in German.
        request = self.get_page_request(
            None, self.user, path='/de/', lang_code='de')
        try:
            renderer = menu_pool.get_renderer(request)
            menu = FaqCategoryMenu(renderer=renderer)
        except AttributeError:
            menu = FaqCategoryMenu()
        nodes = menu.get_nodes(request)
        self.assertEqualItems(
            [menuitem.title for menuitem in nodes],
            [self.category1.name, self.category2.name, self.question1.title,
                self.question2.title]
        )
Example #2
0
    def test_get_nodes(self):
        # Test that the EN version of the menu has only category1 and its
        # question1, and is shown in English.
        request = self.get_page_request(None,
                                        self.user,
                                        path='/en/',
                                        lang_code='en')
        try:
            renderer = menu_pool.get_renderer(request)
            menu = FaqCategoryMenu(renderer=renderer)
        except AttributeError:
            menu = FaqCategoryMenu()
        category1 = self.reload(self.category1, 'en')
        question1 = self.reload(self.question1, 'en')
        self.assertEqualItems(
            [menuitem.title for menuitem in menu.get_nodes(request)],
            [category1.name, question1.title])

        # Test that the DE version has 2 categories and their questions that
        # they are shown in German.
        request = self.get_page_request(None,
                                        self.user,
                                        path='/de/',
                                        lang_code='de')
        try:
            renderer = menu_pool.get_renderer(request)
            menu = FaqCategoryMenu(renderer=renderer)
        except AttributeError:
            menu = FaqCategoryMenu()
        nodes = menu.get_nodes(request)
        self.assertEqualItems([menuitem.title for menuitem in nodes], [
            self.category1.name, self.category2.name, self.question1.title,
            self.question2.title
        ])
Example #3
0
    def test_menu_node_is_selected_on_app_root(self):
        """
        If a user requests a page with an apphook,
        the menu should mark the node for that page as selected.
        """
        defaults = {
            'language': 'en',
            'published': True,
            'in_navigation': True,
            'template': 'nav_playground.html',
        }
        homepage = create_page('EN-P1', **defaults)
        homepage.set_as_homepage()
        app_root = create_page('EN-P2', apphook='AppWithNoMenu', apphook_namespace='app_with_no_menu', **defaults)

        # Public version
        request = self.get_request(self.get_edit_on_url('/en/en-p2/'))
        request.current_page = get_page(request)
        menu_nodes = menu_pool.get_renderer(request).get_nodes()
        self.assertEqual(len(menu_nodes), 2)
        self.assertEqual(menu_nodes[0].id, homepage.publisher_public_id)
        self.assertEqual(menu_nodes[0].selected, False)
        self.assertEqual(menu_nodes[1].id, app_root.publisher_public_id)
        self.assertEqual(menu_nodes[1].selected, True)

        # Draft version
        with self.login_user_context(self.get_superuser()):
            request = self.get_request(self.get_edit_on_url('/en/en-p2/'))
            request.current_page = get_page(request)
            menu_nodes = menu_pool.get_renderer(request).get_nodes()
            self.assertEqual(len(menu_nodes), 2)
            self.assertEqual(menu_nodes[0].id, homepage.pk)
            self.assertEqual(menu_nodes[0].selected, False)
            self.assertEqual(menu_nodes[1].id, app_root.pk)
            self.assertEqual(menu_nodes[1].selected, True)
Example #4
0
    def get_context(self, context, **kwargs):

        menu_name = kwargs.pop('menu_name')

        context.update({
            'children': [],
            'template': kwargs.get('template'),
            'from_level': kwargs.get('from_level'),
            'to_level': kwargs.get('to_level'),
            'extra_inactive': kwargs.get('extra_inactive'),
            'extra_active': kwargs.get('extra_active'),
            'namespace': kwargs.get('namespace')
        })

        try:
            named_menu = CMSNamedMenu.objects.get(name__iexact=menu_name).pages
        except ObjectDoesNotExist:
            logging.warn("Named CMS Menu %s not found" % menu_name)
            return context
        menu_renderer = menu_pool.get_renderer(context['request'])
        nodes = menu_renderer.get_nodes(None, 0)

        context.update({
            'children':
            self.arrange_nodes(nodes,
                               named_menu,
                               namespace=kwargs['namespace'])
        })

        return context
Example #5
0
 def test_public_menu_anonymous_user(self):
     """
     Anonymous user should only see the pages in the rendered menu
     that have no permissions assigned,directly or indirectly
     """
     self._setup_user_groups()
     all_pages = self._setup_tree_pages()
     self._setup_view_restrictions()
     granted = ['page_a',
         'page_c',
         'page_c_a',
         'page_c_b',
         'page_d_a',
         'page_d_b',
         'page_d_c',
         'page_d_d'
     ]
     self.assertGrantedVisibility(all_pages, granted)
     urls = self.get_url_dict(all_pages)
     user = AnonymousUser()
     request = self.get_request(user, urls['/en/'])
     menu_renderer = menu_pool.get_renderer(request)
     nodes = menu_renderer.get_nodes()
     self.assertEqual(len(nodes), 4)
     self.assertInMenu(urls["/en/"], user)
     self.assertInMenu(urls["/en/page_c/"], user)
     self.assertInMenu(urls["/en/page_c/page_c_a/"], user)
     self.assertInMenu(urls["/en/page_c/page_c_b/"], user)
     self.assertViewNotAllowed(urls["/en/page_b/"], user)
     self.assertNotInMenu(urls["/en/page_b/"], user)
     self.assertViewNotAllowed(urls["/en/page_d/"], user)
     self.assertNotInMenu(urls["/en/page_d/"], user)
def get_cms_menu_data_dict(request, renderer=None):
    if not renderer:
        renderer = menu_pool.get_renderer(request)

    nodes = renderer.get_nodes()

    def get_menu_node(node):
        if not node.visible:
            return False

        menu_node = {'path': node.get_absolute_url(), 'label': node.title}

        if node.children:
            child_menu_nodes = []
            for child_node in node.children:
                child_menu_node = get_menu_node(child_node)
                if child_menu_node:
                    child_menu_nodes.append(child_menu_node)

            if child_menu_nodes:
                menu_node['children'] = child_menu_nodes

        return menu_node

    menu_nodes = []
    for node in nodes:
        if node.level == 0:
            menu_nodes.append(get_menu_node(node))

    data = {'type': 'generic', 'content': {'menu': menu_nodes}}

    return data
 def test_public_menu_anonymous_user(self):
     """
     Anonymous user should only see the pages in the rendered menu
     that have no permissions assigned,directly or indirectly
     """
     self._setup_user_groups()
     all_pages = self._setup_tree_pages()
     self._setup_view_restrictions()
     granted = ['page_a',
         'page_c',
         'page_c_a',
         'page_c_b',
         'page_d_a',
         'page_d_b',
         'page_d_c',
         'page_d_d'
     ]
     self.assertGrantedVisibility(all_pages, granted)
     urls = self.get_url_dict(all_pages)
     user = AnonymousUser()
     request = self.get_request(user, urls['/en/'])
     menu_renderer = menu_pool.get_renderer(request)
     nodes = menu_renderer.get_nodes()
     self.assertEqual(len(nodes), 4)
     self.assertInMenu(urls["/en/"], user)
     self.assertInMenu(urls["/en/page_c/"], user)
     self.assertInMenu(urls["/en/page_c/page_c_a/"], user)
     self.assertInMenu(urls["/en/page_c/page_c_b/"], user)
     self.assertViewNotAllowed(urls["/en/page_b/"], user)
     self.assertNotInMenu(urls["/en/page_b/"], user)
     self.assertViewNotAllowed(urls["/en/page_d/"], user)
     self.assertNotInMenu(urls["/en/page_d/"], user)
    def test_hide_untranslated(self):
        TESTLANG = get_primary_language()
        TESTLANG2 = get_secondary_language()
        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)

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

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

        request_1_menu_renderer = menu_pool.get_renderer(request_1)
        request_2_menu_renderer = menu_pool.get_renderer(request_2)

        lang_settings[1][1]['hide_untranslated'] = False
        with self.settings(CMS_LANGUAGES=lang_settings):
            request_1_nodes = request_1_menu_renderer.get_menu(
                'CMSMenu').get_nodes(request_1)
            request_2_nodes = request_2_menu_renderer.get_menu(
                'CMSMenu').get_nodes(request_2)
            list_1 = [node.id for node in request_1_nodes]
            list_2 = [node.id for node in request_2_nodes]
            self.assertEqual(list_1, list_2)
            self.assertEqual(len(list_1), 2)

        lang_settings[1][1]['hide_untranslated'] = True
        with self.settings(CMS_LANGUAGES=lang_settings):
            request_1_nodes = request_1_menu_renderer.get_menu(
                'CMSMenu').get_nodes(request_1)
            request_2_nodes = request_2_menu_renderer.get_menu(
                'CMSMenu').get_nodes(request_2)
            list_1 = [node.id for node in request_1_nodes]
            list_2 = [node.id for node in request_2_nodes]
            self.assertNotEqual(list_1, list_2)
            self.assertEqual(len(list_2), 1)
            self.assertEqual(len(list_1), 2)
def get_nodes(request, namespace=None, root_id=None):
    # Django CMS >= 3.3
    renderer = menu_pool.get_renderer(request)

    all_nodes = renderer.get_nodes(namespace=namespace, root_id=root_id, breadcrumb=False)
    all_nodes = [node for node in all_nodes if not node.attr.get('cms_named_menus_hidden', False)]

    return all_nodes
    def render(self, context, instance, placeholder):

        try:
            # If there's an exception (500), default context_processors may not be called.
            request = context['request']
        except KeyError:
            return _("There is no `request` object in the context.")

        root_page = instance.root
        from_level = instance.start_level
        to_level = instance.show_depth

        renderer = menu_pool.get_renderer(request)
        nodes = renderer.get_nodes(
            namespace=None,
            root_id=None,
            breadcrumb=False,
        )
        root_node = None
        for node in nodes:
            if not node.attr["is_page"]:
                continue
            if node.id == root_page.id or \
                    node.id == root_page.publisher_public_id:
                root_node = node
                break
        if root_node is not None:
            nodes = root_node.children
            for remove_parent in nodes:
                remove_parent.parent = None
            from_level += node.level + 1
            to_level += node.level + 1
            nodes = flatten(nodes)
        else:
            nodes = []

        extra_levels = to_level - from_level
        children = cut_levels(nodes, from_level, to_level,
                              extra_inactive=extra_levels,
                              extra_active=extra_levels)
        children = renderer.apply_modifiers(children, post_cut=True)

        if root_node and instance.include_root:
            children = (root_node, )

        def add_menu_levels(child, level):
            child.menu_level = level
            for child in child.children:
                add_menu_levels(child, level+1)
        for child in children:
            add_menu_levels(child, 0)

        context.update({
            'instance': instance,
            'MenuItems': children,
            'template': re.search('(\w*).html', instance.template).groups()[0],
        })
        return context
Example #11
0
def get_menu_renderer(context=None, request=None):
    menu_renderer = None

    if context:
        menu_renderer = context.get('cms_menu_renderer')

    if not menu_renderer:
        menu_renderer = menu_pool.get_renderer(request)

    return menu_renderer
Example #12
0
def get_nodes(request, namespace=None, root_id=None):

    # Set the menu renderer to force use of the anonymous version
    menu_renderer = menu_pool.get_renderer(request)

    nodes = menu_renderer.get_nodes(namespace, root_id, breadcrumb=False)

    nodes = filter_nodes(nodes)

    return nodes, menu_renderer
Example #13
0
def get_nodes(user=None):
    request = RequestFactory().get("/")
    request.user = user if user else AnonymousUser()
    with patch("menus.menu_pool.use_draft", return_value=False):
        renderer = menu_pool.get_renderer(request)
    nodes = renderer.get_nodes()
    # There are other menu entries (CMSMenu etc.) and they would confuse these
    # tests, so filter them out.
    filter_nodes_by_namespace(nodes, CLASS_UNDER_TEST)
    return nodes
Example #14
0
    def test_get_menus(self):
        """
        Check that menus are dynamically loaded according to the different page the apphook is
        attached to
        """
        titles = self.create_base_structure('VariableUrlsApp', ['en', 'de'])
        titles[0].page.reverse_id = 'page1'
        titles[0].page.save()
        cache.clear()
        self.reload_urls()
        menu_pool.discover_menus()
        cache.clear()

        request = self.get_request('/')
        renderer = menu_pool.get_renderer(request)
        nodes = renderer.get_nodes()
        nodes_urls = [node.url for node in nodes]
        self.assertTrue(reverse('sample-account') in nodes_urls)
        self.assertFalse('/en/child_page/page2/' in nodes_urls)

        self.reload_urls()
        self.apphook_clear()

        cache.clear()
        self.reload_urls()

        page2 = create_page('page2', 'nav_playground.html',
                            'en', created_by=self.superuser, published=True,
                            parent=titles[0].page.get_parent_page().get_draft_object(),
                            in_navigation=True,
                            apphook='VariableUrlsApp', reverse_id='page2')
        create_title('de', 'de_title', page2, slug='slug')
        page2.publish('de')
        request = self.get_request('/page2/')
        renderer = menu_pool.get_renderer(request)
        nodes = renderer.get_nodes()
        nodes_urls = [node.url for node in nodes]
        self.assertTrue(reverse('sample-account') in nodes_urls)
        self.assertTrue(reverse('sample2-root') in nodes_urls)
        self.assertTrue('/static/fresh/' in nodes_urls)

        self.apphook_clear()
Example #15
0
    def get_context(self, context, levels, root_level, nephews, template):
        # Django 1.4 doesn't accept 'None' as a tag value and resolve to ''
        # So we need to force it to None again
        if not root_level and root_level != 0:
            root_level = None
        try:
            # If there's an exception (500), default context_processors may not be called.
            request = context['request']
        except KeyError:
            return {'template': 'menu/empty.html'}

        menu_renderer = context.get('cms_menu_renderer')

        if not menu_renderer:
            menu_renderer = menu_pool.get_renderer(request)

        nodes = menu_renderer.get_nodes()
        children = []
        # adjust root_level so we cut before the specified level, not after
        include_root = False
        if root_level is not None and root_level > 0:
            root_level -= 1
        elif root_level is not None and root_level == 0:
            include_root = True
        for node in nodes:
            if root_level is None:
                if node.selected:
                    # if no root_level specified, set it to the selected nodes level
                    root_level = node.level
                    # is this the ancestor of current selected node at the root level?
            is_root_ancestor = (node.ancestor and node.level == root_level)
            # is a node selected on the root_level specified
            root_selected = (node.selected and node.level == root_level)
            if is_root_ancestor or root_selected:
                cut_after(node, levels, [])
                children = node.children
                for child in children:
                    if child.sibling:
                        cut_after(child, nephews, [])
                        # if root_level was 0 we need to give the menu the entire tree
                    # not just the children
                if include_root:
                    children = menu_renderer.apply_modifiers([node],
                                                             post_cut=True)
                else:
                    children = menu_renderer.apply_modifiers(children,
                                                             post_cut=True)
        context['children'] = children
        context['template'] = template
        context['from_level'] = 0
        context['to_level'] = 0
        context['extra_inactive'] = 0
        context['extra_active'] = 0
        return context
Example #16
0
    def serialize_navigation(self, request):
        menu_renderer = menu_pool.get_renderer(request)
        nodes = menu_renderer.get_nodes(None, 0)
        cleaned = []

        for node in nodes:
            node.children = None
            node.parent = None
            cleaned.append(node.__dict__)

        return json.dumps(cleaned, cls=LazyEncoder)
Example #17
0
 def assertNotInMenu(self, page, user):
     request = self.get_request(user, page)
     menu_renderer = menu_pool.get_renderer(request)
     nodes = menu_renderer.get_nodes()
     target_url = page.get_absolute_url()
     found_in_menu = False
     for node in nodes:
         if node.get_absolute_url() == target_url:
             found_in_menu = True
             break
     self.assertFalse(found_in_menu)
Example #18
0
 def test_public_pages_anonymous_norestrictions(self):
     """
     All pages are visible to an anonymous user
     """
     all_pages = self._setup_tree_pages()
     request = self.get_request()
     visible_page_ids = get_visible_pages(request, all_pages, self.site)
     self.assertEqual(len(all_pages), len(visible_page_ids))
     menu_renderer = menu_pool.get_renderer(request)
     nodes = menu_renderer.get_nodes()
     self.assertEqual(len(nodes), len(all_pages))
 def test_public_pages_anonymous_norestrictions(self):
     """
     All pages are visible to an anonymous user
     """
     all_pages = self._setup_tree_pages()
     request = self.get_request()
     visible_page_ids = get_visible_pages(request, all_pages, self.site)
     self.assertEqual(len(all_pages), len(visible_page_ids))
     menu_renderer = menu_pool.get_renderer(request)
     nodes = menu_renderer.get_nodes()
     self.assertEqual(len(nodes), len(all_pages))
 def assertNotInMenu(self, page, user):
     request = self.get_request(user, page)
     menu_renderer = menu_pool.get_renderer(request)
     nodes = menu_renderer.get_nodes()
     target_url = page.get_absolute_url()
     found_in_menu = False
     for node in nodes:
         if node.get_absolute_url() == target_url:
             found_in_menu = True
             break
     self.assertFalse(found_in_menu)
Example #21
0
    def get_context(self, context, levels, root_level, nephews, template):
        # Django 1.4 doesn't accept 'None' as a tag value and resolve to ''
        # So we need to force it to None again
        if not root_level and root_level != 0:
            root_level = None
        try:
            # If there's an exception (500), default context_processors may not be called.
            request = context['request']
        except KeyError:
            return {'template': 'menu/empty.html'}

        menu_renderer = context.get('cms_menu_renderer')

        if not menu_renderer:
            menu_renderer = menu_pool.get_renderer(request)

        nodes = menu_renderer.get_nodes()
        children = []
        # adjust root_level so we cut before the specified level, not after
        include_root = False
        if root_level is not None and root_level > 0:
            root_level -= 1
        elif root_level is not None and root_level == 0:
            include_root = True
        for node in nodes:
            if root_level is None:
                if node.selected:
                    # if no root_level specified, set it to the selected nodes level
                    root_level = node.level
                    # is this the ancestor of current selected node at the root level?
            is_root_ancestor = (node.ancestor and node.level == root_level)
            # is a node selected on the root_level specified
            root_selected = (node.selected and node.level == root_level)
            if is_root_ancestor or root_selected:
                cut_after(node, levels, [])
                children = node.children
                for child in children:
                    if child.sibling:
                        cut_after(child, nephews, [])
                        # if root_level was 0 we need to give the menu the entire tree
                    # not just the children
                if include_root:
                    children = menu_renderer.apply_modifiers([node], post_cut=True)
                else:
                    children = menu_renderer.apply_modifiers(children, post_cut=True)
        context['children'] = children
        context['template'] = template
        context['from_level'] = 0
        context['to_level'] = 0
        context['extra_inactive'] = 0
        context['extra_active'] = 0
        return context
Example #22
0
def get_nodes(request, namespace=None, root_id=None):
    # Django CMS >= 3.3
    renderer = menu_pool.get_renderer(request)

    all_nodes = renderer.get_nodes(namespace=namespace,
                                   root_id=root_id,
                                   breadcrumb=False)
    all_nodes = [
        node for node in all_nodes
        if not node.attr.get('cms_named_menus_hidden', False)
    ]

    return all_nodes
Example #23
0
    def get_context(self, context, start_level, template, only_visible):
        try:
            # If there's an exception (500), default context_processors may not be called.
            request = context['request']
        except KeyError:
            return {'template': 'cms/content.html'}
        if not (isinstance(start_level, int) or start_level.isdigit()):
            only_visible = template
            template = start_level
            start_level = 0
        try:
            only_visible = bool(int(only_visible))
        except ValueError:
            only_visible = bool(only_visible)
        ancestors = []

        menu_renderer = context.get('cms_menu_renderer')

        if not menu_renderer:
            menu_renderer = menu_pool.get_renderer(request)

        nodes = menu_renderer.get_nodes(breadcrumb=True)

        # Find home
        home = None
        for node in nodes:
            if node.content and isinstance(node.content,
                                           Page) and node.content.is_home:
                home = node
                break

        # Find selected
        selected = None
        selected = next((node for node in nodes if node.selected), None)
        if selected and selected != home:
            node = selected
            while node:
                # Added  to ancestors only if node content is mapped to page/url and visible
                if node.content and node.visible or not only_visible:
                    ancestors.append(node)
                node = node.parent
        if not ancestors or (ancestors and ancestors[-1] != home) and home:
            ancestors.append(home)
        ancestors.reverse()
        if len(ancestors) >= start_level:
            ancestors = ancestors[start_level:]
        else:
            ancestors = []
        context['ancestors'] = ancestors
        context['template'] = template
        return context
Example #24
0
    def test_get_nodes(self):
        request = self.get_page_request(None, self.user, '/en/')

        try:
            # CMS 3.5+
            renderer = menu_pool.get_renderer(request)
            menu = ThingsMenu(renderer=renderer)
        except AttributeError:
            # CMS < 3.5
            menu = ThingsMenu()

        nodes = menu.get_nodes(request)
        self.thing1.set_current_language('en')
        self.thing2.set_current_language('en')
        self.assertEqualItems(
            [menuitem.title for menuitem in nodes],
            [self.thing1.name, self.thing2.name],
        )

        # Test that the DE version has 2 categories and their questions that
        # they are shown in German.
        request = self.get_page_request(None, self.user, '/de/')

        try:
            # CMS 3.5+
            renderer = menu_pool.get_renderer(request)
            menu = ThingsMenu(renderer=renderer)
        except AttributeError:
            # CMS < 3.5
            menu = ThingsMenu()

        nodes = menu.get_nodes(request)
        self.thing1.set_current_language('de')
        self.thing2.set_current_language('de')
        self.assertEqualItems(
            [menuitem.title for menuitem in nodes],
            [self.thing1.name, self.thing2.name]
        )
    def get_context(self, context, from_level, to_level, extra_inactive,
                    extra_active, template, namespace, root_id, next_page):
        try:
            # If there's an exception (500), default context_processors may not be called.
            request = context['request']
        except KeyError:
            return {'template': 'menu/empty.html'}

        menu_renderer = context.get('cms_menu_renderer')
        if not menu_renderer:
            menu_renderer = menu_pool.get_renderer(request)
        if next_page:
            # getting the nodel level
            nodes = menu_renderer.get_nodes(request, namespace, root_id)
            for n in nodes:
                if n.selected:
                    level = n.level

            # getting the children
            children = []
            for n in next_page.children:

                # in fact these are mutually exclusive  either we are a descendant either a sibling
                if n.descendant and n.level < level + 2:
                    children.append(n)

                if n.sibling or n.selected:
                    children.append(n)

        else:
            nodes = menu_renderer.get_nodes(request, namespace, root_id)
            # we find the closest ancestor (that is the one with the highest level but in fact
            # it looks like the nodes are scanned from the top to bottom that is the lowest to the highest.
            for n in nodes:
                if n.ancestor:
                    children = [n]

        try:
            context.update({
                'children': children,
                'template': template,
                'from_level': from_level,
                'to_level': to_level,
                'extra_inactive': extra_inactive,
                'extra_active': extra_active,
                'namespace': namespace
            })
        except:
            context = {"template": template}
        return context
Example #26
0
    def get_context(self, context, from_level, to_level, extra_inactive,
                    extra_active, template, namespace, root_id, next_page):
        try:
            # If there's an exception (500), default context_processors may not be called.
            request = context['request']
        except KeyError:
            return {'template': 'menu/empty.html'}

        if next_page:
            children = next_page.children
        else:
            # new menu... get all the data so we can save a lot of queries
            menu_renderer = context.get('cms_menu_renderer')

            if not menu_renderer:
                menu_renderer = menu_pool.get_renderer(request)

            nodes = menu_renderer.get_nodes(namespace, root_id)
            if root_id:  # find the root id and cut the nodes
                id_nodes = menu_pool.get_nodes_by_attribute(
                    nodes, "reverse_id", root_id)
                if id_nodes:
                    node = id_nodes[0]
                    nodes = node.children
                    for remove_parent in nodes:
                        remove_parent.parent = None
                    from_level += node.level + 1
                    to_level += node.level + 1
                    nodes = flatten(nodes)
                else:
                    nodes = []
            children = cut_levels(nodes, from_level, to_level, extra_inactive,
                                  extra_active)
            children = menu_renderer.apply_modifiers(children,
                                                     namespace,
                                                     root_id,
                                                     post_cut=True)

        try:
            context['children'] = children
            context['template'] = template
            context['from_level'] = from_level
            context['to_level'] = to_level
            context['extra_inactive'] = extra_inactive
            context['extra_active'] = extra_active
            context['namespace'] = namespace
        except:
            context = {"template": template}
        return context
Example #27
0
    def get_context(self, context, start_level, template, only_visible):
        try:
            # If there's an exception (500), default context_processors may not be called.
            request = context['request']
        except KeyError:
            return {'template': 'cms/content.html'}
        if not (isinstance(start_level, int) or start_level.isdigit()):
            only_visible = template
            template = start_level
            start_level = 0
        try:
            only_visible = bool(int(only_visible))
        except TypeError:
            only_visible = bool(only_visible)

        ancestors = []

        menu_renderer = context.get('cms_menu_renderer')

        if not menu_renderer:
            menu_renderer = menu_pool.get_renderer(request)

        nodes = menu_renderer.get_nodes(breadcrumb=True)

        # Find home
        root_url = unquote(reverse("pages-root"))
        home = next(
            (node for node in nodes if node.get_absolute_url() == root_url),
            None)

        # Find selected
        selected = next((node for node in nodes if node.selected), None)

        if selected and selected != home:
            node = selected
            while node:
                if node.visible or not only_visible:
                    ancestors.append(node)
                node = node.parent
        if not ancestors or (ancestors and ancestors[-1] != home) and home:
            ancestors.append(home)
        ancestors.reverse()
        if len(ancestors) >= start_level:
            ancestors = ancestors[start_level:]
        else:
            ancestors = []
        context['ancestors'] = ancestors
        context['template'] = template
        return context
Example #28
0
    def test_get_nodes(self):
        request = self.get_page_request(None, self.user, '/en/')

        try:
            # CMS 3.5+
            renderer = menu_pool.get_renderer(request)
            menu = ThingsMenu(renderer=renderer)
        except AttributeError:
            # CMS < 3.5
            menu = ThingsMenu()

        nodes = menu.get_nodes(request)
        self.thing1.set_current_language('en')
        self.thing2.set_current_language('en')
        self.assertEqualItems(
            [menuitem.title for menuitem in nodes],
            [self.thing1.name, self.thing2.name],
        )

        # Test that the DE version has 2 categories and their questions that
        # they are shown in German.
        request = self.get_page_request(None, self.user, '/de/')

        try:
            # CMS 3.5+
            renderer = menu_pool.get_renderer(request)
            menu = ThingsMenu(renderer=renderer)
        except AttributeError:
            # CMS < 3.5
            menu = ThingsMenu()

        nodes = menu.get_nodes(request)
        self.thing1.set_current_language('de')
        self.thing2.set_current_language('de')
        self.assertEqualItems([menuitem.title for menuitem in nodes],
                              [self.thing1.name, self.thing2.name])
Example #29
0
    def test_hide_untranslated(self):
        TESTLANG = get_primary_language()
        TESTLANG2 = get_secondary_language()
        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)

        lang_settings = copy.deepcopy(get_cms_setting("LANGUAGES"))

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

        request_1_menu_renderer = menu_pool.get_renderer(request_1)
        request_2_menu_renderer = menu_pool.get_renderer(request_2)

        lang_settings[1][1]["hide_untranslated"] = False
        with self.settings(CMS_LANGUAGES=lang_settings):
            request_1_nodes = request_1_menu_renderer.get_menu("CMSMenu").get_nodes(request_1)
            request_2_nodes = request_2_menu_renderer.get_menu("CMSMenu").get_nodes(request_2)
            list_1 = [node.id for node in request_1_nodes]
            list_2 = [node.id for node in request_2_nodes]
            self.assertEqual(list_1, list_2)
            self.assertEqual(len(list_1), 2)

        lang_settings[1][1]["hide_untranslated"] = True
        with self.settings(CMS_LANGUAGES=lang_settings):
            request_1_nodes = request_1_menu_renderer.get_menu("CMSMenu").get_nodes(request_1)
            request_2_nodes = request_2_menu_renderer.get_menu("CMSMenu").get_nodes(request_2)
            list_1 = [node.id for node in request_1_nodes]
            list_2 = [node.id for node in request_2_nodes]
            self.assertNotEqual(list_1, list_2)
            self.assertEqual(len(list_2), 1)
            self.assertEqual(len(list_1), 2)
Example #30
0
    def get_context(self, context, start_level, template, only_visible):
        try:
            # If there's an exception (500), default context_processors may not be called.
            request = context['request']
        except KeyError:
            return {'template': 'cms/content.html'}
        if not (isinstance(start_level, int) or start_level.isdigit()):
            only_visible = template
            template = start_level
            start_level = 0
        try:
            only_visible = bool(int(only_visible))
        except:
            only_visible = bool(only_visible)
        ancestors = []

        menu_renderer = context.get('cms_menu_renderer')

        if not menu_renderer:
            menu_renderer = menu_pool.get_renderer(request)

        nodes = menu_renderer.get_nodes(breadcrumb=True)

        # Find home
        home = None
        root_url = unquote(reverse("pages-root"))
        home = next((node for node in nodes if node.get_absolute_url() == root_url), None)

        # Find selected
        selected = None
        selected = next((node for node in nodes if node.selected), None)

        if selected and selected != home:
            node = selected
            while node:
                if node.visible or not only_visible:
                    ancestors.append(node)
                node = node.parent
        if not ancestors or (ancestors and ancestors[-1] != home) and home:
            ancestors.append(home)
        ancestors.reverse()
        if len(ancestors) >= start_level:
            ancestors = ancestors[start_level:]
        else:
            ancestors = []
        context['ancestors'] = ancestors
        context['template'] = template
        return context
    def get_value(self, context, type):

        request = context['request']

        namespace = None
        root_id = None

        menu_renderer = context.get('cms_menu_renderer')
        if not menu_renderer:
            menu_renderer = menu_pool.get_renderer(request)
        if type == "title":
            return menu_renderer.get_nodes(request, namespace,
                                           root_id)[0].get_menu_title()
        elif type == "url":
            return menu_renderer.get_nodes(request, namespace,
                                           root_id)[0].get_absolute_url()
        else:
            return "UNKNOWN"
Example #32
0
    def get_context(self, context, from_level, to_level, extra_inactive,
                    extra_active, template, namespace, root_id, next_page):
        try:
            # If there's an exception (500), default context_processors may not be called.
            request = context['request']
        except KeyError:
            return {'template': 'menu/empty.html'}

        if next_page:
            children = next_page.children
        else:
            # new menu... get all the data so we can save a lot of queries
            menu_renderer = context.get('cms_menu_renderer')

            if not menu_renderer:
                menu_renderer = menu_pool.get_renderer(request)

            nodes = menu_renderer.get_nodes(namespace, root_id)
            if root_id:  # find the root id and cut the nodes
                id_nodes = menu_pool.get_nodes_by_attribute(nodes, "reverse_id", root_id)
                if id_nodes:
                    node = id_nodes[0]
                    nodes = node.children
                    for remove_parent in nodes:
                        remove_parent.parent = None
                    from_level += node.level + 1
                    to_level += node.level + 1
                    nodes = flatten(nodes)
                else:
                    nodes = []
            children = cut_levels(nodes, from_level, to_level, extra_inactive, extra_active)
            children = menu_renderer.apply_modifiers(children, namespace, root_id, post_cut=True)

        try:
            context['children'] = children
            context['template'] = template
            context['from_level'] = from_level
            context['to_level'] = to_level
            context['extra_inactive'] = extra_inactive
            context['extra_active'] = extra_active
            context['namespace'] = namespace
        except:
            context = {"template": template}
        return context
Example #33
0
    def get_context(self, context, template, namespace, root_id, offset, limit,
                    embody_root, next_page):
        try:
            # If there's an exception (500), default context_processors may not be called.
            request = context['request']
        except KeyError:
            return {'template': 'menu/empty.html'}

        start_level = 0

        if next_page:
            children = next_page.children
        else:
            menu_renderer = context.get('cms_menu_renderer')

            if not menu_renderer:
                menu_renderer = menu_pool.get_renderer(request)

            nodes = menu_renderer.get_nodes(namespace, root_id)
            if root_id:
                # find the root id and cut the nodes
                id_nodes = menu_pool.get_nodes_by_attribute(
                    nodes, "reverse_id", root_id)
                if id_nodes:
                    node = id_nodes[0]
                    nodes = node.children
                    for remove_parent in nodes:
                        remove_parent.parent = None
                    start_level = node.level + 1
                    nodes = flatten(nodes)
                    if embody_root:
                        node.level = start_level
                        nodes.insert(0, node)
                else:
                    nodes = []
            children = cut_levels(nodes, start_level)
            children = menu_renderer.apply_modifiers(children,
                                                     namespace,
                                                     root_id,
                                                     post_cut=True)
            children = children[offset:offset + limit]
        context.update({'children': children, 'template': template})
        return context
 def _get_menu_renderer():
     # We use lru_cache to avoid getting the manager
     # every time this function is called.
     from menus.menu_pool import menu_pool
     return menu_pool.get_renderer(request)
Example #35
0
 def get_context(self, context, start_level, template, only_visible):
     try:
         # If there's an exception (500), default context_processors may not be called.
         request = context['request']
     except KeyError:
         return {'template': 'cms/content.html'}
     if not (isinstance(start_level, int) or start_level.isdigit()):
         only_visible = template
         template = start_level
         start_level = 0
     try:
         only_visible = bool(int(only_visible))
     except:
         only_visible = bool(only_visible)
     branch = []
     menu_renderer = context.get('cms_menu_renderer')
     if not menu_renderer:
         menu_renderer = menu_pool.get_renderer(request)
     nodes = menu_renderer.get_nodes(request, breadcrumb=False) # fait appel à deepcopy, False pour appeler AuthVisibility.modify
     selected = None
     home = None
     homeurl = unquote(reverse("pages-root"))
     debug_allnodes = []
     for node in nodes:
         #print()
         #print(node.title)
         #print(node.visible)
         #print(node.attr)
         # debug_allnodes.append((node.title, node.selected))
         if node.selected:
             selected = node
         if node.get_absolute_url() == homeurl:
             home = node
     if selected: #and selected != home:
         node = selected
         childnode = None
         level = 0
         color = 100
         while node:
             node.attr['color'] = "bread-" + str(color)
             if node == home:
                 node.attr['color'] = "bread-100"
             if level < 3:
                 color -= 20
                 node.attr['display'] = node.title
             else:
                 node.attr['display'] = '…'
             childs = []
             for c in node.children:
                 if c != childnode:
                     c.attr['display'] = node.title
                     c.attr['color'] = ''
                 childs.append(c)
             node.attr['childs'] = childs
             if node.visible or not only_visible:
                 branch.append(node)
             level += 1
             childnode = node
             node = node.parent
     if not branch or (branch and branch[-1] != home) and home:
         branch.append(home)
     branch.reverse()
     if len(branch) >= start_level:
         branch = branch[start_level:]
     else:
         branch = []
     context.update({'branch': branch,
                     'template': template,
                     'homeurl': homeurl,
                     'allnodes': debug_allnodes})
     return context
Example #36
0
 def _get_menu_renderer():
     # We use lru_cache to avoid getting the manager
     # every time this function is called.
     from menus.menu_pool import menu_pool
     return menu_pool.get_renderer(request)
Example #37
0
 def get_nodes(self, menu_pool, request):
     try:
         nodes = menu_pool.get_renderer(request).get_nodes()
     except AttributeError:
         nodes = menu_pool.get_nodes(request)
     return nodes
Example #38
0
 def setUp(self):
     self.request = RequestFactory().get("/")
     self.user = factories.UserFactory()
     self.request.user = self.user
     self.renderer = menu_pool.get_renderer(self.request)
     self.menu = CMSMenu(self.renderer)
    def get_context(self, context, from_level, to_level, extra_inactive,
                    extra_active, template, namespace, root_id, next_page):
        try:
            # If there's an exception (500), default context_processors may not be called.
            request = context['request']
        except KeyError:
            return {'template': 'menu/empty.html'}

        activeul = ''
        activehref = ''

        menu_renderer = context.get('cms_menu_renderer')
        if not menu_renderer:
            menu_renderer = menu_pool.get_renderer(request)

        if next_page:
            children = next_page.children
        else:
            # new menu... get all the data so we can save a lot of queries
            nodes = menu_renderer.get_nodes(request, namespace, root_id)
            if root_id:  # find the root id and cut the nodes
                id_nodes = menu_renderer.get_nodes_by_attribute(
                    nodes, "reverse_id", root_id)
                if id_nodes:
                    node = id_nodes[0]
                    nodes = node.children
                    for remove_parent in nodes:
                        remove_parent.parent = None
                    from_level += node.level + 1
                    to_level += node.level + 1
                    nodes = flatten(nodes)
                else:
                    nodes = []

        nodes = menu_renderer.get_nodes(request, namespace, root_id)

        isleafnode = False
        for n in nodes:
            if n.selected:
                if n.is_leaf_node:
                    isleafnode = True
                    ancestor = "/".join(
                        n.get_absolute_url().split('/')[0:-3]) + '/'
                    directancestor = "/".join(
                        n.get_absolute_url().split('/')[0:-2]) + '/'
                    from_level = n.level - 2
                else:
                    ancestor = "/".join(
                        n.get_absolute_url().split('/')[0:-2]) + '/'
                    directancestor = "/".join(
                        n.get_absolute_url().split('/')[0:-1]) + '/'
                    from_level = n.level - 1
                activehref = n
                #           print "ancestor",n.get_absolute_url(),ancestor,directancestor,from_level
                continue

        for n in nodes:
            #        print n.get_absolute_url() ==  directancestor,n.get_absolute_url(),directancestor
            if n.get_absolute_url() == directancestor:
                activeul = n
                continue

        to_level = from_level + 2
        if next_page:
            to_level = 100
            children = next_page.children
        else:

            children = cut_levels(nodes, from_level, to_level, extra_inactive,
                                  extra_active)
            children = menu_pool.apply_modifiers(children,
                                                 request,
                                                 namespace,
                                                 root_id,
                                                 post_cut=True)

        #print "activeul",activeul.get_absolute_url()
        #print "activehref",activehref.get_absolute_url()
        #print "ancestor",ancestor
        #print "directancestor",directancestor
        #print "BEFORE children",children

        newChildren = []
        for i in children:
            #print i.level,i.get_absolute_url(),
            if i.get_absolute_url().startswith(ancestor[:-1]):
                #print "kept",
                newChildren.append(i)
            #print ""

        try:
            #print "AFTER children",newChildren
            context.update({
                'children': newChildren,
                'activehref': activehref,
                'activeul': activeul,
                'ancestor': ancestor,
                'template': template,
                'from_level': from_level,
                'to_level': to_level,
                'extra_inactive': extra_inactive,
                'extra_active': extra_active,
                'namespace': namespace
            })
        except:
            context = {"template": template}
        return context