Пример #1
0
 def testTranslatingDefaultPagePutsItIntoTranslatedParentFolder(self):
     english_folder = self.folder
     makeTranslation(english_folder, 'de')  # translated folder exists
     english_doc = makeContent(english_folder, 'SimpleType', 'doc')
     english_folder.setDefaultPage(english_doc.getId())
     makeTranslation(english_doc,
                     'de').processForm(values=dict(title='dok'))
     german_folder = english_folder.getTranslation('de')
     german_doc = english_doc.getTranslation('de')
     self.assertTrue(german_doc.getId() in german_folder)
     self.assertTrue(isDefaultPage(english_folder, english_doc))
     self.assertTrue(isDefaultPage(german_folder, german_doc))
 def testTranslatingDefaultPagePutsItIntoTranslatedParentFolder(self):
     english_folder = self.folder
     makeTranslation(english_folder, 'de')   # translated folder exists
     english_doc = makeContent(english_folder, 'SimpleType', 'doc')
     english_folder.setDefaultPage(english_doc.getId())
     makeTranslation(english_doc, 'de').processForm(
         values=dict(title='dok'))
     german_folder = english_folder.getTranslation('de')
     german_doc = english_doc.getTranslation('de')
     self.assertTrue(german_doc.getId() in german_folder)
     self.assertTrue(isDefaultPage(english_folder, english_doc))
     self.assertTrue(isDefaultPage(german_folder, german_doc))
 def testTranslatingDefaultPageInNeutralFolderDoesntCreateFolder(self):
     neutral_folder = self.folder
     neutral_folder.setLanguage('')
     english_doc = makeContent(neutral_folder, 'SimpleType', 'doc')
     english_doc.setLanguage('en')
     neutral_folder.setDefaultPage(english_doc.getId())
     makeTranslation(english_doc, 'de').processForm(
         values=dict(title='dok'))
     self.assertEqual(neutral_folder.getTranslation('de'), None)
     german_doc = english_doc.getTranslation('de')
     self.assertTrue(german_doc.getId() in neutral_folder)
     self.assertTrue(isDefaultPage(neutral_folder, english_doc))
     self.assertFalse(isDefaultPage(neutral_folder, german_doc))
Пример #4
0
 def testTranslatingDefaultPageInNeutralFolderDoesntCreateFolder(self):
     neutral_folder = self.folder
     neutral_folder.setLanguage('')
     english_doc = makeContent(neutral_folder, 'SimpleType', 'doc')
     english_doc.setLanguage('en')
     neutral_folder.setDefaultPage(english_doc.getId())
     makeTranslation(english_doc,
                     'de').processForm(values=dict(title='dok'))
     self.assertEqual(neutral_folder.getTranslation('de'), None)
     german_doc = english_doc.getTranslation('de')
     self.assertTrue(german_doc.getId() in neutral_folder)
     self.assertTrue(isDefaultPage(neutral_folder, english_doc))
     self.assertFalse(isDefaultPage(neutral_folder, german_doc))
Пример #5
0
    def siblings(self):
        if self.data.currentFolderOnly:
            return None

        before = []
        after = []
        context_path = '/'.join((self.context.getPhysicalPath()))
        context_reached = False

        catalog = getToolByName(self.context, 'portal_catalog')

        for brain in catalog(self.get_siblings_query()):
            if brain.getPath() == context_path:
                context_reached = True
                continue
            obj = brain.getObject()
            if isDefaultPage(aq_parent(aq_inner(obj)), obj):
                continue
            if not context_reached:
                before.append(brain)
            else:
                after.append(brain)

        return {'before_context': self.filter_brains(before),
                'after_context': self.filter_brains(after)}
Пример #6
0
    def siblings(self):
        if self.data.currentFolderOnly:
            return None

        parent = aq_parent(aq_inner(self.context))
        before = []
        after = []
        context_path = '/'.join((self.context.getPhysicalPath()))
        context_reached = False

        catalog = getToolByName(self.context, 'portal_catalog')
        query = {'path': {'query': '/'.join((parent.getPhysicalPath())),
                          'depth': 1},
                 'sort_on': 'getObjPositionInParent'}

        for brain in catalog(query):
            if brain.getPath() == context_path:
                context_reached = True
                continue
            obj = brain.getObject()
            if isDefaultPage(aq_parent(aq_inner(obj)), obj):
                continue
            if not context_reached:
                before.append(brain)
            else:
                after.append(brain)

        return {'before_context': self.filter_brains(before),
                'after_context': self.filter_brains(after)}
Пример #7
0
    def sub_objects(self, parent, level=0, query=None):
        """ Returns the sub objects of a given parent.
        Checks if the objects should be listed in navi.
        """
        # if the parent is the portal and its not level 0,
        # return no children
        portal = getToolByName(self.context, 'portal_url').getPortalObject()
        if parent == portal and level > 0:
            return []

        if isinstance(parent, ActionInfo):
            return []

        objs = []
        properties = getToolByName(self.context, 'portal_properties')
        hidden_types = properties.navtree_properties.metaTypesNotToList
        for brain in parent.getFolderContents(contentFilter=query):
            if brain.portal_type in hidden_types:
                continue
            if getattr(brain, 'exclude_from_nav', False) \
                    not in [Missing.Value, False]:
                continue

            obj = brain.getObject()
            if isDefaultPage(aq_parent(aq_inner(obj)), obj):
                continue

            objs.append(obj)

        if parent == portal:
            self.prepend_actions(objs)

        return objs
Пример #8
0
    def index(self):
        sm = getSecurityManager()
        context = aq_inner(self.context)
        container = aq_parent(context)

        if isDefaultPage(container, context):
            context = container


        # avoid redirecting if we are visiting an url different from the url of the context
        viewname = self.context.getLayout()
        if self.request.URL != self.context.absolute_url() and self.request.URL != self.context.absolute_url() + '/' + viewname:
            return ''

        originalcontext = context

        while all([not INavigationRoot.providedBy(context),
                   IRedirectToParent.providedBy(context), 
                   not sm.checkPermission(ModifyPortalContent, context)]):
#            contextid = context.id
            context = aq_parent(context)

        if context != originalcontext:
            viewurl = getMultiAdapter((context, self.request), name='plone_context_state').view_url()
            self.request.RESPONSE.redirect(viewurl + '#content=' + originalcontext.absolute_url())

        return ''
Пример #9
0
    def __call__(self):
        # Disable theming for ajax requests
        self.request.response.setHeader('X-Theme-Disabled', 'True')

        properties = getToolByName(self.context, 'portal_properties')
        view_action_types = properties.site_properties.getProperty(
            'typesUseViewActionInListings', ())

        context = self.context
        if isDefaultPage(aq_parent(aq_inner(context)), context):
            # When asked for the navigation of a default page, return
            # the navigation of its parent, because the user is actually
            # on the parent but viewing the default page and the base-url
            # makes the request be fired on the default page.
            context = aq_parent(aq_inner(context))

        subnavi = '<ul>'
        level = int(self.request.form.get('level', '1'))
        if level == 0:
            subnavi = '<ul id="portal-globalnav" class="mobileNavigation">'
        for obj in self.sub_objects(context, level=level):
            url = obj.absolute_url()
            if obj.portal_type in view_action_types:
                url = obj.absolute_url() + '/view'
            subnavi += '<li class="%s"><a href="%s">%s</a></li>' % (
                self.get_css_classes(obj),
                url,
                escape_html(obj.Title()))
        subnavi += '</ul>'
        return subnavi
Пример #10
0
 def create(self):
     """
     project1/
     project1/welcome        (page set as default page for project)
     project1/team1/
     project1/team1/stuff    (folder)
     project1/team2
     project1/folder1        (folder)
     otherstuff/             (folder)
     """
     project = self.add_project('project1')
     welcome = self.add_content(
         'Document',
         'welcome',
         title='Welcome',
         parent=project,
         )
     project.default_page = 'welcome'
     assert isDefaultPage(container=project, obj=welcome)
     team1 = self.add_workspace_to(project, 'team1')
     self.add_content('Folder', 'stuff', title='Folder A', parent=team1)
     team2 = self.add_workspace_to(project, 'team2')  # noqa
     self.add_content('Folder', 'folder1', title='Folder1', parent=project)
     assert 'folder1' in project.contentIds()
     self.add_content(
         'Folder',
         'otherstuff',
         title='not in project',
         parent=self.portal,
         )
Пример #11
0
    def siblings(self):
        if self.data.currentFolderOnly:
            return None

        before = []
        after = []
        context_path = '/'.join((self.context.getPhysicalPath()))
        context_reached = False

        catalog = getToolByName(self.context, 'portal_catalog')

        for brain in catalog(self.get_siblings_query()):
            if brain.getPath() == context_path:
                context_reached = True
                continue
            obj = brain.getObject()
            if isDefaultPage(aq_parent(aq_inner(obj)), obj):
                continue
            if not context_reached:
                before.append(brain)
            else:
                after.append(brain)

        return {
            'before_context': self.filter_brains(before),
            'after_context': self.filter_brains(after)
        }
Пример #12
0
    def resolveRelativeLink(self, context, link):
        url = link.get('href', '')

        if not url.strip():
            return

        if url.startswith('#'):
            return

        if '://' in url and url.index('://') <= 5:
            return

        if url.startswith('/'):
            context = self.context.portal_url.getPortalObject()
            url = url.lstrip('/')

        url = url.encode('utf-8')

        try:
            obj = context.restrictedTraverse(url)
        except NotFound:
            obj = context
        else:
            parent = obj.aq_parent
            if isDefaultPage(parent, obj):
                obj = parent

        link['href'] = obj.absolute_url()
Пример #13
0
    def sub_objects(self, parent, level=0, query=None):
        """ Returns the sub objects of a given parent.
        Checks if the objects should be listed in navi.
        """
        # if the parent is the portal and its not level 0,
        # return no children
        portal = getToolByName(self.context, 'portal_url').getPortalObject()
        if parent == portal and level > 0:
            return []

        if isinstance(parent, ActionInfo):
            return []

        objs = []
        properties = getToolByName(self.context, 'portal_properties')
        hidden_types = properties.navtree_properties.metaTypesNotToList
        for brain in parent.getFolderContents(contentFilter=query):
            if brain.portal_type in hidden_types:
                continue
            if getattr(brain, 'exclude_from_nav', False) \
                    not in [Missing.Value, False]:
                continue

            obj = brain.getObject()
            if isDefaultPage(aq_parent(aq_inner(obj)), obj):
                continue

            objs.append(obj)

        if parent == portal:
            self.prepend_actions(objs)

        return objs
Пример #14
0
    def index(self):
        context = aq_inner(self.context)

        container = aq_parent(context)

        if isDefaultPage(container, context):
            context = container

        originalcontext = context

        # avoid redirecting if we are visiting an url different from the url of the context
        viewname = self.context.getLayout()
        if self.request.URL != self.context.absolute_url() and self.request.URL != self.context.absolute_url() + '/' + viewname:
            return ''

        while all([not INavigationRoot.providedBy(context),
                   IRedirectToParent.providedBy(context)]):
#            contextid = context.id
            context = aq_parent(context)

        if context != originalcontext:
            viewurl = getMultiAdapter((context, self.request), name='plone_context_state').view_url()
            return u'<a class="redirect-to-parent" href="%s">%s</a>' % (viewurl + '#content=' + originalcontext.absolute_url(),context.Title())
        else:
            return ''
Пример #15
0
    def __call__(self):
        # Disable theming for ajax requests
        self.request.response.setHeader('X-Theme-Disabled', 'True')

        properties = getToolByName(self.context, 'portal_properties')
        view_action_types = properties.site_properties.getProperty(
            'typesUseViewActionInListings', ())

        context = self.context
        if isDefaultPage(aq_parent(aq_inner(context)), context):
            # When asked for the navigation of a default page, return
            # the navigation of its parent, because the user is actually
            # on the parent but viewing the default page and the base-url
            # makes the request be fired on the default page.
            context = aq_parent(aq_inner(context))

        subnavi = '<ul>'
        level = int(self.request.form.get('level', '1'))
        if level == 0:
            subnavi = '<ul id="portal-globalnav" class="mobileNavigation">'
        for obj in self.sub_objects(context, level=level):
            is_action = isinstance(obj, ActionInfo)
            if is_action:
                url = obj['url']
                title = translate(obj['title'], context=self.request)
            else:
                url = obj.absolute_url()
                title = obj.Title()
            if not is_action and obj.portal_type in view_action_types:
                url = obj.absolute_url() + '/view'
            subnavi += '<li class="%s"><a href="%s">%s</a></li>' % (
                self.get_css_classes(obj), url, escape_html(title))
        subnavi += '</ul>'
        return subnavi
    def __call__(self):
        context = aq_inner(self.context)
        container = aq_parent(context)

        if isDefaultPage(container, context):
            context = container

        return IRedirectToParent.providedBy(context)
Пример #17
0
 def collection_url(self):
     collection = self.collection()
     if collection is None:
         return
     parent = collection.aq_parent
     if isDefaultPage(parent, collection):
         collection = parent
     return collection.absolute_url()
Пример #18
0
 def collection_url(self):
     collection = self.collection()
     if collection is None:
         return
     parent = collection.aq_parent
     if isDefaultPage(parent, collection):
         collection = parent
     return collection.absolute_url()
Пример #19
0
 def base_url(self):
     context = aq_inner(self.context)
     parent = aq_parent(context)
     request_url = self.request['ACTUAL_URL']
     context_url = context.absolute_url()
     if isDefaultPage(parent, context) \
       and not request_url.startswith(context_url):
         context = parent
     return context.absolute_url()
 def form_fields(self):
     form_fields = FormFields(ISearchReplaceForm)
     container = aq_parent(self.context)
     if not self.context.isPrincipiaFolderish and not isDefaultPage(
             container, self.context):
         form_fields = form_fields.omit('searchSubfolders')
     form_fields['findWhat'].custom_widget = TwoLineTextAreaWidget
     form_fields['replaceWith'].custom_widget = TwoLineTextAreaWidget
     return form_fields
Пример #21
0
 def update(self):
     is_default_page = isDefaultPage(self.container, self.context)
     can_review = checkPermission('cmf.ReviewPortalContent', self.container)
     if is_default_page and can_review:
         wftool = getToolByName(self.context,'portal_workflow')
         if len(wftool.getChainFor(self.context)) and len(wftool.getChainFor(self.container)):
             page_wf_state = len(wftool.getChainFor(self.context)) and wftool.getInfoFor(self.context, 'review_state')
             container_wf_state = wftool.getInfoFor(self.container, 'review_state')
             self.visible = page_wf_state != container_wf_state
Пример #22
0
 def root_item_class(self):
     context = aq_inner(self.context)
     root = self.getNavRoot()
     container = aq_parent(context)
     if (aq_base(root) is aq_base(context) or
             (aq_base(root) is aq_base(container) and
             isDefaultPage(container, context))):
         return 'navTreeCurrentItem'
     return ''
Пример #23
0
 def form_fields(self):
     form_fields = FormFields(ISearchReplaceForm)
     container = aq_parent(self.context)
     if not self.context.isPrincipiaFolderish and not isDefaultPage(
             container, self.context):
         form_fields = form_fields.omit("searchSubfolders")
     form_fields["findWhat"].custom_widget = TwoLineTextAreaWidget
     form_fields["replaceWith"].custom_widget = TwoLineTextAreaWidget
     return form_fields
Пример #24
0
 def root_item_class(self):
     context = aq_inner(self.context)
     root = self.getNavRoot()
     container = aq_parent(context)
     if (aq_base(root) is aq_base(context)
             or (aq_base(root) is aq_base(container)
                 and isDefaultPage(container, context))):
         return 'navTreeCurrentItem'
     return ''
    def __call__(self):

        context = aq_inner(self.context)
        container = aq_parent(context)

        if isDefaultPage(container, context):
            context = container

        if IPloneSiteRoot.providedBy(context) or INavigationRoot.providedBy(context):
            return False

        return True
    def getTranslations(self):
        context = self.context.aq_inner
        parent = context.__parent__
        if isDefaultPage(parent, context):
            if not INavigationRoot.providedBy(parent):
                context = parent

        lang_items = ITranslationGraph(context).getNearestTranslations()

        translations = {}
        for lang_id, item, distance in lang_items:
            if item is None:
                continue

            parent = item.__parent__
            if isDefaultPage(parent, item):
                item = parent

            translations[lang_id] = item

        return translations
Пример #27
0
 def update(self):
     is_default_page = isDefaultPage(self.container, self.context)
     can_review = checkPermission('cmf.ReviewPortalContent', self.container)
     if is_default_page and can_review:
         wftool = getToolByName(self.context, 'portal_workflow')
         if len(wftool.getChainFor(self.context)) and len(
                 wftool.getChainFor(self.container)):
             page_wf_state = len(wftool.getChainFor(
                 self.context)) and wftool.getInfoFor(
                     self.context, 'review_state')
             container_wf_state = wftool.getInfoFor(self.container,
                                                    'review_state')
             self.visible = page_wf_state != container_wf_state
Пример #28
0
    def resolveRelativeLink(self, context, link):
        url = link.get('href', '')

        if not url.strip():
            return
        
        if(url.startswith('resolveuid')):
            url = self.resolveuid(url)
        portal_base = self.context.portal_url() + '/'
        if(url.startswith(self.context.portal_url())):
            url = url.replace(portal_base, '')
        portal_base = self.context.portal_url.absolute_url_path().replace('/portal_url', '') + '/'
        if(url.startswith(portal_base)):
            url = url.replace(portal_base, '')
        if url.startswith('#'):
            return
        if url.startswith('mailto:'):
            return
        if url.startswith('\\\\'):
            return

        if '://' in url and url.index('://') <= 5:
            return

        if url.startswith('/'):
            context = self.context.portal_url.getPortalObject()
            url = url.lstrip('/')

        url = url.encode('utf-8')

        try:
            obj = context.restrictedTraverse(urllib.unquote(url))
        except NotFound:
            obj = context
        except AttributeError as e:
            rds = queryUtility(IRedirectionStorage)
            new_path = rds.get(getToolByName(self.context, 'portal_url').getPortalPath() + '/' + urllib.unquote(url))
            if new_path:
                obj = context.restrictedTraverse(new_path)
            else:
                logger.warn('error resolving url: %s exception: %s' % (link.get('href', ''), repr(e)))
                return
        except Exception as e:
            logger.warn('error resolving url: %s exception: %s' % (link.get('href', ''), repr(e)))
            return
        else:
            parent = obj.aq_parent
            if isDefaultPage(parent, obj):
                obj = parent

        link['href'] = '#%s' % obj.UID()
def make_catalog_query_args(context, findWhat, searchSubFolders,
                            onlySearchableText):
    # Get items to search
    query = {"query": "/".join(context.getPhysicalPath())}
    if context.isPrincipiaFolderish and not searchSubFolders:
        query["depth"] = 1
    container = aq_parent(context)
    if isDefaultPage(container, context) and searchSubFolders:
        query["query"] = "/".join(container.getPhysicalPath())
    catalog_query_args = dict(path=query)
    if settings().restrict_searchable_types:
        catalog_query_args["portal_type"] = settings().enabled_types
    if onlySearchableText:
        catalog_query_args["SearchableText"] = u"*{0}*".format(findWhat)
    return catalog_query_args
    def __call__(self):

        context = aq_inner(self.context)
        container = aq_parent(context)

        if isDefaultPage(container, context):
            context = container

        if IPloneSiteRoot.providedBy(context) or INavigationRoot.providedBy(context):
            self.request.RESPONSE.redirect(self.viewurl)

        if IRedirectToParent.providedBy(context):
            noLongerProvides(context, IRedirectToParent)
        else:
            alsoProvides(context, IRedirectToParent)

        self.request.RESPONSE.redirect(self.viewurl)
    def get_context(self):
        context = aq_inner(self.context)
        container = aq_parent(context)

        if isDefaultPage(container, context):
            context = container

        if self.data.relative_to_contenttype:
            if hasattr(self.data, 'relative_to_ct_inherit') and self.data.relative_to_ct_inherit:
                while context.portal_type != self.data.relative_to_contenttype:
                    if INavigationRoot.providedBy(context):
                        return None # parent not found
                    context = aq_parent(context)
            else:
                if context.portal_type != self.data.relative_to_contenttype:
                    return None # parent not found
            
        return context
Пример #32
0
    def __call__(self):
        # Disable theming for ajax requests
        self.request.response.setHeader('X-Theme-Disabled', 'True')

        context = self.context
        if isDefaultPage(aq_parent(aq_inner(context)), context):
            # When asked for the navigation of a default page, return
            # the navigation of its parent, because the user is actually
            # on the parent but viewing the default page and the base-url
            # makes the request be fired on the default page.
            context = aq_parent(aq_inner(context))

        self.parent = None
        if not IPloneSiteRoot.providedBy(context):
            self.parent = aq_parent(aq_inner(context))

        self.children = self.sub_objects(context)

        return self.template()
Пример #33
0
    def __call__(self):
        # Disable theming for ajax requests
        self.request.response.setHeader('X-Theme-Disabled', 'True')

        context = self.context
        if isDefaultPage(aq_parent(aq_inner(context)), context):
            # When asked for the navigation of a default page, return
            # the navigation of its parent, because the user is actually
            # on the parent but viewing the default page and the base-url
            # makes the request be fired on the default page.
            context = aq_parent(aq_inner(context))

        self.parent = None
        if not IPloneSiteRoot.providedBy(context):
            self.parent = aq_parent(aq_inner(context))

        self.children = self.sub_objects(context)

        return self.template()
Пример #34
0
 def create(self):
     """
     project1/
     project1/welcome        (page set as default page for project)
     project1/team1/
     project1/team1/stuff    (folder)
     project1/team2
     project1/folder1        (folder)
     otherstuff/             (folder)
     """
     _add_team = self.add_workspace_to
     layer = self.layer
     if layer in (TEAM_PROFILE_TESTING, TEAM_PROFILE_FUNCTIONAL_TESTING):
         _add_team = self.add_team_to
     project = self.add_project('project1')
     project2 = self.add_project('project2')
     welcome = self.add_content(
         'Document',
         'welcome',
         title='Welcome',
         parent=project,
         )
     project.default_page = 'welcome'
     assert isDefaultPage(container=project, obj=welcome)
     team1 = _add_team(project, 'team1')
     self.add_content('Folder', 'stuff', title='Folder A', parent=team1)
     team2 = _add_team(project, 'team2')  # noqa
     self.add_content(
         'Folder',
         'folder1',
         title='Folder1',
         parent=project,
         )
     assert 'folder1' in project.contentIds()
     self.add_content(
         'Folder',
         'otherstuff',
         title='not in project',
         parent=self.portal,
         )
     # sub-team workspace:
     _add_team(team1, 'subteam')
Пример #35
0
    def __call__(self):
        # Disable theming for ajax requests
        self.request.response.setHeader('X-Theme-Disabled', 'True')

        properties = getToolByName(self.context, 'portal_properties')
        view_action_types = properties.site_properties.getProperty(
            'typesUseViewActionInListings', ())

        context = self.context
        if isDefaultPage(aq_parent(aq_inner(context)), context):
            # When asked for the navigation of a default page, return
            # the navigation of its parent, because the user is actually
            # on the parent but viewing the default page and the base-url
            # makes the request be fired on the default page.
            context = aq_parent(aq_inner(context))

        subnavi = u'<ul>'
        level = int(self.request.form.get('level', '1'))
        if level == 0:
            subnavi = u'<ul id="portal-globalnav" class="mobileNavigation">'
        for obj in self.sub_objects(context, level=level):
            is_action = isinstance(obj, ActionInfo)
            if is_action:
                url = obj['url']
                title = translate(obj['title'], context=self.request)
            else:
                url = obj.absolute_url()
                title = obj.Title()

            # not all objects have the unicode url and titles
            url = safe_unicode(url)
            title = safe_unicode(title)

            if not is_action and obj.portal_type in view_action_types:
                url = safe_unicode(obj.absolute_url() + '/view')

            subnavi += u'<li class="{}"><a href="{}">{}</a></li>'.format(
                self.get_css_classes(obj),
                url,
                escape_html(title))
        subnavi += u'</ul>'
        return subnavi
Пример #36
0
 def create(self):
     """
     project1/
     project1/welcome        (page set as default page for project)
     project1/team1/
     project1/team1/stuff    (folder)
     project1/team2
     project1/folder1        (folder)
     otherstuff/             (folder)
     """
     _add_team = self.add_workspace_to
     layer = self.layer
     if layer in (TEAM_PROFILE_TESTING, TEAM_PROFILE_FUNCTIONAL_TESTING):
         _add_team = self.add_team_to
     project = self.add_project('project1')
     project2 = self.add_project('project2')
     welcome = self.add_content(
         'Document',
         'welcome',
         title='Welcome',
         parent=project,
     )
     project.default_page = 'welcome'
     assert isDefaultPage(container=project, obj=welcome)
     team1 = _add_team(project, 'team1')
     self.add_content('Folder', 'stuff', title='Folder A', parent=team1)
     team2 = _add_team(project, 'team2')  # noqa
     self.add_content(
         'Folder',
         'folder1',
         title='Folder1',
         parent=project,
     )
     assert 'folder1' in project.contentIds()
     self.add_content(
         'Folder',
         'otherstuff',
         title='not in project',
         parent=self.portal,
     )
     # sub-team workspace:
     _add_team(team1, 'subteam')
    def getAllMessages(self):
        catalog = api.portal.get_tool(name='portal_catalog')
        # Getting user roles on context
        if api.user.is_anonymous():
            mb_roles = set(['Anonymous'])
        else:
            mb_roles = set(api.user.get_roles(obj=self.context))
        now = DateTime()
        brains = catalog.unrestrictedSearchResults(portal_type=['Message'],
                                                   start={'query': now, 'range': 'max'},
                                                   end={'query': now, 'range': 'min'},
                                                   review_state=('activated'),
                                                   sort_on='getObjPositionInParent')
        messages = []
        for brain in brains:
            if brain.location == 'homepage':
                # Test if context is PloneSite or its default page
                if not IPloneSiteRoot.providedBy(self.context) and \
                        not isDefaultPage(self.portal, self.context):
                    continue
            obj = brain._unrestrictedGetObject()
            # check in the cookie if message is marked as read
            if obj.can_hide:
                m_uids = self.request.get('messagesviewlet', '')
                if obj.hidden_uid in m_uids.split('|'):
                    continue
            # check if member has a required role on the context
            if obj.required_roles:
                if mb_roles.intersection(obj.required_roles) == set():
                    continue
            # We define obj.context to viewlet context to evaluate expression on viewlet context display.
            if not evaluateExpressionFor(obj, extra_expr_ctx={'context': self.context}):
                continue
            # We check the local roles
            if obj.use_local_roles and not api.user.is_anonymous() and 'Reader' not in api.user.get_roles(obj=obj):
                continue
            messages.append(obj)

        return messages
Пример #38
0
    def createTranslation(self, container, language, *args, **kwargs):
        context = aq_inner(self.context)
        canonical = context.getCanonical()
        portal_type = self.getTranslationPortalType(container, language)
        new_id = kwargs.pop(
            'id', self.generateId(container, canonical.getId(), language))
        kwargs["language"] = language
        translation = _createObjectByType(portal_type, container, new_id,
                                          *args, **kwargs)

        # If there is a custom factory method that doesn't add the
        # translation relationship, make sure it is done now.
        if translation.getCanonical() != canonical:
            translation.addTranslationReference(canonical)

        # THIS IS THE LINE WE NEED TO CUSTOMIZE
        OSHALanguageIndependentFields(canonical).copyFields(translation)

        if isDefaultPage(aq_parent(aq_inner(canonical)), canonical):
            translation._lp_default_page = True

        # If this is a folder, move translated subobjects aswell.
        if context.isPrincipiaFolderish:
            moveids = []
            for obj in context.values():
                translator = ITranslatable(obj, None)
                if translator is not None \
                   and translator.getLanguage() == language:
                    lockable = ILockable(obj, None)
                    if lockable is not None and lockable.can_safely_unlock():
                        lockable.unlock()
                    moveids.append(obj.getId())
            if moveids:
                info = context.manage_cutObjects(moveids)
                translation.manage_pasteObjects(info)

        return translation
Пример #39
0
    def createTranslation(self, container, language, *args, **kwargs):
        context = aq_inner(self.context)
        canonical = context.getCanonical()
        portal_type = self.getTranslationPortalType(container, language)
        new_id = kwargs.pop(
            'id', self.generateId(container, canonical.getId(), language))
        kwargs["language"] = language
        translation = _createObjectByType(portal_type, container,
                                          new_id, *args, **kwargs)

        # If there is a custom factory method that doesn't add the
        # translation relationship, make sure it is done now.
        if translation.getCanonical() != canonical:
            translation.addTranslationReference(canonical)

        # THIS IS THE LINE WE NEED TO CUSTOMIZE
        OSHALanguageIndependentFields(canonical).copyFields(translation)

        if isDefaultPage(aq_parent(aq_inner(canonical)), canonical):
            translation._lp_default_page = True

        # If this is a folder, move translated subobjects aswell.
        if context.isPrincipiaFolderish:
            moveids = []
            for obj in context.values():
                translator = ITranslatable(obj, None)
                if translator is not None \
                   and translator.getLanguage() == language:
                    lockable = ILockable(obj, None)
                    if lockable is not None and lockable.can_safely_unlock():
                        lockable.unlock()
                    moveids.append(obj.getId())
            if moveids:
                info = context.manage_cutObjects(moveids)
                translation.manage_pasteObjects(info)

        return translation
Пример #40
0
    def siblings(self):
        if self.data.currentFolderOnly:
            return None

        parent = aq_parent(aq_inner(self.context))
        before = []
        after = []
        context_path = '/'.join((self.context.getPhysicalPath()))
        context_reached = False

        for brain in parent.getFolderContents():
            if brain.getPath() == context_path:
                context_reached = True
                continue
            obj = brain.getObject()
            if isDefaultPage(aq_parent(aq_inner(obj)), obj):
                continue
            if not context_reached:
                before.append(brain)
            else:
                after.append(brain)

        return {'before_context': self.filter_brains(before),
                'after_context': self.filter_brains(after)}
Пример #41
0
 def default_page(self):
     return isDefaultPage(self.context.aq_parent, self.context)
Пример #42
0
 def searchObjects(self, context, find, **kwargs):
     """ Search objects and optionally do a replace. """
     # Get search parameters
     cpath = context.getPhysicalPath()
     if 'searchSubFolders' in kwargs:
         ssf = kwargs['searchSubFolders']
     else:
         ssf = True
     if 'matchCase' in kwargs:
         mc = kwargs['matchCase']
     else:
         mc = False
     onlySearchableText = kwargs.get('onlySearchableText', True)
     if 'replaceText' in kwargs:
         rtext = kwargs['replaceText']
         if rtext is None:
             # Allow replacing by an empty string.
             rtext = u''
     else:
         rtext = u''
     if 'doReplace' in kwargs:
         replace = kwargs['doReplace']
     else:
         replace = False
     if 'searchItems' in kwargs:
         sitems = kwargs['searchItems']
     else:
         sitems = None
     if 'maxResults' in kwargs:
         maxResults = kwargs['maxResults']
     else:
         maxResults = None
     # Get Regex matcher
     sflags = mc and searchflags or (searchflags | re.IGNORECASE)
     matcher = re.compile(find, sflags)
     # Get items to search
     query = {'query': '/'.join(cpath)}
     if context.isPrincipiaFolderish and not ssf:
         query['depth'] = 1
     container = aq_parent(context)
     if isDefaultPage(container, context) and ssf:
         query['query'] = '/'.join(container.getPhysicalPath())
     catalog = getToolByName(context, 'portal_catalog')
     parameters = dict(path=query)
     registry = getUtility(IRegistry)
     settings = registry.forInterface(ISearchReplaceSettings, check=False)
     if settings.restrict_searchable_types:
         parameters['portal_type'] = settings.enabled_types
     if onlySearchableText:
         parameters['SearchableText'] = u'*{0}*'.format(find)
     brains = catalog(**parameters)
     memship = getToolByName(context, 'portal_membership')
     checkPermission = memship.checkPermission
     # Match objects
     results = []
     replaced = 0
     for b in brains:
         ipath = b.getPath()
         if not sitems or ipath in sitems:
             try:
                 obj = b.getObject()
             except (KeyError, AttributeError):
                 logger.warn('getObject failed for %s', ipath)
                 continue
             # Does the user have the modify permission on this object?
             if not checkPermission(self.permission, obj):
                 continue
             # If there is a filtered list of items, and it
             # is in the list, or if there is no filter
             # then process the item
             if replace:
                 # Do a replace
                 if sitems:
                     sitem = sitems[ipath]
                 else:
                     sitem = None
                 rep = self._replaceObject(matcher,
                                           obj,
                                           cpath,
                                           rtext,
                                           sitem)
                 if rep:
                     self._afterReplace(obj, find, rtext)
                     replaced += rep
             elif not replace:
                 # Just find the matches and return info
                 result = self._searchObject(matcher, obj)
                 if result:
                     results += result
                 if maxResults is not None and len(results) > maxResults:
                     results = results[:maxResults]
                     break
     if replace:
         return replaced
     else:
         return results
Пример #43
0
def get_messages_to_show(context, caching=True):
    """
        Returns every message to be displayed for current context.
    """
    messages = None
    if caching:
        request = getRequest()
        if request:
            key = 'messagesviewlet-utils-get_messages_to_show-{0}'.format(
                '_'.join(context.getPhysicalPath()))
            cache = IAnnotations(request)
            messages = cache.get(key, None)
        else:
            caching = False

    if messages is None:
        messages = []
        portal = api.portal.get()
        catalog = api.portal.get_tool(name='portal_catalog')
        # Getting user roles on context
        if api.user.is_anonymous():
            mb_roles = set(['Anonymous'])
        else:
            mb_roles = set(api.user.get_roles(obj=context))
        now = DateTime()
        brains = catalog.unrestrictedSearchResults(
            portal_type=['Message'],
            start={
                'query': now,
                'range': 'max'
            },
            end={
                'query': now,
                'range': 'min'
            },
            review_state=('activated'),
            sort_on='getObjPositionInParent')
        for brain in brains:
            message = brain._unrestrictedGetObject()
            if message.location == 'homepage':
                # Test if context is PloneSite or its default page
                if not INavigationRoot.providedBy(context) and \
                        not isDefaultPage(portal, context):
                    continue
            # check in the cookie if message is marked as read
            if message.can_hide:
                m_uids = context.REQUEST.get('messagesviewlet', '')
                if message.hidden_uid in m_uids.split('|'):
                    continue
            # check if member has a required role on the context
            if message.required_roles:
                if mb_roles.intersection(message.required_roles) == set():
                    continue
            # We define obj.context to viewlet context to evaluate expression on viewlet context display.
            if not ITALCondition(message).evaluate(
                    extra_expr_ctx={'context': context}):
                continue
            # We check the local roles
            if message.use_local_roles and \
               not api.user.is_anonymous() and \
               'Reader' not in api.user.get_roles(obj=message):
                continue
            messages.append(message)

        if caching:
            cache[key] = messages

    return messages
Пример #44
0
def objectAddedEvent(context, event):
    """Handle event that translation was added.

    By convention, when a translation is created, its ``translations``
    attribute is set to a list with a single item, which is the
    translation source.

    In this event handler, we simply reverse that relationship.
    """

    container = event.newParent

    # If we're copying an item, than we can expect a volatile
    # attribute to contain a reference to the original item. This
    # information is turned into a translation reference below.
    try:
        uuid, language = context._v_multilingual_copy
    except AttributeError:
        is_copy = False
        translations = getattr(aq_base(context), "translations", None)
        if translations:
            uuid = list(translations)[0]
            del context.translations
        else:
            uuid = None
    else:
        # The Plone site root is a special case, because it always has
        # a language setting, so the check below won't work.
        if IPloneSiteRoot.providedBy(container):
            return

        # If we're copying the item into the same language, then we do
        # nothing.
        if language == getattr(aq_base(container), "language"):
            return

        is_copy = True

    # Inherit the language of the container to which the item is
    # added.
    if not IPloneSiteRoot.providedBy(container):
        if not context.language:
            context.language = aq_base(container).language

    catalog = getToolByName(container, 'portal_catalog')
    result = catalog(UID=uuid)
    if len(result) != 1:
        return

    parent = result[0].getObject()
    if not is_copy and parent.creation_date >= context.creation_date:
        logger.warn("parent %r is newer than translation %r." %
                    (uuid, str(IUUID(context))))

    # If the item being copied or translated was a default page, apply
    # the same setting to this item, relative to its container.
    if getDefaultPage(container) is None:
        if isDefaultPage(parent.__parent__, parent):
            objectId = context.getId()
            container.setDefaultPage(objectId)
            modified(container)

    # If this item is being copied into a language folder, make sure
    # we unregister an existing translation.
    if is_copy:
        for language, obj in ITranslationGraph(parent).getTranslations():
            if language == container.language:
                ITranslationGraph(obj).unregisterTranslation(parent)

    # Now, append the translation to the source item's list.
    wrapped = context.__of__(container)
    ITranslationGraph(wrapped).registerTranslation(parent)
    modified(parent)

    # For technical reasons, we need to invalidate the counter
    # explicitly because the item being added might not yet be
    # catalogued.
    getPersistentTranslationCounter(parent).change(1)
Пример #45
0
    def getMenuItems(self, context, request):
        """Return menu item entries in a TAL-friendly form."""
        menu = []
        url = context.absolute_url()
        lt = getToolByName(context, "portal_languages")
        portal_state = getMultiAdapter((context, request), name=u'plone_portal_state')
        portal_url = portal_state.portal_url()
        showflags = lt.showFlags()
        context_id = ITranslationManager(context).tg
        registry = getUtility(IRegistry)
        settings = registry.forInterface(IMultiLanguageExtraOptionsSchema)
        edit_view = 'babel_edit' if settings.redirect_babel_view else 'edit'
        # In case is neutral language show set language menu only
        if LANGUAGE_INDEPENDENT != ILanguage(context).get_language():
            menu.append({
                "title": _(u"title_babel_edit",
                       default=u"Edit with babel view"),
                "description": _(u"description_babel_edit",
                                default=u"Edit with the babel_edit"),
                "action": url + "/" + edit_view,
                "selected": False,
                "icon": None,
                "extra": {"id": "_edit_babel_edit",
                       "separator": None,
                       "class": ""},
                "submenu": None,
                })

            contexts = [context,]
            prt = aq_parent(context)
            if isDefaultPage(prt, context):
                contexts.append(prt)

            for idx,context in enumerate(contexts):
                url = context.absolute_url()

                langs = untranslated_languages(context)
                for lang in langs:
                    lang_name = lang.title
                    lang_id = lang.value
                    icon = showflags and lt.getFlagForLanguageCode(lang_id) or None
                    item = {
                        "description": _(u"description_translate_into",
                                        default=u"Translate into ${lang_name}",
                                        mapping={"lang_name": lang_name}),
                        "action": url + "/@@create_translation?language=%s" % lang_id,
                        "selected": False,
                        "icon": icon,
                        "width": "14",
                        "height": "11",
                        "extra": {"id": "translate_into_%s" % lang_id,
                                  "separator": None,
                                  "class": "contentmenuflags"},
                                  "submenu": None,
                        }
                    item['title'] = idx and _(u'create_translation_folder',
                                    default=u"Create ${lang_name} folder",
                                    mapping={"lang_name": lang_name}) \
                            or _(u'create_translation',
                                        default=u"Create ${lang_name}",
                                        mapping={"lang_name": lang_name})
                    menu.append(item)

                langs = translated_languages(context)
                urls = translated_urls(context)
                for lang in langs:
                    if lang not in urls:
                        # omit if translation is not permitted to access.
                        continue
                    lang_name = lang.title
                    lang_id = lang.value
                    icon = showflags and lt.getFlagForLanguageCode(lang_id) or None
                    item = {
                        "description": _(u"description_babeledit_menu",
                                        default=u"Babel edit ${lang_name}",
                                        mapping={"lang_name": lang_name}),
                        "action": urls.getTerm(lang_id).title + "/" + edit_view,
                        "selected": False,
                        "icon": icon,
                        "width": "14",
                        "height": "11",
                        "extra": {"id": "babel_edit_%s" % lang_id,
                                  "separator": None,
                                  "class": "contentmenuflags"},
                                  "submenu": None,
                        }
                    item['title'] = idx and _(u'edit_translation_folder',
                                    default=u"Edit ${lang_name} folder",
                                    mapping={"lang_name": lang_name}) \
                            or _(u'edit_translation',
                                                default=u"Edit ${lang_name}",
                                                mapping={"lang_name": lang_name})
                    menu.append(item)

                item = {
                    "description": _(u"description_add_translations",
                                    default=u"Add existing content as translation"),
                    "action": url + "/add_translations",
                    "selected": False,
                    "icon": None,
                    "extra": {"id": "_add_translations",
                           "separator": langs and "actionSeparator" or None,
                           "class": ""},
                    "submenu": None,
                    }
                item['title'] = idx and _(u"title_add_translations_folder",
                                    default=u"Add translations for folder...") \
                        or _(u"title_add_translations",
                                                        default=u"Add translations...")
                menu.append(item)

                item = {
                    "title": _(u"title_remove_translations",
                               default=u"Remove translations..."),
                    "description": _(
                        u"description_remove_translations",
                        default=u"Delete translations or remove the relations"),
                    "action": url + "/remove_translations",
                    "selected": False,
                    "icon": None,
                    "extra": {"id": "_remove_translations",
                           "separator": langs and "actionSeparator" or None,
                           "class": ""},
                    "submenu": None,
                    }
                menu.append(item)

        elif LANGUAGE_INDEPENDENT == ILanguage(context).get_language():
            menu.append({
                "title": _(u"language_folder",
                       default=u"Return to language folder"),
                "description": _(
                    u"description_language_folder",
                    default=u"Go to the user's browser preferred language related folder"),
                "action": portal_url + '/' + lt.getPreferredLanguage(),
                "selected": False,
                "icon": None,
                "extra": {"id": "_shared_folder",
                       "separator": None,
                       "class": ""},
                "submenu": None,
                })

        if LANGUAGE_INDEPENDENT != ILanguage(context).get_language():
            menu.append({
                "title": _(u"universal_link",
                       default=u"Universal Link"),
                "description": _(
                    u"description_universal_link",
                    default=u"Universal Language content link"),
                "action": portal_url + "/@@multilingual-universal-link/" + context_id,
                "selected": False,
                "icon": None,
                "extra": {"id": "_universal_link",
                       "separator": None,
                       "class": ""},
                "submenu": None,
                })

            menu.append({
                "title": _(u"shared_folder",
                       default=u"Go to shared folder"),
                "description": _(
                    u"description_shared_folder",
                    default=u"Show the language shared (neutral language) folder"),
                "action": portal_url + '/' + SHARED_NAME,
                "selected": False,
                "icon": None,
                "extra": {"id": "_shared_folder",
                       "separator": None,
                       "class": ""},
                "submenu": None,
                })

        menu.append({
            "title": _(u"title_set_language",
                        default=u"Set content language"),
            "description": _(u"description_set_language",
                             default=u"Set or change the current content language"),
            "action": url + "/update_language",
            "selected": False,
            "icon": None,
            "extra": {"id": "_set_language",
               "separator": None,
                   "class": ""},
                 "submenu": None,
            })

        return menu
Пример #46
0
 def context_is_workspace_view(self):
     """Is context a selected item as view for a workspace"""
     if self.workspace is None or self.context.__parent__ != self.workspace:
         # if not directly contained within workspace, ignore:
         return False
     return isDefaultPage(container=self.workspace, obj=self.context)
Пример #47
0
 def context_is_workspace_view(self):
     """Is context a selected item as view for a workspace"""
     if self.workspace is None or self.context.__parent__ != self.workspace:
         # if not directly contained within workspace, ignore:
         return False
     return isDefaultPage(container=self.workspace, obj=self.context)
Пример #48
0
    def getMenuItems(self, context, request):
        """Return menu item entries in a TAL-friendly form.
        """
        try:
            lang_names = request.locale.displayNames.languages
        except AttributeError:
            lang_names = {}
        menu = []
        url = context.absolute_url()
        lt = getToolByName(context, "portal_languages")

        site_url = getSite().absolute_url()
        showflags = lt.showFlags
        context_id = ITranslationManager(context).tg
        registry = getUtility(IRegistry)
        settings = registry.forInterface(IMultiLanguageExtraOptionsSchema,
                                         prefix="plone")
        edit_view = 'babel_edit' if settings.redirect_babel_view else 'edit'
        # In case is neutral language show set language menu only
        is_neutral_content = (ILanguage(context).get_language()
                              == LANGUAGE_INDEPENDENT
                              or is_language_independent(context))

        shared_folder_url = site_url + '/folder_contents'
        pc = getToolByName(getSite(), 'portal_catalog')
        results = pc.unrestrictedSearchResults(
            portal_type='LIF', Language=ILanguage(context).get_language())
        for brain in results:
            shared_folder_url = brain.getURL() + '/folder_contents'

        if not is_neutral_content and not INavigationRoot.providedBy(context):
            menu.append({
                "title":
                _(u"title_babel_edit", default=u"Edit with babel view"),
                "description":
                _(u"description_babel_edit",
                  default=u"Edit with the babel_edit"),
                "action":
                url + "/" + edit_view,
                "selected":
                False,
                "icon":
                None,
                "extra": {
                    "id": "_edit_babel_edit",
                    "separator": None,
                    "class": "",
                },
                "submenu":
                None,
            })

            if ITranslatable.providedBy(context):
                contexts = [
                    context,
                ]
            else:
                contexts = []
            prt = aq_parent(context)
            if isDefaultPage(prt, context) and ITranslatable.providedBy(prt):
                contexts.append(prt)

            for idx, context in enumerate(contexts):
                url = context.absolute_url()
                ulangs = untranslated_languages(context)
                for lang in ulangs:
                    lang_name = lang_names.get(lang.value, lang.title)
                    lang_id = lang.value
                    icon = showflags and lt.getFlagForLanguageCode(lang_id)\
                        or None
                    item = {
                        "description":
                        _(u"description_translate_into",
                          default=u"Translate into ${lang_name}",
                          mapping={"lang_name": lang_name}),
                        "action":
                        "%s/@@create_translation?language=%s" % (url, lang_id),
                        "selected":
                        False,
                        "icon":
                        icon,
                        "width":
                        "14",
                        "height":
                        "11",
                        "extra": {
                            "id": "translate_into_%s" % lang_id,
                            "separator": None,
                            "class": "contentmenuflags"
                        },
                        "submenu":
                        None,
                    }
                    item['title'] = idx and _(
                        u'create_translation_folder',
                        default=u"Create ${lang_name} folder",
                        mapping={"lang_name": lang_name}) or _(
                            u'create_translation',
                            default=u"Create ${lang_name}",
                            mapping={"lang_name": lang_name})
                    menu.append(item)
                langs = translated_languages(context)
                urls = translated_urls(context)
                for lang in langs:
                    if lang.value not in urls.by_token:
                        # omit if translation is not permitted to access.
                        continue
                    lang_name = lang_names.get(lang.value, lang.title)
                    lang_id = lang.value
                    icon = showflags and lt.getFlagForLanguageCode(lang_id)\
                        or None
                    item = {
                        "description":
                        _(u"description_babeledit_menu",
                          default=u"Babel edit ${lang_name}",
                          mapping={"lang_name": lang_name}),
                        "action":
                        (urls.getTerm(lang_id).title + "/" + edit_view),
                        "selected":
                        False,
                        "icon":
                        icon,
                        "width":
                        "14",
                        "height":
                        "11",
                        "extra": {
                            "id": "babel_edit_%s" % lang_id,
                            "separator": None,
                            "class": "contentmenuflags"
                        },
                        "submenu":
                        None,
                    }
                    item['title'] = idx and _(
                        u'edit_translation_folder',
                        default=u"Edit ${lang_name} folder",
                        mapping={"lang_name": lang_name}) or _(
                            u'edit_translation',
                            default=u"Edit ${lang_name}",
                            mapping={"lang_name": lang_name})
                    menu.append(item)

                item = {
                    "description":
                    _(u"description_add_translations",
                      default=u"Add existing content as translation"),
                    "action":
                    url + "/add_translations",
                    "selected":
                    False,
                    "icon":
                    None,
                    "extra": {
                        "id": "_add_translations",
                        "separator": langs and "actionSeparator" or None,
                        "class": ""
                    },
                    "submenu":
                    None,
                }
                item['title'] = idx and _(
                    u"title_add_translations_folder",
                    default=u"Add translations for folder...") or _(
                        u"title_add_translations",
                        default=u"Add translations...")
                menu.append(item)

                item = {
                    "title":
                    _(u"title_remove_translations",
                      default=u"Remove translations..."),
                    "description":
                    _(u"description_remove_translations",
                      default=u"Delete translations or remove the relations"),
                    "action":
                    url + "/remove_translations",
                    "selected":
                    False,
                    "icon":
                    None,
                    "extra": {
                        "id": "_remove_translations",
                        "separator": langs and "actionSeparator" or None,
                        "class": ""
                    },
                    "submenu":
                    None,
                }
                menu.append(item)

        elif is_neutral_content:
            menu.append({
                "title":
                _(u"language_folder", default=u"Return to language folder"),
                "description":
                _(u"description_language_folder",
                  default=u"Go to the user's browser preferred language "
                  u"related folder"),
                "action":
                site_url + '/' + lt.getPreferredLanguage(),
                "selected":
                False,
                "icon":
                None,
                "extra": {
                    "id": "_shared_folder",
                    "separator": None,
                    "class": ""
                },
                "submenu":
                None,
            })

        if not is_neutral_content:
            menu.append({
                "title":
                _(u"universal_link", default=u"Universal Link"),
                "description":
                _(u"description_universal_link",
                  default=u"Universal Language content link"),
                "action":
                "%s/@@multilingual-universal-link/%s" % (site_url, context_id),
                "selected":
                False,
                "icon":
                None,
                "extra": {
                    "id": "_universal_link",
                    "separator": None,
                    "class": ""
                },
                "submenu":
                None,
            })

            menu.append({
                "title":
                _(u"shared_folder", default=u"Go to shared folder"),
                "description":
                _(u"description_shared_folder",
                  default=u"Show the language shared (neutral language) "
                  u"folder"),
                "action":
                shared_folder_url,
                "selected":
                False,
                "icon":
                None,
                "extra": {
                    "id": "_shared_folder",
                    "separator": None,
                    "class": ""
                },
                "submenu":
                None,
            })

        menu.append({
            "title":
            _(u"title_set_language", default=u"Set content language"),
            "description":
            _(u"description_set_language",
              default=u"Set or change the current content language"),
            "action":
            url + "/update_language",
            "selected":
            False,
            "icon":
            None,
            "extra": {
                "id": "_set_language",
                "separator": None,
                "class": ""
            },
            "submenu":
            None,
        })

        return menu
Пример #49
0
    def languages(self):
        context = aq_inner(self.context)
        results = LanguageSelector.languages(self)
        translatable = ITranslatable(context, None)
        if translatable is not None:
            translations = translatable.getTranslations()
        else:
            translations = []

        # We want to preserve the current template / view as used for the
        # current object and also use it for the other languages

        # We need to find the actual translatable content object. As an
        # optimization we assume it is one of the last two path segments
        match = filter(None, context.getPhysicalPath()[-2:])
        current_path = filter(None, self.request.get('PATH_INFO', '').split('/'))
        append_path = []
        stop = False
        while current_path and not stop:
            check = current_path.pop()
            if check not in match:
                append_path.insert(0, check)
            else:
                stop = True
        # we remove virtualhostroot
        if 'VirtualHostRoot' in append_path:
            append_path.remove('VirtualHostRoot')
        if append_path:
            append_path.insert(0, '')
        formvariables = self.request.form
        for k, v in formvariables.items():
            if isinstance(v, unicode):
                formvariables[k] = v.encode('utf-8')
        for data in results:
            data['translated'] = data['code'] in translations

            try:
                appendtourl = '/'.join(append_path) + \
                          '?' + make_query(formvariables, dict(set_language=data['code']))
            except UnicodeError:
                appendtourl = '/'.join(append_path) + '?set_language=' + data['code']

            if data['translated']:
                trans = translations[data['code']][0]
                container = aq_parent(trans)
                if isDefaultPage(container, trans):
                    trans = container
                state = getMultiAdapter((trans, self.request),
                        name='plone_context_state')
                data['url'] = state.view_url() + appendtourl
            else:
                container = aq_parent(context)
                if isDefaultPage(container, context):
                    context = container
                state = getMultiAdapter((context, self.request),
                        name='plone_context_state')
                try:
                    data['url'] = state.view_url() + appendtourl
                except AttributeError:
                    data['url'] = context.absolute_url() + appendtourl

        return results
Пример #50
0
def getTranslationActionItems(context, request):
    """Return action menu items for 'Translate' menu."""

    parent = context.__parent__
    is_default_page = isDefaultPage(parent, context)

    # There is a special case here which is when the ``context`` is a
    # default page. In this case, we compute the nearest translations
    # of the parent folder, unless the parent is a navigation or site
    # root.
    use_parent = False

    graph = ITranslationGraph(context)

    current_lang = getattr(aq_base(context), "language", "")
    lt = getToolByName(context, 'portal_languages')
    pt = getToolByName(context, name="portal_url")
    showflags = lt.showFlags()
    default_lang = lt.getDefaultLanguage()
    display_languages = request.locale.displayNames.languages
    site = pt.getPortalObject()
    site_url = site.absolute_url()

    if use_parent:
        lang_items = ITranslationGraph(parent).getNearestTranslations()
    else:
        lang_items = graph.getNearestTranslations()

    menu = []
    for lang_id, item, distance in lang_items:
        if lang_id == current_lang:
            continue

        if not current_lang and lang_id == default_lang:
            continue

        icon = showflags and lt.getFlagForLanguageCode(lang_id) or None

        display_lang_name = display_languages[lang_id]
        title = unicode(display_lang_name)

        if use_parent:
            if distance >= 0:
                distance += 1

            if item is not None:
                default_page = getDefaultPage(item)
                if default_page is not None:
                    item = item[default_page]
                    distance = 0
                else:
                    add_context = context
            else:
                add_context = parent
        else:
            add_context = context

        # If the item already exists, link to its default view.
        if distance == 0:
            assert item is not None
            fti = getUtility(IDexterityFTI, name=item.portal_type)
            info = fti.getActionInfo('object/view')
            url = "/" + info['url']
            title += u" ✓"

        # Otherwise, link to the add form.
        else:
            uuid = str(IUUID(add_context))
            portal_type = add_context.portal_type
            title = _(u"${title} (add...)", mapping={'title': title})

            url = "/++add++%s?%s" % (portal_type,
                                     urllib.urlencode({
                                         'translation': uuid,
                                         'language': lang_id,
                                     }))

            if item is None:
                if lang_id == default_lang:
                    item = site
                else:
                    try:
                        item = site[lang_id]
                    except KeyError:
                        title = _(u"${lang_name} (setup required)",
                                  mapping={'lang_name': title})

                        url = site_url + "/" + lang_id + url
                        url = "/@@setup-language?language=%s&next_url=%s" % (
                            lang_id, urllib.quote_plus(url))

                        action_url = site_url + url

        if item is not None:
            action_url = item.absolute_url() + url.rstrip('/')

        entry = {
            "title":
            translate(title, context=request),
            "description":
            _(u"description_translate_into",
              default=u"Translate into ${lang_name}",
              mapping={"lang_name": display_lang_name}),
            "action":
            action_url,
            "selected":
            False,
            "icon":
            icon,
            "width":
            14,
            "height":
            11,
            "extra": {
                "id": "translate_into_%s" % lang_id,
                "separator": None,
                "class": ""
            },
            "submenu":
            None,
        }

        menu.append(entry)

    menu.sort(key=lambda item: unicode(item['title']))

    if graph.getTranslations():
        menu.append({
            "title":
            _(u"Clear..."),
            "description":
            _(u"Clear the list of translation references."),
            "action":
            graph.context.absolute_url() + "/@@clear-translations",
            "selected":
            False,
            "icon":
            None,
            "extra": {
                "id": "clearTranslations",
                "separator": None,
                "class": ""
            },
            "submenu":
            None,
        })
    else:
        menu.append({
            "title":
            _(u"This is a translation of..."),
            "description":
            _(u"Mark this item as the translation for "
              u"another content item on the site."),
            "action":
            graph.context.absolute_url() + "/@@set-translation-for",
            "selected":
            False,
            "icon":
            None,
            "extra": {
                "id": "setTranslationFor",
                "separator": None,
                "class": ""
            },
            "submenu":
            None,
        })

    return menu
 def available(self):
     return self.data.siteroot_only is False and True\
       or ISiteRoot.providedBy(self.context)\
       or ISiteRoot.providedBy(aq_parent(aq_inner(self.context)))\
           and isDefaultPage(aq_parent(aq_inner(self.context)), self.context) \
       or False