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))
def ContentTypes(context):
    #    portal_state = getMultiAdapter((context, context.REQUEST), name=u'plone_portal_state')
    #    allowedCT = portal_state.friendly_types()
    #    allowedCT = portal_types.listContentTypes()
    portal_types = getMultiAdapter((context, context.REQUEST), name=u"plone_tools").types()
    #    allowedCT = [t for t in portal_types.listTypeInfo() if t.global_allow]
    allowedCT = [t for t in portal_types.listTypeInfo() if IDynamicViewTypeInformation.providedBy(t)]

    return SimpleVocabulary([SimpleTerm(value=t.getId(), title=t.Title()) for t in allowedCT])
Exemple #3
0
 def testSmallContentDynamicViewFTI(self):
     """SmallContent implemented by IDynamicViewTypeInformation"""
     small = getattr(self.folder, 'small')
     from Products.CMFDynamicViewFTI.interfaces import IDynamicViewTypeInformation
     info = self.portal.portal_types['SmallContent']
     self.failUnless(IDynamicViewTypeInformation.isImplementedBy(info))
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
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, six.string_types):
        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
    registry = getUtility(IRegistry)
    for page in registry.get('plone.default_page', []):
        if page in ids:
            return page
    def update(self):

        self.path = '/'.join(self.context.getPhysicalPath())
        self.cls = self.context.__class__

        self.fti = None
        self.methodAliases = None

        if IDynamicType.providedBy(self.context):
            self.fti = self.context.getTypeInfo()
            self.methodAliases = sorted(self.fti.getMethodAliases().items())

        self.defaultView = None
        self.viewMethods = []
        if IDynamicViewTypeInformation.providedBy(self.fti):
            self.defaultView = self.fti.defaultView(self.context)
            self.viewMethods = self.fti.getAvailableViewMethods(self.context)

        directly_provided = directlyProvidedBy(self.context)
        self.provided = list(providedBy(self.context).flattened())
        self.provided.sort(key=lambda i: i.__identifier__)
        self.provided = ({
            'dottedname': i.__identifier__,
            'is_marker': i in directly_provided
        } for i in self.provided)
        self.views = []

        generator = getAdapters((
            self.context,
            self.request,
        ), Interface)
        while True:
            try:
                name, view = generator.next()

                if not IView.providedBy(view):
                    continue

                cls = view.__class__
                module = cls.__module__
                template = None

                if isinstance(view, ViewMixinForTemplates):
                    template = view.index.filename
                else:
                    for attr in ('index', 'template', '__call__'):
                        pt = getattr(view, attr, None)
                        if hasattr(pt, 'filename'):
                            template = pt.filename
                            break

                # Deal with silly Five metaclasses
                if (module == 'Products.Five.metaclass'
                        and len(cls.__bases__) > 0):
                    cls = cls.__bases__[0]
                elif cls == ViewMixinForTemplates:
                    cls = None

                self.views.append({
                    'name': name,
                    'class': cls,
                    'template': template,
                })
            except StopIteration:
                break
            except:
                # Some adapters don't initialise cleanly
                pass

        self.views.sort(key=lambda v: v['name'])

        self.methods = []
        self.variables = []

        _marker = object()
        for name in sorted(dir(aq_base(self.context))):
            attr = getattr(aq_base(self.context), name, _marker)
            if attr is _marker:
                continue

            # FIXME: Should we include ComputedAttribute here ? [glenfant]
            if isinstance(attr, (int, long, float, basestring, bool, list,
                                 tuple, dict, set, frozenset)):
                self.variables.append({
                    'name': name,
                    'primitive': True,
                    'value': attr,
                })
            elif (isinstance(attr,
                             (types.MethodType, types.BuiltinFunctionType,
                              types.BuiltinMethodType, types.FunctionType))
                  or attr.__class__.__name__ == 'method-wrapper', ):

                source = None
                if name.endswith('__roles__'):
                    # name without '__roles__' is the last in self.methods since we're in a sorted(...) loop
                    if callable(attr):
                        secu_infos = attr()
                    else:
                        secu_infos = attr
                    if secu_infos is None:
                        secu_label = 'Public'
                    else:
                        secu_label = ''
                        try:
                            secu_label += 'Roles: ' + ', '.join(
                                [r for r in secu_infos[:-1]])
                        except TypeError:
                            # Avoid "TypeError: sequence index must be
                            # integer, not 'slice'", which occurs with the
                            # ``C`` security implementation. This is a rare
                            # case. In development you normally use the
                            # ``Python`` security implementation, where this
                            # error doesn't occur.
                            pass
                        secu_label += '. Permission: ' + secu_infos[-1][
                            1:-11]  # _x_Permission -> x
                    self.methods[-1]['secu_infos'] = secu_label
                else:
                    try:
                        source = inspect.getsourcefile(attr)
                    except TypeError:
                        None

                    signature = name + "()"
                    try:
                        signature = name + inspect.formatargspec(
                            *inspect.getargspec(attr))
                    except TypeError:
                        pass

                    self.methods.append({
                        'signature': signature,
                        'filename': source,
                        'help': inspect.getdoc(attr),
                    })
            else:
                self.variables.append({
                    'name': name,
                    'primitive': False,
                    'value': str(attr),
                })
    def update(self):

        self.path = '/'.join(self.context.getPhysicalPath())
        self.cls = self.context.__class__

        self.fti = None
        self.methodAliases = None

        if IDynamicType.providedBy(self.context):
            self.fti = self.context.getTypeInfo()
            self.methodAliases = sorted(self.fti.getMethodAliases().items())

        self.defaultView = None
        self.viewMethods = []
        if IDynamicViewTypeInformation.providedBy(self.fti):
            self.defaultView = self.fti.defaultView(self.context)
            self.viewMethods = self.fti.getAvailableViewMethods(self.context)

        directly_provided = directlyProvidedBy(self.context)
        self.provided = list(providedBy(self.context).flattened())
        self.provided.sort(key=lambda i: i.__identifier__)
        self.provided = ({'dottedname': i.__identifier__,
                          'is_marker': i in directly_provided}
                          for i in self.provided)
        self.views = []

        generator = getAdapters((self.context, self.request,), Interface)
        while True:
            try:
                name, view = generator.next()

                if not IView.providedBy(view):
                    continue

                cls = view.__class__
                module = cls.__module__
                template = None

                if isinstance(view, ViewMixinForTemplates):
                    template = view.index.filename
                else:
                    for attr in ('index', 'template', '__call__'):
                        pt = getattr(view, attr, None)
                        if hasattr(pt, 'filename'):
                            template = pt.filename
                            break

                # Deal with silly Five metaclasses
                if (
                    module == 'Products.Five.metaclass' and
                    len(cls.__bases__) > 0
                ):
                    cls = cls.__bases__[0]
                elif cls == ViewMixinForTemplates:
                    cls = None

                self.views.append({
                    'name': name,
                    'class': cls,
                    'template': template,
                })
            except StopIteration:
                break
            except:
                # Some adapters don't initialise cleanly
                pass

        self.views.sort(key=lambda v: v['name'])

        self.methods = []
        self.variables = []

        _marker = object()
        for name in sorted(dir(aq_base(self.context))):
            attr = getattr(aq_base(self.context), name, _marker)
            if attr is _marker:
                continue

            # FIXME: Should we include ComputedAttribute here ? [glenfant]
            if isinstance(attr, (int, long, float, basestring, bool, list, tuple, dict, set, frozenset)):
                self.variables.append({
                    'name': name,
                    'primitive': True,
                    'value': attr,
                })
            elif (
                isinstance(attr, (types.MethodType, types.BuiltinFunctionType, types.BuiltinMethodType, types.FunctionType)) or
                attr.__class__.__name__ == 'method-wrapper',
            ):

                source = None
                if name.endswith('__roles__'):
                    # name without '__roles__' is the last in self.methods since we're in a sorted(...) loop
                    if callable(attr):
                        secu_infos = attr()
                    else:
                        secu_infos = attr
                    if secu_infos is None:
                        secu_label = 'Public'
                    else:
                        secu_label = ''
                        try:
                            secu_label += 'Roles: ' + ', '.join([r for r in secu_infos[:-1]])
                        except TypeError:
                            # Avoid "TypeError: sequence index must be
                            # integer, not 'slice'", which occurs with the
                            # ``C`` security implementation. This is a rare
                            # case. In development you normally use the
                            # ``Python`` security implementation, where this
                            # error doesn't occur.
                            pass
                        secu_label += '. Permission: ' + secu_infos[-1][1:-11]  # _x_Permission -> x
                    self.methods[-1]['secu_infos'] = secu_label
                else:
                    try:
                        source = inspect.getsourcefile(attr)
                    except TypeError:
                        None

                    signature = name + "()"
                    try:
                        signature = name + inspect.formatargspec(*inspect.getargspec(attr))
                    except TypeError:
                        pass

                    self.methods.append({
                        'signature': signature,
                        'filename': source,
                        'help': inspect.getdoc(attr),
                    })
            else:
                self.variables.append({
                    'name': name,
                    'primitive': False,
                    'value': str(attr),
                })
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
    def update(self):
        
        self.path = '/'.join(self.context.getPhysicalPath())
        self.cls = self.context.__class__

        self.fti = None
        self.methodAliases = None

        if IDynamicType.providedBy(self.context):
            self.fti = self.context.getTypeInfo()
            self.methodAliases = sorted(self.fti.getMethodAliases().items())
        
        self.defaultView = None
        self.viewMethods = []
        if IDynamicViewTypeInformation.providedBy(self.fti):
            self.defaultView = self.fti.defaultView(self.context)
            self.viewMethods = self.fti.getAvailableViewMethods(self.context)
        
        self.provided = list(providedBy(self.context).flattened())
        self.provided.sort(key=lambda i: i.__identifier__)

        self.views = []
        
        generator = getAdapters((self.context, self.request,), Interface)
        while True:
            try:
                name, view = generator.next()

                if not IView.providedBy(view):
                    continue

                cls = view.__class__
                module = cls.__module__
                template = None

                if isinstance(view, ViewMixinForTemplates):
                    template = view.index.filename
                else:
                    for attr in ('index', 'template', '__call__'):
                        pt = getattr(view, attr, None)
                        if hasattr(pt, 'filename'):
                            template = pt.filename
                            break

                # Deal with silly Five metaclasses
                if (
                    module == 'Products.Five.metaclass' and 
                    len(cls.__bases__) > 0
                ):
                    cls = cls.__bases__[0]
                elif cls == ViewMixinForTemplates:
                    cls = None

                self.views.append({
                    'name': name,
                    'class': cls,
                    'template': template,
                })
            except StopIteration:
                break
            except:
                # Some adapters don't initialise cleanly
                pass
        
        self.views.sort(key=lambda v: v['name'])

        self.methods = []
        self.variables = []

        _marker = object()
        for name in sorted(dir(aq_base(self.context))):
            attr = getattr(aq_base(self.context), name, _marker)
            if attr is _marker:
                continue
            
            if isinstance(attr, (int, long, float, basestring, bool, list, tuple, dict, set, frozenset)):
                self.variables.append({
                    'name': name,
                    'primitive': True,
                    'value': attr,
                })
            elif (
                isinstance(attr, (types.MethodType, types.BuiltinFunctionType, types.BuiltinMethodType, types.FunctionType)) or
                attr.__class__.__name__ == 'method-wrapper',
            ):
                
                source = None
                try:
                    source = inspect.getsourcefile(attr)
                except TypeError:
                    None

                signature = name + "()"
                try:
                    signature = name + inspect.formatargspec(*inspect.getargspec(attr))
                except TypeError:
                    pass

                self.methods.append({
                    'signature': signature,
                    'filename': source,
                    'help': inspect.getdoc(attr),
                })
            else:
                self.variables.append({
                    'name': name,
                    'primitive': False,
                    'value': str(attr),
                })
Exemple #10
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