def getRootPath(context, currentFolderOnly, topLevel, root):
    """Helper function to calculate the real root path
    """
    context = aq_inner(context)
    if currentFolderOnly:
        folderish = getattr(aq_base(context), 'isPrincipiaFolderish', False) and not INonStructuralFolder.providedBy(context)
        parent = aq_parent(context)
        
        is_default_page = False
        browser_default = IBrowserDefault(parent, None)
        if browser_default is not None:
            is_default_page = (browser_default.getDefaultPage() == context.getId())
        
        if not folderish:
            return '/'.join(parent.getPhysicalPath())
        else:
            return '/'.join(context.getPhysicalPath())

    rootPath = getNavigationRoot(context, relativeRoot=root)

    # Adjust for topLevel
    if topLevel > 0:
        contextPath = '/'.join(context.getPhysicalPath())
        if not contextPath.startswith(rootPath):
            return None
        contextSubPathElements = contextPath[len(rootPath)+1:]
        if contextSubPathElements:
            contextSubPathElements = contextSubPathElements.split('/')
            if len(contextSubPathElements) < topLevel:
                return None
            rootPath = rootPath + '/' + '/'.join(contextSubPathElements[:topLevel])
        else:
            return None
    
    return rootPath
Ejemplo n.º 2
0
def _is_default_page(container, context):
    is_default_page = False
    browser_default = IBrowserDefault(container, None)
    if browser_default is not None:
        is_default_page = browser_default.getDefaultPage() == context.getId()

    return is_default_page
Ejemplo n.º 3
0
def getObjectDefaultView(context):
    """Get the id of an object's default view
    """

    # courtesy of Producs.CacheSetup

    browserDefault = IBrowserDefault(context, None)

    if browserDefault is not None:
        try:
            return stripLeadingCharacters(browserDefault.defaultView())
        except AttributeError:
            # Might happen if FTI didn't migrate yet.
            pass

    if not IDynamicType.providedBy(context):
        return None

    fti = context.getTypeInfo()
    try:
        # XXX: This isn't quite right since it assumes the action starts
        #with ${object_url}
        action = fti.getActionInfo('object/view')['url'].split('/')[-1]
    except ValueError:
        # If the action doesn't exist, stop
        return None

    # Try resolving method aliases because we need a real template_id here
    if action:
        action = fti.queryMethodID(action, default = action, context = context)
    else:
        action = fti.queryMethodID('(Default)', default = action,
                                   context = context)

    return stripLeadingCharacters(action)
Ejemplo n.º 4
0
 def test_is_view_template_alias(self):
     browserDefault = IBrowserDefault(self.folder, None)
     fti = browserDefault.getTypeInfo()
     aliases = fti.getMethodAliases()
     aliases["foo_alias"] = "(Default)"
     fti.setMethodAliases(aliases)
     self.app.REQUEST["ACTUAL_URL"] = self.folder.absolute_url() + "/foo_alias"
     self.assertEquals(self.fview.is_view_template(), True)
     self.assertEquals(self.dview.is_view_template(), False)
Ejemplo n.º 5
0
 def test_is_view_template_alias(self):
     browserDefault = IBrowserDefault(self.folder, None)
     fti = browserDefault.getTypeInfo()
     aliases = fti.getMethodAliases()
     aliases['foo_alias'] = '(Default)'
     fti.setMethodAliases(aliases)
     self.app.REQUEST[
         'ACTUAL_URL'] = self.folder.absolute_url() + '/foo_alias'
     self.assertEqual(self.fview.is_view_template(), True)
     self.assertEqual(self.dview.is_view_template(), False)
Ejemplo n.º 6
0
    def test_getDefaultPage_step_2(self):
        # Else check for IBrowserDefault, either if the container implements
        # it or if an adapter exists. In both cases fetch its FTI and either
        # take it if it implements IDynamicViewTypeInformation or adapt it to
        # IDynamicViewTypeInformation. call getDefaultPage on the implementer
        # and take value if given.

        # first check some preconditions
        #
        # 1) a folder provides IBrowserDefault
        from Products.CMFDynamicViewFTI.interfaces import IBrowserDefault
        self.assertTrue(IBrowserDefault.providedBy(self.folder))

        # 2) a folder also provides an fti that implements
        #    IDynamicViewTypeInformation
        from Products.CMFDynamicViewFTI.interfaces import IDynamicViewTypeInformation  # noqa
        fti = self.folder.getTypeInfo()
        self.assertTrue(IDynamicViewTypeInformation.providedBy(fti))

        # so if we set a document as defaultpage
        self.folder.invokeFactory('Document', 'd1', title=u"Doc 1")
        self.folder.setDefaultPage('d1')

        # 3) fti should return it
        self.assertEqual('d1',
                         fti.getDefaultPage(self.folder, check_exists=True))

        # now test since we're sure everythings set up correctly
        from plone.app.layout.navigation.defaultpage import getDefaultPage
        self.assertEqual('d1', getDefaultPage(self.folder))
    def test_get_default_page_step_2(self):
        # Else check for IBrowserDefault, either if the container implements
        # it or if an adapter exists. In both cases fetch its FTI and either
        # take it if it implements IDynamicViewTypeInformation or adapt it to
        # IDynamicViewTypeInformation. call get_default_page on the implementer
        # and take value if given.

        # first check some preconditions
        #
        # 1) a folder provides IBrowserDefault
        from Products.CMFDynamicViewFTI.interfaces import IBrowserDefault
        self.assertTrue(IBrowserDefault.providedBy(self.folder))

        # 2) a folder also provides an fti that implements
        #    IDynamicViewTypeInformation
        from Products.CMFDynamicViewFTI.interfaces import IDynamicViewTypeInformation  # noqa
        fti = self.folder.getTypeInfo()
        self.assertTrue(IDynamicViewTypeInformation.providedBy(fti))

        # so if we set a document as defaultpage
        self.folder.invokeFactory('Document', 'd1', title=u"Doc 1")
        self.folder.setDefaultPage('d1')

        # 3) fti should return it
        self.assertEqual(
            'd1',
            fti.getDefaultPage(self.folder, check_exists=True)
        )

        # now test since we're sure everythings set up correctly
        from Products.CMFPlone.defaultpage import get_default_page
        self.assertEqual('d1', get_default_page(self.folder))
Ejemplo n.º 8
0
def getRootPath(context, currentFolderOnly, topLevel, root_path):
    """Helper function to calculate the real root path"""
    context = aq_inner(context)
    if currentFolderOnly:
        folderish = getattr(
            aq_base(context), "isPrincipiaFolderish",
            False) and not INonStructuralFolder.providedBy(context)
        parent = aq_parent(context)

        is_default_page = False
        browser_default = IBrowserDefault(parent, None)
        if browser_default is not None:
            is_default_page = browser_default.getDefaultPage(
            ) == context.getId()

        if not folderish or is_default_page:
            return "/".join(parent.getPhysicalPath())
        else:
            return "/".join(context.getPhysicalPath())

    # root = uuidToObject(root)
    root = get_root(context, root_path)

    if root is not None:
        rootPath = "/".join(root.getPhysicalPath())
    else:
        rootPath = getNavigationRoot(context)

    # Adjust for topLevel
    if topLevel > 0:
        contextPath = "/".join(context.getPhysicalPath())
        if not contextPath.startswith(rootPath):
            return
        contextSubPathElements = contextPath[len(rootPath) + 1:]
        if contextSubPathElements:
            contextSubPathElements = contextSubPathElements.split("/")
            if len(contextSubPathElements) < topLevel:
                return
            rootPath = rootPath + "/" + "/".join(
                contextSubPathElements[:topLevel])
        else:
            return

    return rootPath
Ejemplo n.º 9
0
def getObjectDefaultView(context):
    """Get the id of an object's default view
    """

    # courtesy of Producs.CacheSetup

    browserDefault = IBrowserDefault(context, None)

    if browserDefault is not None:
        try:
            return browserDefault.defaultView()
        except AttributeError:
            # Might happen if FTI didn't migrate yet.
            pass

    if not IDynamicType.providedBy(context):
        return None

    fti = context.getTypeInfo()
    try:
        # XXX: This isn't quite right since it assumes the action starts with ${object_url}
        action = fti.getActionInfo('object/view')['url'].split('/')[-1]
    except ValueError:
        # If the action doesn't exist, stop
        return None

    # Try resolving method aliases because we need a real template_id here
    if action:
        action = fti.queryMethodID(action, default=action, context=context)
    else:
        action = fti.queryMethodID('(Default)',
                                   default=action,
                                   context=context)

    # Strip off leading / and/or @@
    if action and action[0] == '/':
        action = action[1:]
    if action and action.startswith('@@'):
        action = action[2:]
    return action
Ejemplo n.º 10
0
    def is_view_template(self):
        current_url = self.current_base_url()
        canonical_url = self.canonical_object_url()
        object_url = self.object_url()

        if current_url.endswith('/'):
            current_url = current_url[:-1]

        if current_url == canonical_url or current_url == object_url:
            return True
        if not current_url.startswith(object_url):
            # Cut short.
            return False
        # Get the part of the current_url minus the object_url.
        last_part = current_url.split(object_url)[-1]
        if not last_part.startswith('/'):
            # Unexpected
            return False
        # Remove the slash from the front:
        last_part = last_part[1:]
        if last_part == 'view':
            return True
        context = aq_inner(self.context)
        browserDefault = IBrowserDefault(context, None)
        if browserDefault is not None:
            fti = browserDefault.getTypeInfo()
            if fti.getMethodAliases().get(last_part) == '(Default)':
                return True

        template_id = self.view_template_id()
        if last_part == template_id:
            return True
        elif last_part == '@@%s' % template_id:
            return True

        return False
Ejemplo n.º 11
0
    def is_view_template(self):
        current_url = self.current_base_url()
        canonical_url = self.canonical_object_url()
        object_url = self.object_url()

        if current_url.endswith('/'):
            current_url = current_url[:-1]

        if current_url == canonical_url or current_url == object_url:
            return True
        if not current_url.startswith(object_url):
            # Cut short.
            return False
        # Get the part of the current_url minus the object_url.
        last_part = current_url.split(object_url)[-1]
        if not last_part.startswith('/'):
            # Unexpected
            return False
        # Remove the slash from the front:
        last_part = last_part[1:]
        if last_part == 'view':
            return True
        context = aq_inner(self.context)
        browserDefault = IBrowserDefault(context, None)
        if browserDefault is not None:
            fti = browserDefault.getTypeInfo()
            if fti.getMethodAliases().get(last_part) == '(Default)':
                return True

        template_id = self.view_template_id()
        if last_part == template_id:
            return True
        elif last_part == '@@%s' % template_id:
            return True

        return False
Ejemplo n.º 12
0
    def view_template_id(self):
        context = aq_inner(self.context)

        if IBrowserDefault.providedBy(context):
            browserDefault = context
        else:
            browserDefault = queryAdapter(context, IBrowserDefault)

        if browserDefault is not None:
            try:
                return browserDefault.getLayout()
            except AttributeError:
                # Might happen if FTI didn't migrate yet.
                pass

        action = self._lookupTypeActionTemplate('object/view')
        if not action:
            action = self._lookupTypeActionTemplate('folder/folderlisting')

        return action
Ejemplo n.º 13
0
    def view_template_id(self):
        context = aq_inner(self.context)

        if IBrowserDefault.providedBy(context):
            browserDefault = context
        else:
            browserDefault = queryAdapter(context, IBrowserDefault)

        if browserDefault is not None:
            try:
                return browserDefault.getLayout()
            except AttributeError:
                # Might happen if FTI didn't migrate yet.
                pass

        action = self._lookupTypeActionTemplate('object/view')
        if not action:
            action = self._lookupTypeActionTemplate('folder/folderlisting')

        return action
Ejemplo n.º 14
0
    def browserDefault(self, obj):
        """Sets default so we can return whatever we want instead of index_html.

        This method is complex, and interacts with mechanisms such as
        IBrowserDefault (implemented in CMFDynamicViewFTI), LinguaPlone and
        various mechanisms for setting the default page.

        The method returns a tuple (obj, [path]) where path is a path to
        a template or other object to be acquired and displayed on the object.
        The path is determined as follows:

        0. If we're c oming from WebDAV, make sure we don't return a contained
            object "default page" ever
        1. If there is an index_html attribute (either a contained object or
            an explicit attribute) on the object, return that as the
            "default page". Note that this may be used by things like
            File and Image to return the contents of the file, for example,
            not just content-space objects created by the user.
        2. If the object implements IBrowserDefault, query this for the
            default page.
        3. If the object has a property default_page set and this gives a list
            of, or single, object id, and that object is is found in the
            folder or is the name of a skin template, return that id
        4. If the property default_page is set in site_properties and that
            property contains a list of ids of which one id is found in the
            folder, return that id
        5. If the object implements IBrowserDefault, try to get the selected
            layout.
        6. If the type has a 'folderlisting' action and no default page is
            set, use this action. This permits folders to have the default
            'view' action be 'string:${object_url}/' and hence default to
            a default page when clicking the 'view' tab, whilst allowing the
            fallback action to be specified TTW in portal_types (this action
            is typically hidden)
        7. If nothing else is found, fall back on the object's 'view' action.
        8. If this is not found, raise an AttributeError
        """

        # WebDAV in Zope is odd it takes the incoming verb eg: PROPFIND
        # and then requests that object, for example for: /, with verb PROPFIND
        # means acquire PROPFIND from the folder and call it
        # its all very odd and WebDAV'y
        request = getattr(self, 'REQUEST', None)
        if request is not None and 'REQUEST_METHOD' in request:
            if request['REQUEST_METHOD'] not in ['GET', 'POST']:
                return obj, [request['REQUEST_METHOD']]
        # Now back to normal

        #
        # 1. Get an attribute or contained object index_html
        #

        # Note: The base PloneFolder, as well as ATCT's ATCTOrderedFolder
        # defines a method index_html() which returns a ReplaceableWrapper.
        # This is needed for WebDAV to work properly, and to avoid implicit
        # acquisition of index_html's, which are generally on-object only.
        # For the purposes of determining a default page, we don't want to
        # use this index_html(), nor the ComputedAttribute which defines it.

        if not isinstance(getattr(obj, 'index_html', None),
                          ReplaceableWrapper):
            index_obj = getattr(aq_base(obj), 'index_html', None)
            if index_obj is not None \
                    and not isinstance(index_obj, ComputedAttribute):
                return obj, ['index_html']

        #
        # 2. Look for a default_page managed by an IBrowserDefault-implementing
        #    object
        #
        # 3. Look for a default_page property on the object
        #
        # 4. Try the default sitewide default_page setting
        #

        if obj.isPrincipiaFolderish:
            defaultPage = self.getDefaultPage(obj)
            if defaultPage is not None:
                if defaultPage in obj:
                    return obj, [defaultPage]
                # Avoid infinite recursion in the case that the page id == the
                # object id
                elif (
                    defaultPage != obj.getId()
                    and defaultPage != '/'.join(obj.getPhysicalPath())
                ):
                    # For the default_page property, we may get things in the
                    # skin layers or with an explicit path - split this path
                    # to comply with the __browser_default__() spec
                    return obj, defaultPage.split('/')

        # 5. If there is no default page, try IBrowserDefault.getLayout()
        if IBrowserDefault.providedBy(obj):
            browserDefault = obj
        else:
            browserDefault = queryAdapter(obj, IBrowserDefault)
        if browserDefault is not None:
            layout = browserDefault.getLayout()
            if layout is None:
                raise AttributeError(
                    "%s has no assigned layout, perhaps it needs an FTI" % obj)
            else:
                return obj, [layout]

        #
        # 6. If the object has a 'folderlisting' action, use this
        #

        # This allows folders to determine in a flexible manner how they are
        # displayed when there is no default page, whilst still using
        # browserDefault() to show contained objects by default on the 'view'
        # action (this applies to old-style folders only, IBrowserDefault is
        # managed explicitly above)

        if base_hasattr(obj, 'getTypeInfo'):
            try:
                # XXX: This isn't quite right since it assumes the action
                # starts with ${object_url}.  Should we raise an error if
                # it doesn't?
                act = obj.getTypeInfo().getActionInfo(
                    'folder/folderlisting'
                )['url'].split('/')[-1]
                return obj, [act]
            except ValueError:
                pass

            #
            # 7. Fall back on the 'view' action
            #

            try:
                # XXX: This isn't quite right since it assumes the action
                # starts with ${object_url}.  Should we raise an error if
                # it doesn't?
                act = obj.getTypeInfo().getActionInfo(
                    'object/view'
                )['url'].split('/')[-1]
                return obj, [act]
            except ValueError:
                pass

        #
        # 8. If we can't find this either, raise an exception
        #

        raise AttributeError(
            "Failed to get a default page or view_action for %s"
            % (obj.absolute_url(),)
        )
Ejemplo n.º 15
0
    def browserDefault(self, obj):
        """Sets default so we can return whatever we want instead of index_html.

        This method is complex, and interacts with mechanisms such as
        IBrowserDefault (implemented in CMFDynamicViewFTI), LinguaPlone and
        various mechanisms for setting the default page.

        The method returns a tuple (obj, [path]) where path is a path to
        a template or other object to be acquired and displayed on the object.
        The path is determined as follows:

        0. If we're c oming from WebDAV, make sure we don't return a contained
            object "default page" ever
        1. If there is an index_html attribute (either a contained object or
            an explicit attribute) on the object, return that as the
            "default page". Note that this may be used by things like
            File and Image to return the contents of the file, for example,
            not just content-space objects created by the user.
        2. If the object implements IBrowserDefault, query this for the
            default page.
        3. If the object has a property default_page set and this gives a list
            of, or single, object id, and that object is is found in the
            folder or is the name of a skin template, return that id
        4. If the property default_page is set in site_properties and that
            property contains a list of ids of which one id is found in the
            folder, return that id
        5. If the object implements IBrowserDefault, try to get the selected
            layout.
        6. If the type has a 'folderlisting' action and no default page is
            set, use this action. This permits folders to have the default
            'view' action be 'string:${object_url}/' and hence default to
            a default page when clicking the 'view' tab, whilst allowing the
            fallback action to be specified TTW in portal_types (this action
            is typically hidden)
        7. If nothing else is found, fall back on the object's 'view' action.
        8. If this is not found, raise an AttributeError
        """

        # WebDAV in Zope is odd it takes the incoming verb eg: PROPFIND
        # and then requests that object, for example for: /, with verb PROPFIND
        # means acquire PROPFIND from the folder and call it
        # its all very odd and WebDAV'y
        request = getattr(self, 'REQUEST', None)
        if request is not None and 'REQUEST_METHOD' in request:
            if request['REQUEST_METHOD'] not in ['GET', 'POST']:
                return obj, [request['REQUEST_METHOD']]
        # Now back to normal

        #
        # 1. Get an attribute or contained object index_html
        #

        # Note: The base PloneFolder, as well as ATCT's ATCTOrderedFolder
        # defines a method index_html() which returns a ReplaceableWrapper.
        # This is needed for WebDAV to work properly, and to avoid implicit
        # acquisition of index_html's, which are generally on-object only.
        # For the purposes of determining a default page, we don't want to
        # use this index_html(), nor the ComputedAttribute which defines it.

        if not isinstance(getattr(obj, 'index_html', None),
                          ReplaceableWrapper):
            index_obj = getattr(aq_base(obj), 'index_html', None)
            if index_obj is not None \
                    and not isinstance(index_obj, ComputedAttribute):
                return obj, ['index_html']

        #
        # 2. Look for a default_page managed by an IBrowserDefault-implementing
        #    object
        #
        # 3. Look for a default_page property on the object
        #
        # 4. Try the default sitewide default_page setting
        #

        if obj.isPrincipiaFolderish:
            defaultPage = self.getDefaultPage(obj)
            if defaultPage is not None:
                if defaultPage in obj:
                    return obj, [defaultPage]
                # Avoid infinite recursion in the case that the page id == the
                # object id
                elif (defaultPage != obj.getId()
                      and defaultPage != '/'.join(obj.getPhysicalPath())):
                    # For the default_page property, we may get things in the
                    # skin layers or with an explicit path - split this path
                    # to comply with the __browser_default__() spec
                    return obj, defaultPage.split('/')

        # 5. If there is no default page, try IBrowserDefault.getLayout()
        if IBrowserDefault.providedBy(obj):
            browserDefault = obj
        else:
            browserDefault = queryAdapter(obj, IBrowserDefault)
        if browserDefault is not None:
            layout = browserDefault.getLayout()
            if layout is None:
                raise AttributeError(
                    "%s has no assigned layout, perhaps it needs an FTI" % obj)
            else:
                return obj, [layout]

        #
        # 6. If the object has a 'folderlisting' action, use this
        #

        # This allows folders to determine in a flexible manner how they are
        # displayed when there is no default page, whilst still using
        # browserDefault() to show contained objects by default on the 'view'
        # action (this applies to old-style folders only, IBrowserDefault is
        # managed explicitly above)

        if base_hasattr(obj, 'getTypeInfo'):
            try:
                # XXX: This isn't quite right since it assumes the action
                # starts with ${object_url}.  Should we raise an error if
                # it doesn't?
                act = obj.getTypeInfo().getActionInfo(
                    'folder/folderlisting')['url'].split('/')[-1]
                return obj, [act]
            except ValueError:
                pass

            #
            # 7. Fall back on the 'view' action
            #

            try:
                # XXX: This isn't quite right since it assumes the action
                # starts with ${object_url}.  Should we raise an error if
                # it doesn't?
                act = obj.getTypeInfo().getActionInfo(
                    'object/view')['url'].split('/')[-1]
                return obj, [act]
            except ValueError:
                pass

        #
        # 8. If we can't find this either, raise an exception
        #

        raise AttributeError(
            "Failed to get a default page or view_action for %s" %
            (obj.absolute_url(), ))
Ejemplo n.º 16
0
    def getConfiguration(self, context=None, field=None, request=None):
        """Return configuration as a dictionary

        :param field: Dexterity or Archetypes Field instance

        :param context: The TinyMCE editor content items

        :return: JSON string of the TinyMCE configuration for this field
        """
        results = {}

        # Get widget attributes
        widget = getattr(field, 'widget', None)
        filter_buttons = getattr(widget, 'filter_buttons', None)
        allow_buttons = getattr(widget, 'allow_buttons', None)
        redefine_parastyles = getattr(widget, 'redefine_parastyles', None)
        parastyles = getattr(widget, 'parastyles', None)
        rooted = getattr(widget, 'rooted', False)
        toolbar_width = getattr(widget, 'toolbar_width', self.toolbar_width)

        # Get safe html transform
        safe_html = getattr(getToolByName(self, 'portal_transforms'),
                            'safe_html')

        # Get kupu library tool filter
        # Settings are stored on safe_html transform in Plone 4 and
        # on kupu tool in Plone 3.
        kupu_library_tool = getToolByName(self, 'kupu_library_tool', None)

        # Remove to be stripped attributes
        try:
            style_whitelist = safe_html.get_parameter_value('style_whitelist')
        except (KeyError, AttributeError):
            if kupu_library_tool is not None:
                style_whitelist = kupu_library_tool.getStyleWhitelist()
            else:
                style_whitelist = []
        results['valid_inline_styles'] = ','.join(
            style_whitelist)  # tinymce format

        # Replacing some hardcoded translations
        labels = {}
        labels['label_browseimage'] = translate(_('Image Browser'),
                                                context=request)
        labels['label_browselink'] = translate(_('Link Browser'),
                                               context=request)
        labels['label_addnewimage'] = translate(_('Add new Image'),
                                                context=request)
        labels['label_addnewfile'] = translate(_('Add new File'),
                                               context=request)
        labels['label_styles'] = translate(_('(remove style)'),
                                           context=request)
        labels['label_paragraph'] = translate(_('Normal paragraph'),
                                              context=request)
        labels['label_plain_cell'] = translate(_('Plain cell'),
                                               context=request)
        labels['label_style_ldots'] = translate(_('Style...'), context=request)
        labels['label_text'] = translate(_('Text'), context=request)
        labels['label_tables'] = translate(_('Tables'), context=request)
        labels['label_selection'] = translate(_('Selection'), context=request)
        labels['label_lists'] = translate(_('Lists'), context=request)
        labels['label_print'] = translate(_('Print'), context=request)
        labels['label_no_items'] = translate(_('No items in this folder'),
                                             context=request)
        labels['label_no_anchors'] = translate(_('No anchors in this page'),
                                               context=request)
        labels['label_browser'] = translate(_('Browser'), context=request)
        labels['label_shortcuts'] = translate(_('Shortcuts'), context=request)
        labels['label_search_results'] = translate(_('Search results:'),
                                                   context=request)
        labels['label_internal_path'] = translate(PMF("you_are_here",
                                                      default="You are here:"),
                                                  context=request)
        results['labels'] = labels

        # Add styles to results
        results['styles'] = []
        table_styles = []
        if not redefine_parastyles:
            if isinstance(self.tablestyles, StringTypes):
                for tablestyle in self.tablestyles.split('\n'):
                    if not tablestyle:
                        # empty line
                        continue
                    tablestylefields = tablestyle.split('|')
                    tablestyletitle = tablestylefields[0]
                    tablestyleid = tablestylefields[1]
                    if tablestyleid == 'plain':
                        # Do not duplicate the default style hardcoded in the
                        # table.htm.pt
                        continue
                    if request is not None:
                        tablestyletitle = translate(_(tablestylefields[0]),
                                                    context=request)
                    results['styles'].append(tablestyletitle + '|table|' +
                                             tablestyleid)
                    table_styles.append(tablestyletitle + '=' + tablestyleid)
            if isinstance(self.styles, StringTypes):
                styles = []
                for style in self.styles.split('\n'):
                    if not style:
                        # empty line
                        continue
                    stylefields = style.split('|')
                    styletitle = stylefields[0]
                    if request is not None:
                        styletitle = translate(_(stylefields[0]),
                                               context=request)
                    merge = styletitle + '|' + '|'.join(stylefields[1:])
                    styles.append(merge)
                results['styles'].extend(styles)
        results['table_styles'] = ';'.join(table_styles)  # tinymce config

        if parastyles is not None:
            results['styles'].extend(parastyles)

        styles = results.pop('styles')

        # Get buttons from control panel
        results['buttons'] = self.getEnabledButtons(context=context)

        # Filter buttons
        if allow_buttons is not None:
            allow_buttons = self.translateButtonsFromKupu(
                context=context, buttons=allow_buttons)
            results['buttons'] = filter(lambda x: x in results['buttons'],
                                        allow_buttons)
        if filter_buttons is not None:
            filter_buttons = self.translateButtonsFromKupu(
                context=context, buttons=filter_buttons)
            results['buttons'] = filter(lambda x: x not in filter_buttons,
                                        results['buttons'])

        # Get valid html elements
        valid_elements = self.getValidElements()
        results['valid_elements'] = ','.join([
            "%s[%s]" % (key, '|'.join(value))
            for key, value in valid_elements.iteritems()
        ])

        # self.customplugins can be None on old migrated sites
        results['customplugins'] = (self.customplugins or "").splitlines()

        # Set toolbar_location
        if self.toolbar_external:
            results['theme_advanced_toolbar_location'] = 'external'
        else:
            results['theme_advanced_toolbar_location'] = 'top'

        if self.autoresize:
            results['theme_advanced_path_location'] = 'none'
            results['theme_advanced_resizing_use_cookie'] = False
            results['theme_advanced_resizing'] = False
            results['autoresize'] = True
        else:
            results['theme_advanced_path_location'] = 'bottom'
            results['theme_advanced_resizing_use_cookie'] = True
            results['theme_advanced_resizing'] = self.resizing
            results['autoresize'] = False

        if '%' in self.editor_width:
            results['theme_advanced_resize_horizontal'] = False
        else:
            results['theme_advanced_resize_horizontal'] = True

        try:
            results['theme_advanced_source_editor_width'] = int(
                self.editor_width)
        except (TypeError, ValueError):
            results['theme_advanced_source_editor_width'] = 600

        try:
            results['theme_advanced_source_editor_height'] = int(
                self.editor_height)
        except (TypeError, ValueError):
            results['theme_advanced_source_editor_height'] = 400

        try:
            results['toolbar_width'] = int(toolbar_width)
        except (TypeError, ValueError):
            results['toolbar_width'] = 440

        portal_state = context.restrictedTraverse('@@plone_portal_state')
        # is_rtl handles every possible setting as far as RTL/LTR is concerned
        # pass that to tinmyce
        results['directionality'] = portal_state.is_rtl() and 'rtl' or 'ltr'

        portal = portal_state.portal()
        portal_url = portal_state.portal_url()
        results['portal_url'] = portal_url
        results['navigation_root_url'] = portal_state.navigation_root_url()

        if self.content_css and self.content_css.strip() != "":
            results['content_css'] = self.content_css
        else:
            results['content_css'] = '/'.join(
                [results['portal_url'],
                 self.getId(), "@@tinymce-getstyle"])

        results['link_using_uids'] = self.link_using_uids
        results['contextmenu'] = self.contextmenu
        results['entity_encoding'] = self.entity_encoding
        results['script_url'] = portal_url + '/tiny_mce_gzip.js'
        results['allow_captioned_images'] = bool(self.allow_captioned_images)
        results['rooted'] = bool(self.rooted or rooted)

        props = getToolByName(portal, 'portal_properties')
        plone_livesearch = props.site_properties.getProperty(
            'enable_livesearch', False)
        livesearch = props.site_properties.getProperty(
            'enable_tinymce_livesearch', plone_livesearch)
        results['livesearch'] = bool(livesearch)

        AVAILABLE_LANGUAGES = set(
            'sq ar hy az eu be bn nb bs br bg ca ch zh hr cs da dv nl en et fi fr gl '
            'ka de el gu he hi hu is id ia it ja ko lv lt lb mk ms ml mn se no nn fa '
            'pl pt ps ro ru sc sr ii si sk sl es sv ta tt te th tr zh-cn zh-tw uk ur cy vi zu'
            .split())

        if 'LANGUAGE' in context.REQUEST:
            if context.REQUEST.LANGUAGE in AVAILABLE_LANGUAGES:
                results['language'] = context.REQUEST.LANGUAGE
            elif context.REQUEST.LANGUAGE[:2] in AVAILABLE_LANGUAGES:
                results['language'] = context.REQUEST.LANGUAGE[:2]
            else:
                results['language'] = "en"
        else:
            results['language'] = "en"

        try:
            results['document_url'] = context.absolute_url()

            obj = context
            while obj is not None:
                if IFolderish.providedBy(obj):
                    if obj.portal_type != 'TempFolder':
                        # do not use portal_factory generated
                        # temporary object for base url.
                        results['document_base_url'] = obj.absolute_url() + "/"
                        break

                # We should never reach this.
                if ISiteRoot.providedBy(obj):
                    results['document_base_url'] = portal_url + "/"
                    results['document_url'] = portal_url
                    break

                obj = aq_parent(aq_inner(obj))

        except AttributeError:
            results['document_base_url'] = portal_url + "/"
            results['document_url'] = portal_url

        # Get Library options
        results[
            'gecko_spellcheck'] = self.libraries_spellchecker_choice == 'browser'

        # Content Browser
        shortcuts_dict = dict(getUtilitiesFor(ITinyMCEShortcut))
        results['link_shortcuts_html'] = []
        results['image_shortcuts_html'] = []
        results['num_of_thumb_columns'] = self.num_of_thumb_columns
        results['thumbnail_size'] = self.thumbnail_size
        results['anchor_selector'] = self.anchor_selector

        for name in self.link_shortcuts:
            results['link_shortcuts_html'].extend(
                shortcuts_dict.get(name).render(context))
        for name in self.image_shortcuts:
            results['image_shortcuts_html'].extend(
                shortcuts_dict.get(name).render(context))

        # init vars specific for "After the Deadline" spellchecker
        mtool = getToolByName(portal, 'portal_membership')
        member = mtool.getAuthenticatedMember()
        results['atd_rpc_id'] = 'Products.TinyMCE-' + (
            member.getId() or '')  # None when Anonymous User
        results['atd_rpc_url'] = "%s/@@" % portal_url
        results['atd_show_types'] = self.libraries_atd_show_types.strip(
        ).replace('\n', ',')
        results[
            'atd_ignore_strings'] = self.libraries_atd_ignore_strings.strip(
            ).replace('\n', ',')

        # generic configuration
        results['mode'] = "exact"
        results['theme'] = "advanced"
        results['skin'] = "plone"
        results['inlinepopups_skin'] = "plonepopup"

        results['body_class'] = "documentContent"
        plone_view = context.restrictedTraverse('@@plone')
        template = None
        if IBrowserDefault.providedBy(context):
            template = context.unrestrictedTraverse(context.getLayout())
        results['body_class'] += ' ' + plone_view.bodyClass(template, template)

        results['body_id'] = "content"
        results['table_firstline_th'] = True
        results['fix_list_elements'] = False
        # allow embed tag if user removes it from
        # list of nasty tags - see #10681
        results['media_strict'] = False
        results['theme_advanced_path'] = False
        results['theme_advanced_toolbar_align'] = "left"

        results['plugins'] = self.getPlugins()
        results['theme_advanced_styles'] = self.getStyles(styles, labels)
        results['theme_advanced_buttons1'], results['theme_advanced_buttons2'], \
            results['theme_advanced_buttons3'], results['theme_advanced_buttons4'] = self.getToolbars(results)

        if self.formats and self.formats.strip():
            results['formats'] = json.loads(self.formats)

        return results
Ejemplo n.º 17
0
def get_default_page(context):
    """Given a folderish item, find out if it has a default-page using
    the following lookup rules:

        1. A content object called 'index_html' wins
        2. Else check for IBrowserDefault, either if the container implements
           it or if an adapter exists. In both cases fetch its FTI and either
           take it if it implements IDynamicViewTypeInformation or adapt it to
           IDynamicViewTypeInformation. call getDefaultPage on the implementer
           and take value if given.
        3. Else, look up the attribute default_page on the object, without
           acquisition in place
        3.1 look for a content in the container with the id, no acquisition!
        3.2 look for a content at portal, with acquisition
        4. Else, look up the property default_page in site_properties for
           magic ids and test these

    The id of the first matching item is then used to lookup a translation
    and if found, its id is returned. If no default page is set, None is
    returned. If a non-folderish item is passed in, return None always.
    """
    # met precondition?
    if not IFolderish.providedBy(context):
        return

    # The ids where we look for default - must support __contains__
    ids = set()

    # For BTreeFolders we just use the __contains__ otherwise build a set
    if isinstance(aq_base(context), BTreeFolder2Base):
        ids = context
    elif hasattr(aq_base(context), 'objectIds'):
        ids = set(context.objectIds())

    # 1. test for contentish index_html
    if 'index_html' in ids:
        return 'index_html'

    # 2. Test for IBrowserDefault
    if IBrowserDefault.providedBy(context):
        browserDefault = context
    else:
        browserDefault = queryAdapter(context, IBrowserDefault)

    if browserDefault is not None:
        fti = context.getTypeInfo()
        if fti is not None:
            if IDynamicViewTypeInformation.providedBy(fti):
                dynamic_fti = fti
            else:
                dynamic_fti = queryAdapter(fti, IDynamicViewTypeInformation)
            if dynamic_fti is not None:
                page = dynamic_fti.getDefaultPage(context, check_exists=True)
                if page is not None:
                    return page

    # 3.1 Test for default_page attribute in folder, no acquisition
    pages = getattr(aq_base(context), 'default_page', [])
    if isinstance(pages, basestring):
        pages = [pages]
    for page in pages:
        if page and page in ids:
            return page

    portal = queryUtility(ISiteRoot)
    # Might happen during portal creation
    if portal is None:
        return

    # 3.2 Test for default page in portal, acquire
    for page in pages:
        if portal.unrestrictedTraverse(page, None):
            return page

    # 4. Test for default sitewide default_page setting
    pp = getattr(portal, 'portal_properties', None)
    if pp is not None:
        site_properties = getattr(pp, 'site_properties', None)
        if site_properties is not None:
            for page in site_properties.getProperty('default_page', []):
                if page in ids:
                    return page
Ejemplo n.º 18
0
    def getConfiguration(self, context=None, field=None, request=None):
        """Return configuration as a dictionary

        :param field: Dexterity or Archetypes Field instance

        :param context: The TinyMCE editor content items

        :return: JSON string of the TinyMCE configuration for this field
        """
        results = {}

        # Get widget attributes
        widget = getattr(field, 'widget', None)
        filter_buttons = getattr(widget, 'filter_buttons', None)
        allow_buttons = getattr(widget, 'allow_buttons', None)
        redefine_parastyles = getattr(widget, 'redefine_parastyles', None)
        parastyles = getattr(widget, 'parastyles', None)
        rooted = getattr(widget, 'rooted', False)
        toolbar_width = getattr(widget, 'toolbar_width', self.toolbar_width)

        # Get safe html transform
        safe_html = getattr(getToolByName(self, 'portal_transforms'), 'safe_html')

        # Get kupu library tool filter
        # Settings are stored on safe_html transform in Plone 4 and
        # on kupu tool in Plone 3.
        kupu_library_tool = getToolByName(self, 'kupu_library_tool', None)

        # Remove to be stripped attributes
        try:
            style_whitelist = safe_html.get_parameter_value('style_whitelist')
        except (KeyError, AttributeError):
            if kupu_library_tool is not None:
                style_whitelist = kupu_library_tool.getStyleWhitelist()
            else:
                style_whitelist = []
        results['valid_inline_styles'] = ','.join(style_whitelist)  # tinymce format

        # Replacing some hardcoded translations
        labels = {}
        labels['label_browseimage'] = translate(_('Image Browser'), context=request)
        labels['label_browselink'] = translate(_('Link Browser'), context=request)
        labels['label_addnewimage'] = translate(_('Add new Image'), context=request)
        labels['label_addnewfile'] = translate(_('Add new File'), context=request)
        labels['label_styles'] = translate(_('(remove style)'), context=request)
        labels['label_paragraph'] = translate(_('Normal paragraph'), context=request)
        labels['label_plain_cell'] = translate(_('Plain cell'), context=request)
        labels['label_style_ldots'] = translate(_('Style...'), context=request)
        labels['label_text'] = translate(_('Text'), context=request)
        labels['label_tables'] = translate(_('Tables'), context=request)
        labels['label_selection'] = translate(_('Selection'), context=request)
        labels['label_lists'] = translate(_('Lists'), context=request)
        labels['label_print'] = translate(_('Print'), context=request)
        labels['label_no_items'] = translate(_('No items in this folder'), context=request)
        labels['label_no_anchors'] = translate(_('No anchors in this page'), context=request)
        labels['label_browser'] = translate(_('Browser'), context=request)
        labels['label_shortcuts'] = translate(_('Shortcuts'), context=request)
        labels['label_search_results'] = translate(_('Search results:'), context=request)
        labels['label_internal_path'] = translate(PMF("you_are_here", default="You are here:"), context=request)
        results['labels'] = labels

        # Add styles to results
        results['styles'] = []
        table_styles = []
        if not redefine_parastyles:
            if isinstance(self.tablestyles, StringTypes):
                for tablestyle in self.tablestyles.split('\n'):
                    if not tablestyle:
                        # empty line
                        continue
                    tablestylefields = tablestyle.split('|')
                    tablestyletitle = tablestylefields[0]
                    tablestyleid = tablestylefields[1]
                    if tablestyleid == 'plain':
                        # Do not duplicate the default style hardcoded in the
                        # table.htm.pt
                        continue
                    if request is not None:
                        tablestyletitle = translate(_(tablestylefields[0]), context=request)
                    results['styles'].append(tablestyletitle + '|table|' + tablestyleid)
                    table_styles.append(tablestyletitle + '=' + tablestyleid)
            if isinstance(self.styles, StringTypes):
                styles = []
                for style in self.styles.split('\n'):
                    if not style:
                        # empty line
                        continue
                    stylefields = style.split('|')
                    styletitle = stylefields[0]
                    if request is not None:
                        styletitle = translate(_(stylefields[0]), context=request)
                    merge = styletitle + '|' + '|'.join(stylefields[1:])
                    styles.append(merge)
                results['styles'].extend(styles)
        results['table_styles'] = ';'.join(table_styles)  # tinymce config

        if parastyles is not None:
            results['styles'].extend(parastyles)

        styles = results.pop('styles')

        # Get buttons from control panel
        results['buttons'] = self.getEnabledButtons(context=context)

        # Filter buttons
        if allow_buttons is not None:
            allow_buttons = self.translateButtonsFromKupu(context=context, buttons=allow_buttons)
            results['buttons'] = filter(lambda x: x in results['buttons'], allow_buttons)
        if filter_buttons is not None:
            filter_buttons = self.translateButtonsFromKupu(context=context, buttons=filter_buttons)
            results['buttons'] = filter(lambda x: x not in filter_buttons, results['buttons'])

        # Get valid html elements
        valid_elements = self.getValidElements()
        results['valid_elements'] = ','.join(["%s[%s]" % (key, '|'.join(value)) for key, value in valid_elements.iteritems()])

        # If safe_html transform is disabled, allow other non xhtml conform tags as well
        if results['valid_elements'] == '*[*]':
            results['valid_children'] = "+body[style]"

        # self.customplugins can be None on old migrated sites
        results['customplugins'] = (self.customplugins or "").splitlines()

        # Set toolbar_location
        if self.toolbar_external:
            results['theme_advanced_toolbar_location'] = 'external'
        else:
            results['theme_advanced_toolbar_location'] = 'top'

        if self.autoresize:
            results['theme_advanced_path_location'] = 'none'
            results['theme_advanced_resizing_use_cookie'] = False
            results['theme_advanced_resizing'] = False
            results['autoresize'] = True
        else:
            results['theme_advanced_path_location'] = 'bottom'
            results['theme_advanced_resizing_use_cookie'] = True
            results['theme_advanced_resizing'] = self.resizing
            results['autoresize'] = False

        if '%' in self.editor_width:
            results['theme_advanced_resize_horizontal'] = False
        else:
            results['theme_advanced_resize_horizontal'] = True

        try:
            results['theme_advanced_source_editor_width'] = int(self.editor_width)
        except (TypeError, ValueError):
            results['theme_advanced_source_editor_width'] = 600

        try:
            results['theme_advanced_source_editor_height'] = int(self.editor_height)
        except (TypeError, ValueError):
            results['theme_advanced_source_editor_height'] = 400

        try:
            results['toolbar_width'] = int(toolbar_width)
        except (TypeError, ValueError):
            results['toolbar_width'] = 440

        portal_state = context.restrictedTraverse('@@plone_portal_state')
        # is_rtl handles every possible setting as far as RTL/LTR is concerned
        # pass that to tinmyce
        results['directionality'] = portal_state.is_rtl() and 'rtl' or 'ltr'

        portal = portal_state.portal()
        portal_url = portal_state.portal_url()
        results['portal_url'] = portal_url
        results['navigation_root_url'] = portal_state.navigation_root_url()

        if self.content_css and self.content_css.strip() != "":
            results['content_css'] = self.content_css
        else:
            results['content_css'] = '/'.join([
                results['portal_url'],
                self.getId(),
                "@@tinymce-getstyle"])

        results['link_using_uids'] = self.link_using_uids
        results['contextmenu'] = self.contextmenu
        results['entity_encoding'] = self.entity_encoding
        results['script_url'] = portal_url + '/tiny_mce_gzip.js'
        results['allow_captioned_images'] = bool(self.allow_captioned_images)
        results['rooted'] = bool(self.rooted or rooted)

        props = getToolByName(portal, 'portal_properties')
        plone_livesearch = props.site_properties.getProperty('enable_livesearch', False)
        livesearch = props.site_properties.getProperty('enable_tinymce_livesearch', plone_livesearch)
        results['livesearch'] = bool(livesearch)

        AVAILABLE_LANGUAGES = set(
        'sq ar hy az eu be bn nb bs br bg ca ch zh hr cs da dv nl en et fi fr gl '
        'ka de el gu he hi hu is id ia it ja ko lv lt lb mk ms ml mn se no nn fa '
        'pl pt ps ro ru sc sr ii si sk sl es sv ta tt te th tr zh-cn zh-tw uk ur cy vi zu'.split())

        if 'LANGUAGE' in context.REQUEST:
            if context.REQUEST.LANGUAGE in AVAILABLE_LANGUAGES:
                results['language'] = context.REQUEST.LANGUAGE
            elif context.REQUEST.LANGUAGE[:2] in AVAILABLE_LANGUAGES:
                results['language'] = context.REQUEST.LANGUAGE[:2]
            else:
                results['language'] = "en"
        else:
            results['language'] = "en"

        try:
            results['document_url'] = context.absolute_url()

            obj = context
            while obj is not None:
                if IFolderish.providedBy(obj):
                    if obj.portal_type != 'TempFolder':
                        # do not use portal_factory generated
                        # temporary object for base url.
                        results['document_base_url'] = obj.absolute_url() + "/"
                        break

                # We should never reach this.
                if ISiteRoot.providedBy(obj):
                    results['document_base_url'] = portal_url + "/"
                    results['document_url'] = portal_url
                    break

                obj = aq_parent(aq_inner(obj))

        except AttributeError:
            results['document_base_url'] = portal_url + "/"
            results['document_url'] = portal_url

        # Get Library options
        results['gecko_spellcheck'] = self.libraries_spellchecker_choice == 'browser'

        # Content Browser
        shortcuts_dict = dict(getUtilitiesFor(ITinyMCEShortcut))
        results['link_shortcuts_html'] = []
        results['image_shortcuts_html'] = []
        results['num_of_thumb_columns'] = self.num_of_thumb_columns
        results['thumbnail_size'] = self.thumbnail_size
        results['anchor_selector'] = self.anchor_selector

        for name in self.link_shortcuts:
            results['link_shortcuts_html'].extend(shortcuts_dict.get(name).render(context))
        for name in self.image_shortcuts:
            results['image_shortcuts_html'].extend(shortcuts_dict.get(name).render(context))

        # init vars specific for "After the Deadline" spellchecker
        mtool = getToolByName(portal, 'portal_membership')
        member = mtool.getAuthenticatedMember()
        results['atd_rpc_id'] = 'Products.TinyMCE-' + (member.getId() or '')  # None when Anonymous User
        results['atd_rpc_url'] = "%s/@@" % portal_url
        results['atd_show_types'] = self.libraries_atd_show_types.strip().replace('\n', ',')
        results['atd_ignore_strings'] = self.libraries_atd_ignore_strings.strip().replace('\n', ',')

        # generic configuration
        results['mode'] = "exact"
        results['theme'] = "advanced"
        results['skin'] = "plone"
        results['inlinepopups_skin'] = "plonepopup"

        results['body_class'] = "documentContent"
        plone_view = context.restrictedTraverse('@@plone')
        template = None
        if IBrowserDefault.providedBy(context):
            template = context.unrestrictedTraverse(context.getLayout())
        results['body_class'] += ' ' + plone_view.bodyClass(template, template)

        results['body_id'] = "content"
        results['table_firstline_th'] = True
        results['fix_list_elements'] = False
        # allow embed tag if user removes it from
        # list of nasty tags - see #10681
        results['media_strict'] = False
        results['theme_advanced_path'] = False
        results['theme_advanced_toolbar_align'] = "left"

        results['plugins'] = self.getPlugins()
        results['theme_advanced_styles'] = self.getStyles(styles, labels)
        results['theme_advanced_buttons1'], results['theme_advanced_buttons2'], \
            results['theme_advanced_buttons3'], results['theme_advanced_buttons4'] = self.getToolbars(results)

        if self.formats and self.formats.strip():
            results['formats'] = json.loads(self.formats)

        return results
Ejemplo n.º 19
0
    def getConfiguration(self, context=None, field=None, request=None):
        """Return configuration as a dictionary

        :param field: Dexterity or Archetypes Field instance

        :param context: The TinyMCE editor content items

        :return: JSON string of the TinyMCE configuration for this field
        """
        results = {}

        # Get widget attributes
        widget = getattr(field, "widget", None)
        filter_buttons = getattr(widget, "filter_buttons", None)
        allow_buttons = getattr(widget, "allow_buttons", None)
        redefine_parastyles = getattr(widget, "redefine_parastyles", None)
        parastyles = getattr(widget, "parastyles", None)
        rooted = getattr(widget, "rooted", False)
        toolbar_width = getattr(widget, "toolbar_width", self.toolbar_width)

        # Get safe html transform
        safe_html = getattr(getToolByName(self, "portal_transforms"), "safe_html")

        # Get kupu library tool filter
        # Settings are stored on safe_html transform in Plone 4 and
        # on kupu tool in Plone 3.
        kupu_library_tool = getToolByName(self, "kupu_library_tool", None)

        # Remove to be stripped attributes
        try:
            style_whitelist = safe_html.get_parameter_value("style_whitelist")
        except (KeyError, AttributeError):
            if kupu_library_tool is not None:
                style_whitelist = kupu_library_tool.getStyleWhitelist()
            else:
                style_whitelist = []
        results["valid_inline_styles"] = ",".join(style_whitelist)  # tinymce format

        # Replacing some hardcoded translations
        labels = {}
        labels["label_browseimage"] = translate(_("Image Browser"), context=request)
        labels["label_browselink"] = translate(_("Link Browser"), context=request)
        labels["label_addnewimage"] = translate(_("Add new Image"), context=request)
        labels["label_addnewfile"] = translate(_("Add new File"), context=request)
        labels["label_styles"] = translate(_("(remove style)"), context=request)
        labels["label_paragraph"] = translate(_("Normal paragraph"), context=request)
        labels["label_plain_cell"] = translate(_("Plain cell"), context=request)
        labels["label_style_ldots"] = translate(_("Style..."), context=request)
        labels["label_text"] = translate(_("Text"), context=request)
        labels["label_tables"] = translate(_("Tables"), context=request)
        labels["label_selection"] = translate(_("Selection"), context=request)
        labels["label_lists"] = translate(_("Lists"), context=request)
        labels["label_print"] = translate(_("Print"), context=request)
        labels["label_no_items"] = translate(_("No items in this folder"), context=request)
        labels["label_no_anchors"] = translate(_("No anchors in this page"), context=request)
        labels["label_browser"] = translate(_("Browser"), context=request)
        labels["label_shortcuts"] = translate(_("Shortcuts"), context=request)
        labels["label_search_results"] = translate(_("Search results:"), context=request)
        labels["label_internal_path"] = translate(PMF("you_are_here", default="You are here:"), context=request)
        results["labels"] = labels

        # Add styles to results
        results["styles"] = []
        table_styles = []
        if not redefine_parastyles:
            if isinstance(self.tablestyles, StringTypes):
                for tablestyle in self.tablestyles.split("\n"):
                    if not tablestyle:
                        # empty line
                        continue
                    tablestylefields = tablestyle.split("|")
                    tablestyletitle = tablestylefields[0]
                    tablestyleid = tablestylefields[1]
                    if tablestyleid == "plain":
                        # Do not duplicate the default style hardcoded in the
                        # table.htm.pt
                        continue
                    if request is not None:
                        tablestyletitle = translate(_(tablestylefields[0]), context=request)
                    results["styles"].append(tablestyletitle + "|table|" + tablestyleid)
                    table_styles.append(tablestyletitle + "=" + tablestyleid)
            if isinstance(self.styles, StringTypes):
                styles = []
                for style in self.styles.split("\n"):
                    if not style:
                        # empty line
                        continue
                    stylefields = style.split("|")
                    styletitle = stylefields[0]
                    if request is not None:
                        styletitle = translate(_(stylefields[0]), context=request)
                    merge = styletitle + "|" + "|".join(stylefields[1:])
                    styles.append(merge)
                results["styles"].extend(styles)
        results["table_styles"] = ";".join(table_styles)  # tinymce config

        if parastyles is not None:
            results["styles"].extend(parastyles)

        styles = results.pop("styles")

        # Get buttons from control panel
        results["buttons"] = self.getEnabledButtons(context=context)

        # Filter buttons
        if allow_buttons is not None:
            allow_buttons = self.translateButtonsFromKupu(context=context, buttons=allow_buttons)
            results["buttons"] = filter(lambda x: x in results["buttons"], allow_buttons)
        if filter_buttons is not None:
            filter_buttons = self.translateButtonsFromKupu(context=context, buttons=filter_buttons)
            results["buttons"] = filter(lambda x: x not in filter_buttons, results["buttons"])

        # Get valid html elements
        valid_elements = self.getValidElements()
        results["valid_elements"] = ",".join(
            ["%s[%s]" % (key, "|".join(value)) for key, value in valid_elements.iteritems()]
        )

        # self.customplugins can be None on old migrated sites
        results["customplugins"] = (self.customplugins or "").splitlines()

        # Set toolbar_location
        if self.toolbar_external:
            results["theme_advanced_toolbar_location"] = "external"
        else:
            results["theme_advanced_toolbar_location"] = "top"

        if self.autoresize:
            results["theme_advanced_path_location"] = "none"
            results["theme_advanced_resizing_use_cookie"] = False
            results["theme_advanced_resizing"] = False
            results["autoresize"] = True
        else:
            results["theme_advanced_path_location"] = "bottom"
            results["theme_advanced_resizing_use_cookie"] = True
            results["theme_advanced_resizing"] = self.resizing
            results["autoresize"] = False

        if "%" in self.editor_width:
            results["theme_advanced_resize_horizontal"] = False
        else:
            results["theme_advanced_resize_horizontal"] = True

        try:
            results["theme_advanced_source_editor_width"] = int(self.editor_width)
        except (TypeError, ValueError):
            results["theme_advanced_source_editor_width"] = 600

        try:
            results["theme_advanced_source_editor_height"] = int(self.editor_height)
        except (TypeError, ValueError):
            results["theme_advanced_source_editor_height"] = 400

        try:
            results["toolbar_width"] = int(toolbar_width)
        except (TypeError, ValueError):
            results["toolbar_width"] = 440

        portal_state = context.restrictedTraverse("@@plone_portal_state")
        # is_rtl handles every possible setting as far as RTL/LTR is concerned
        # pass that to tinmyce
        results["directionality"] = portal_state.is_rtl() and "rtl" or "ltr"

        portal = portal_state.portal()
        portal_url = portal_state.portal_url()
        results["portal_url"] = portal_url
        results["navigation_root_url"] = portal_state.navigation_root_url()

        if self.content_css and self.content_css.strip() != "":
            results["content_css"] = self.content_css
        else:
            results["content_css"] = "/".join([results["portal_url"], self.getId(), "@@tinymce-getstyle"])

        results["link_using_uids"] = self.link_using_uids
        results["contextmenu"] = self.contextmenu
        results["entity_encoding"] = self.entity_encoding
        results["script_url"] = portal_url + "/tiny_mce_gzip.js"
        results["allow_captioned_images"] = bool(self.allow_captioned_images)
        results["rooted"] = bool(self.rooted or rooted)

        props = getToolByName(portal, "portal_properties")
        plone_livesearch = props.site_properties.getProperty("enable_livesearch", False)
        livesearch = props.site_properties.getProperty("enable_tinymce_livesearch", plone_livesearch)
        results["livesearch"] = bool(livesearch)

        AVAILABLE_LANGUAGES = set(
            "sq ar hy az eu be bn nb bs br bg ca ch zh hr cs da dv nl en et fi fr gl "
            "ka de el gu he hi hu is id ia it ja ko lv lt lb mk ms ml mn se no nn fa "
            "pl pt ps ro ru sc sr ii si sk sl es sv ta tt te th tr zh-cn zh-tw uk ur cy vi zu".split()
        )

        if "LANGUAGE" in context.REQUEST:
            if context.REQUEST.LANGUAGE in AVAILABLE_LANGUAGES:
                results["language"] = context.REQUEST.LANGUAGE
            elif context.REQUEST.LANGUAGE[:2] in AVAILABLE_LANGUAGES:
                results["language"] = context.REQUEST.LANGUAGE[:2]
            else:
                results["language"] = "en"
        else:
            results["language"] = "en"

        try:
            results["document_url"] = context.absolute_url()

            obj = context
            while obj is not None:
                if IFolderish.providedBy(obj):
                    if obj.portal_type != "TempFolder":
                        # do not use portal_factory generated
                        # temporary object for base url.
                        results["document_base_url"] = obj.absolute_url() + "/"
                        break

                # We should never reach this.
                if ISiteRoot.providedBy(obj):
                    results["document_base_url"] = portal_url + "/"
                    results["document_url"] = portal_url
                    break

                obj = aq_parent(aq_inner(obj))

        except AttributeError:
            results["document_base_url"] = portal_url + "/"
            results["document_url"] = portal_url

        # Get Library options
        results["gecko_spellcheck"] = self.libraries_spellchecker_choice == "browser"

        # Content Browser
        shortcuts_dict = dict(getUtilitiesFor(ITinyMCEShortcut))
        results["link_shortcuts_html"] = []
        results["image_shortcuts_html"] = []
        results["num_of_thumb_columns"] = self.num_of_thumb_columns
        results["thumbnail_size"] = self.thumbnail_size
        results["anchor_selector"] = self.anchor_selector

        for name in self.link_shortcuts:
            results["link_shortcuts_html"].extend(shortcuts_dict.get(name).render(context))
        for name in self.image_shortcuts:
            results["image_shortcuts_html"].extend(shortcuts_dict.get(name).render(context))

        # init vars specific for "After the Deadline" spellchecker
        mtool = getToolByName(portal, "portal_membership")
        member = mtool.getAuthenticatedMember()
        results["atd_rpc_id"] = "Products.TinyMCE-" + (member.getId() or "")  # None when Anonymous User
        results["atd_rpc_url"] = "%s/@@" % portal_url
        results["atd_show_types"] = self.libraries_atd_show_types.strip().replace("\n", ",")
        results["atd_ignore_strings"] = self.libraries_atd_ignore_strings.strip().replace("\n", ",")

        # generic configuration
        results["mode"] = "exact"
        results["theme"] = "advanced"
        results["skin"] = "plone"
        results["inlinepopups_skin"] = "plonepopup"

        results["body_class"] = "documentContent"
        plone_view = context.restrictedTraverse("@@plone")
        template = None
        if IBrowserDefault.providedBy(context):
            template = context.unrestrictedTraverse(context.getLayout())
        results["body_class"] += " " + plone_view.bodyClass(template, template)

        results["body_id"] = "content"
        results["table_firstline_th"] = True
        results["fix_list_elements"] = False
        # allow embed tag if user removes it from
        # list of nasty tags - see #10681
        results["media_strict"] = False
        results["theme_advanced_path"] = False
        results["theme_advanced_toolbar_align"] = "left"

        results["plugins"] = self.getPlugins()
        results["theme_advanced_styles"] = self.getStyles(styles, labels)
        results["theme_advanced_buttons1"], results["theme_advanced_buttons2"], results[
            "theme_advanced_buttons3"
        ], results["theme_advanced_buttons4"] = self.getToolbars(results)

        if self.formats and self.formats.strip():
            results["formats"] = json.loads(self.formats)

        return results
Ejemplo n.º 20
0
def getDefaultPage(context):
    """Given a folderish item, find out if it has a default-page using
    the following lookup rules:

        1. A content object called 'index_html' wins
        2. If the folder implements IBrowserDefault, query this
        3. Else, look up the property default_page on the object
            - Note that in this case, the returned id may *not* be of an
              object in the folder, since it could be acquired from a
              parent folder or skin layer
        4. Else, look up the property default_page in site_properties for
            magic ids and test these

    The id of the first matching item is then used to lookup a translation
    and if found, its id is returned. If no default page is set, None is
    returned. If a non-folderish item is passed in, return None always.
    """
    # The list of ids where we look for default
    ids = {}

    # For BTreeFolders we just use the has_key, otherwise build a dict
    if hasattr(aq_base(context), 'has_key'):
        ids = context
    elif hasattr(aq_base(context), 'objectIds'):
        for id in context.objectIds():
            ids[id] = 1

    # 1. test for contentish index_html
    if 'index_html' in ids:
        return 'index_html'

    # 2. Test for IBrowserDefault
    if IBrowserDefault.providedBy(context):
        browserDefault = context
    else:
        browserDefault = queryAdapter(context, IBrowserDefault)

    if browserDefault is not None:
        fti = context.getTypeInfo()
        if fti is not None:
            if IDynamicViewTypeInformation.providedBy(fti):
                dynamicFTI = fti
            else:
                dynamicFTI = queryAdapter(fti, IDynamicViewTypeInformation)
            if dynamicFTI is not None:
                page = dynamicFTI.getDefaultPage(context, check_exists=True)
                if page is not None:
                    return page

    # 3. Test for default_page property in folder, then skins
    pages = getattr(aq_base(context), 'default_page', [])
    if isinstance(pages, basestring):
        pages = [pages]
    for page in pages:
        if page and page in ids:
            return page

    portal = queryUtility(ISiteRoot)
    # Might happen during portal creation
    if portal is not None:
        for page in pages:
            if portal.unrestrictedTraverse(page, None):
                return page

        # 4. Test for default sitewide default_page setting
        pp = getattr(portal, 'portal_properties', None)
        if pp is not None:
            site_properties = getattr(pp, 'site_properties', None)
            if site_properties is not None:
                for page in site_properties.getProperty('default_page', []):
                    if page in ids:
                        return page

    return None
Ejemplo n.º 21
0
def getDefaultPage(context):
    """Given a folderish item, find out if it has a default-page using
    the following lookup rules:

        1. A content object called 'index_html' wins
        2. If the folder implements IBrowserDefault, query this
        3. Else, look up the property default_page on the object
            - Note that in this case, the returned id may *not* be of an
              object in the folder, since it could be acquired from a
              parent folder or skin layer
        4. Else, look up the property default_page in site_properties for
            magic ids and test these

    The id of the first matching item is then used to lookup a translation
    and if found, its id is returned. If no default page is set, None is
    returned. If a non-folderish item is passed in, return None always.
    """
    # The list of ids where we look for default
    ids = {}

    # For BTreeFolders we just use the has_key, otherwise build a dict
    if hasattr(aq_base(context), 'has_key'):
        ids = context
    else:
        for id in context.objectIds():
            ids[id] = 1

    # 1. test for contentish index_html
    if 'index_html' in ids:
        return 'index_html'

    # 2. Test for IBrowserDefault
    if IBrowserDefault.providedBy(context):
        browserDefault = context
    else:
        browserDefault = queryAdapter(context, IBrowserDefault)

    if browserDefault is not None:
        fti = context.getTypeInfo()
        if fti is not None:
            if IDynamicViewTypeInformation.providedBy(fti):
                dynamicFTI = fti
            else:
                dynamicFTI = queryAdapter(fti, IDynamicViewTypeInformation)
            if dynamicFTI is not None:
                page = dynamicFTI.getDefaultPage(context, check_exists=True)
                if page is not None:
                    return page

    # 3. Test for default_page property in folder, then skins
    pages = getattr(aq_base(context), 'default_page', [])
    if isinstance(pages, basestring):
        pages = [pages]
    for page in pages:
        if page and page in ids:
            return page

    portal = queryUtility(ISiteRoot)
    # Might happen during portal creation
    if portal is not None:
        for page in pages:
            if portal.unrestrictedTraverse(page, None):
                return page

        # 4. Test for default sitewide default_page setting
        pp = getattr(portal, 'portal_properties', None)
        if pp is not None:
            site_properties = getattr(pp, 'site_properties', None)
            if site_properties is not None:
                for page in site_properties.getProperty('default_page', []):
                    if page in ids:
                        return page

    return None