def setUp(self):
        super(AuthZopePublicationTests, self).setUp()
        principalRegistry.defineDefaultPrincipal('anonymous', '')

        root = self.db.open().root()
        app = root[ZopePublication.root_name]
        app['f1'] = rootFolder()
        f1 = app['f1']
        f1['f2'] = Folder()
        if not ISite.providedBy(f1):
            f1.setSiteManager(LocalSiteManager(f1))
        sm1 = f1.getSiteManager()
        addUtility(sm1, '', IAuthentication, AuthUtility1())

        f2 = f1['f2']
        if not ISite.providedBy(f2):
            f2.setSiteManager(LocalSiteManager(f2))
        sm2 = f2.getSiteManager()
        addUtility(sm2, '', IAuthentication, AuthUtility2())
        transaction.commit()

        from zope.container.interfaces import ISimpleReadContainer
        from zope.container.traversal import ContainerTraverser

        component.provideAdapter(ContainerTraverser,
                                 (ISimpleReadContainer, IRequest),
                                 IPublishTraverse,
                                 name='')

        from zope.site.interfaces import IFolder
        from zope.security.checker import defineChecker, InterfaceChecker
        defineChecker(Folder, InterfaceChecker(IFolder))
    def setUp(self):
        super(AuthZopePublicationTests, self).setUp()
        principalRegistry.defineDefaultPrincipal('anonymous', '')

        root = self.db.open().root()
        app = root[ZopePublication.root_name]
        app['f1'] = rootFolder()
        f1 = app['f1']
        f1['f2'] = Folder()
        if not ISite.providedBy(f1):
            f1.setSiteManager(LocalSiteManager(f1))
        sm1 = f1.getSiteManager()
        addUtility(sm1, '', IAuthentication, AuthUtility1())

        f2 = f1['f2']
        if not ISite.providedBy(f2):
            f2.setSiteManager(LocalSiteManager(f2))
        sm2 = f2.getSiteManager()
        addUtility(sm2, '', IAuthentication, AuthUtility2())
        transaction.commit()

        from zope.container.interfaces import ISimpleReadContainer
        from zope.container.traversal import ContainerTraverser

        component.provideAdapter(ContainerTraverser,
                                 (ISimpleReadContainer, IRequest),
                                 IPublishTraverse, name='')

        from zope.site.interfaces import IFolder
        from zope.security.checker import defineChecker, InterfaceChecker
        defineChecker(Folder, InterfaceChecker(IFolder))
Exemplo n.º 3
0
 def test_get_and_set(self):
     smc = self.makeTestObject()
     self.failIf(ISite.providedBy(smc))
     sm = site.LocalSiteManager(smc)
     smc.setSiteManager(sm)
     self.failUnless(ISite.providedBy(smc))
     self.failUnless(smc.getSiteManager() is sm)
     zope.interface.verify.verifyObject(ISite, smc)
Exemplo n.º 4
0
 def test_get_and_set(self):
     smc = self.makeTestObject()
     self.failIf(ISite.providedBy(smc))
     sm = site.LocalSiteManager(smc)
     smc.setSiteManager(sm)
     self.failUnless(ISite.providedBy(smc))
     self.failUnless(smc.getSiteManager() is sm)
     zope.interface.verify.verifyObject(ISite, smc)
Exemplo n.º 5
0
 def test_get_and_set(self):
     smc = self.makeTestObject()
     self.assertFalse(ISite.providedBy(smc))
     sm = site.LocalSiteManager(smc)
     smc.setSiteManager(sm)
     self.assertTrue(ISite.providedBy(smc))
     self.assertTrue(smc.getSiteManager() is sm)
     zope.interface.verify.verifyObject(ISite, smc)
Exemplo n.º 6
0
def setUp(test):
    from zope.component.testing import setUp
    setUp()
    from zope.container.testing import setUp
    setUp()
    from zope.component import hooks
    hooks.setHooks()
    from zope.traversing.testing import setUp
    setUp()

    from zope.publisher.browser import BrowserLanguages
    from zope.publisher.interfaces.http import IHTTPRequest
    from zope.i18n.interfaces import IUserPreferredLanguages
    zope.component.provideAdapter(BrowserLanguages, [IHTTPRequest],
                   IUserPreferredLanguages)

    from zope.site.folder import rootFolder
    site = rootFolder()
    from zope.site.site import LocalSiteManager
    from zope.component.interfaces import ISite
    if not ISite.providedBy(site):
        site.setSiteManager(LocalSiteManager(site))
    hooks.setSite(site)
    test.globs = {
        'print_function': print_function,
        'root': site,
        'pprint': pprint.pprint}
Exemplo n.º 7
0
def createSiteManager(folder, setsite=False):
    "Make the given folder a site, and optionally make it the current site."
    if not ISite.providedBy(folder):
        folder.setSiteManager(LocalSiteManager(folder))
    if setsite:
        setSite(folder)
    return traverse(folder, "++etc++site")
Exemplo n.º 8
0
def setUp(self):
    """Test setUp based on z3c.form.testing.setUp minus their globals.
    """
    from zope.component.testing import setUp
    setUp()
    from zope.container.testing import setUp
    setUp()
    from zope.component import hooks
    hooks.setHooks()
    from zope.traversing.testing import setUp
    setUp()

    from zope.publisher.browser import BrowserLanguages
    from zope.publisher.interfaces.http import IHTTPRequest
    from zope.i18n.interfaces import IUserPreferredLanguages
    import zope.component
    zope.component.provideAdapter(
        BrowserLanguages, [IHTTPRequest], IUserPreferredLanguages)

    from zope.site.folder import rootFolder
    site = rootFolder()
    from zope.site.site import LocalSiteManager
    from zope.component.interfaces import ISite
    if not ISite.providedBy(site):
        site.setSiteManager(LocalSiteManager(site))
    hooks.setSite(site)
    def test_registry_assignment(self):
        setRoles(self.portal, TEST_USER_ID, ['Manager'])
        self.oid = self.portal.invokeFactory('Folder', 'folder')
        setRoles(self.portal, TEST_USER_ID, ['Member'])

        folder = self.portal[self.oid]
        registry = getUtility(IRegistry)

        if not ISite.providedBy(folder):
            make_objectmanager_site(folder)

        setSite(folder)

        pc = getToolByName(folder, 'portal_catalog')
        pc.reindexObject(folder, idxs=['object_provides'])

        enableRegistry(folder)
        self.assertIn(REGISTRY_NAME, folder.objectIds())

        registry = getUtility(IRegistry)
        self.assertTrue(isinstance(registry, LineageRegistry))

        disableRegistry(folder)
        registry = getUtility(IRegistry)
        self.assertTrue(isinstance(registry, Registry))
Exemplo n.º 10
0
    def test_migration_preserves_references(self):
        portal = self.layer['portal']
        z2.login(portal['acl_users'], 'manager')
        portal.invokeFactory("Child Folder", "cf1")
        cf1 = portal.cf1
        cf1.setTitle("CF 1")
        make_objectmanager_site(cf1)
        pw = portal.portal_workflow
        pw.doActionFor(cf1, "publish")
        self.failUnless(cf1.Title() == "CF 1")
        self.failUnless(pw.getInfoFor(cf1, "review_state") == "published")
        self.failUnless(ISite.providedBy(cf1))

        cf1.invokeFactory("Document", "doc1", Title="Doc 1")
        doc1 = cf1["doc1"]
        cf1.setDefaultPage("doc1")

        doc2_text = (
            '<p><a href="resolveuid/%s" class="internal">Link to doc 1'
            '</a></p>') % doc1.UID()
        cf1.invokeFactory("Document", "doc2", Title="Doc 2", text=doc2_text)
        doc2 = cf1["doc2"]
        # I'm not sure what layer of Plone code adds these
        doc2.addReference(doc1, 'isReferencing', updateReferences=True)
        self.assertEquals(
            len(doc2._getReferenceAnnotations().objectItems()), 1)

        self.run_migration_step()

        cf1 = portal.cf1
        doc2 = cf1["doc2"]
        self.assertEquals(
            len(doc2._getReferenceAnnotations().objectItems()), 1)
Exemplo n.º 11
0
def get_top_site_from_url(context, request):
    """Find the top-most site, which is still in the url path.

    If the current context is within a subsite within a PloneSiteRoot and no
    virtual hosting is in place, the PloneSiteRoot is returned.
    When at the same context but in a virtual hosting environment with the
    virtual host root pointing to the subsites, it returns the subsite instead
    of the PloneSiteRoot.

    For this given content structure:

    /Plone/Subsite

    It should return the following in these cases:

    - Naked Plone without virtual hosting, /Plone: Plone
    - Naked Plone without virtual hosting, /Plone/Subsite: Plone
    - Virtual hosting which roots to the subsite: Subsite
    """
    url_path = urlparse(context.absolute_url()).path.split('/')

    site = getSite()
    for idx in range(len(url_path)):
        _path = '/'.join(url_path[:idx + 1]) or '/'
        site_path = request.physicalPathFromURL(_path)
        site = context.restrictedTraverse('/'.join(site_path) or '/')
        if ISite.providedBy(site):
            break
    return site
Exemplo n.º 12
0
async def do_traverse(request, parent, path):
    """Traverse for the code API."""
    if not path:
        return parent, path

    assert request is not None  # could be used for permissions, etc

    if ISite.providedBy(parent) and \
       path[0] != request._db_id:
        # Tried to access a site outsite the request
        raise HTTPUnauthorized()

    if IApplication.providedBy(parent) and \
       path[0] != request._site_id:
        # Tried to access a site outsite the request
        raise HTTPUnauthorized()

    try:
        if path[0].startswith('_'):
            raise HTTPUnauthorized()
        context = parent[path[0]]
    except TypeError:
        return parent, path
    except KeyError:
        return parent, path

    context._v_parent = parent

    return await traverse(request, context, path[1:])
Exemplo n.º 13
0
def setUp(self):
    """Test setUp based on z3c.form.testing.setUp minus their globals.
    """
    from zope.component.testing import setUp
    setUp()
    from zope.container.testing import setUp
    setUp()
    from zope.component import hooks
    hooks.setHooks()
    from zope.traversing.testing import setUp
    setUp()

    from zope.publisher.browser import BrowserLanguages
    from zope.publisher.interfaces.http import IHTTPRequest
    from zope.i18n.interfaces import IUserPreferredLanguages
    import zope.component
    zope.component.provideAdapter(BrowserLanguages, [IHTTPRequest],
                                  IUserPreferredLanguages)

    from zope.site.folder import rootFolder
    site = rootFolder()
    from zope.site.site import LocalSiteManager
    from zope.component.interfaces import ISite
    if not ISite.providedBy(site):
        site.setSiteManager(LocalSiteManager(site))
    hooks.setSite(site)
Exemplo n.º 14
0
    def __init__(self, context):
        permissions = [MANAGE_TEAMPLETS_PERMISSION]
        super(ShopPortletMailTemplatesLink, self).__init__(
            context, view_permissions=permissions)

        # Find the nearest context, where this functionality can be bound to.
        def _find_context(ctx):
            return ctx\
                if ISite.providedBy(ctx) or IVendor.providedBy(ctx)\
                else _find_context(aq_parent(ctx))
        context = _find_context(context)

        if IPloneSiteRoot.providedBy(context):
            self.title = _(
                'mailtemplates_global',
                default=u'Notification Templates (global)'
            )
        elif ISite.providedBy(context):
            self.title = _(
                'mailtemplates_site',
                default=u'Notification Templates (site-wide)'
            )
        elif IVendor.providedBy(context):
            self.title = _(
                'mailtemplates_vendor',
                default=u'Notification Templates (vendor specific)'
            )

        self.url = '%s/@@mailtemplates' % context.absolute_url()
        self.order = 50
        self.cssclass = 'mailtemplates'
Exemplo n.º 15
0
def get_top_site_from_url(context, request):
    """Find the top-most site, which is still in the url path.

    If the current context is within a subsite within a PloneSiteRoot and no
    virtual hosting is in place, the PloneSiteRoot is returned.
    When at the same context but in a virtual hosting environment with the
    virtual host root pointing to the subsites, it returns the subsite instead
    of the PloneSiteRoot.

    For this given content structure:

    /Plone/Subsite

    It should return the following in these cases:

    - Naked Plone without virtual hosting, /Plone: Plone
    - Naked Plone without virtual hosting, /Plone/Subsite: Plone
    - Virtual hosting which roots to the subsite: Subsite
    """
    url_path = urlparse(context.absolute_url()).path.split('/')

    site = getSite()
    for idx in range(len(url_path)):
        _path = '/'.join(url_path[:idx + 1]) or '/'
        site_path = request.physicalPathFromURL(_path)
        site = context.restrictedTraverse('/'.join(site_path) or '/')
        if ISite.providedBy(site):
            break
    return site
Exemplo n.º 16
0
    def __init__(self, context):
        permissions = [VIEW_ORDERS_PERMISSION]
        super(ShopPortletOrdersLink, self).__init__(
            context, view_permissions=permissions)
        # check if authenticated user is vendor
        if self.display and not get_vendors_for():
            self.display = False

        # Find the nearest context, where this functionality can be bound to.
        def _find_context(ctx):
            return ctx\
                if ISite.providedBy(ctx) or IVendor.providedBy(ctx)\
                else _find_context(aq_parent(ctx))
        context = _find_context(context)

        if IPloneSiteRoot.providedBy(context):
            self.title = _(
                'orders_global',
                default=u'Orders (global)'
            )
        elif ISite.providedBy(context):
            self.title = _(
                'orders_site',
                default=u'Orders (site-wide)'
            )
        elif IVendor.providedBy(context):
            self.title = _(
                'orders_vendor',
                default=u'Orders (vendor specific)'
            )

        self.url = '%s/@@orders' % context.absolute_url()
        self.order = 10
        self.cssclass = 'orders'
Exemplo n.º 17
0
    def __init__(self, context):
        permissions = [MANAGE_SHOP_PERMISSION]
        super(ShopPortletControlpanelLink, self).__init__(
            context, view_permissions=permissions)

        # Find the nearest context, where this functionality can be bound to.
        def _find_context(ctx):
            return ctx\
                if ISite.providedBy(ctx)\
                else _find_context(aq_parent(ctx))
        context = _find_context(context)

        if IPloneSiteRoot.providedBy(context):
            self.title = _(
                'shop_controlpanel_global',
                default=u'Shop Controlpanel (global)'
            )
        elif ISite.providedBy(context):
            self.title = _(
                'shop_controlpanel_site',
                default=u'Shop Controlpanel (site-wide)'
            )

        self.url = '%s/@@shop_controlpanel' % context.absolute_url()
        self.order = 50
        self.cssclass = 'controlpanel'
Exemplo n.º 18
0
def enableFolder(folder):
    zope.event.notify(ChildSiteWillBeCreatedEvent(folder))
    if not ISite.providedBy(folder):
        make_objectmanager_site(folder)
    # reindex so that the object_provides index is aware of our
    # new interface
    reindexObjectProvides(folder)
    zope.event.notify(ChildSiteCreatedEvent(folder))
Exemplo n.º 19
0
 def __init__(self, context):
     permissions = [MANAGE_DISCOUNT_PERMISSION]
     super(ShopPortletCartDiscountLink, self).__init__(context, view_permissions=permissions)
     if self.display:
         self.display = ISite.providedBy(context)
     self.url = "%s/@@cart_discount" % context.absolute_url()
     self.title = _("cart_discount", default=u"Cart Discount")
     self.order = 60
     self.cssclass = "cart_discount"
Exemplo n.º 20
0
 def __init__(self, context):
     permissions = [MANAGE_DISCOUNT_PERMISSION]
     super(ShopPortletCartItemDiscountLink, self).__init__(context, view_permissions=permissions)
     if self.display:
         self.display = ISite.providedBy(context) or IDiscountSettingsEnabled.providedBy(context)
     self.url = "%s/@@item_discount" % context.absolute_url()
     self.title = _("item_discount", default=u"Item Discount")
     self.order = 70
     self.cssclass = "item_discount"
Exemplo n.º 21
0
 def test_component_registry(self):
     portal = self.layer['portal']
     z2.login(portal['acl_users'], 'contributor')
     portal.invokeFactory('Folder', 'site1')
     zope.component.provideUtility(engine.Subtyper())
     subtyper = zope.component.getUtility(interfaces.ISubtyper)
     subtyper.change_type(
         portal.site1,
         u'collective.lineage.childsite')
     self.failUnless(ISite.providedBy(portal.site1))
Exemplo n.º 22
0
    def bootstrapSchoolTool(self, db):
        """Bootstrap SchoolTool database."""
        connection = db.open()
        root = connection.root()
        app_obj = root.get(ZopePublication.root_name)
        if app_obj is None:
            app = SchoolToolApplication()

            # Run school specific initialization code
            initializationUtility = getUtility(
                ISchoolToolInitializationUtility)
            initializationUtility.initializeApplication(app)

            directlyProvides(app, directlyProvidedBy(app) + IContainmentRoot)
            root[ZopePublication.root_name] = app
            # savepoint to make sure that the app object has
            # a _p_jar. This is needed to make things like
            # KeyReference work, which in turn is needed to
            # make the catalog work. We make this savepoint
            # optimistic because it will then work with any registered
            # data managers that do not support this feature.
            transaction.savepoint(optimistic=True)

            # set up the site so that local utility setups and catalog
            # indexing would work properly
            if not ISite.providedBy(app):
                app.setSiteManager(LocalSiteManager(app))

            setSite(app)

            # We must set up the int ids utility before setting up any
            # of the plugin specific catalogs, as catalogs rely on
            # IntIds being present
            setUpUtilities(app, [UtilitySpecification(IntIds, IIntIds)])

            # tell plugins to initialize their catalogs, must be done
            # before initializing plugins themselves or else all the
            # initial groups, persons, resources will not get indexed
            notify(CatalogSetUpEvent(app))
            notify(CatalogStartUpEvent(app))

            # initialize plugins themselves
            notify(ApplicationInitializationEvent(app))

            notify(ObjectAddedEvent(app))

            # unset the site so we would not confuse other
            # bootstraping code
            setSite(None)

            self.restoreManagerUser(app, MANAGER_PASSWORD)
            self.initializePreferences(app)
        transaction.commit()
        connection.close()
Exemplo n.º 23
0
    def setUp(self):
        self.portal = portal = self.layer['portal']
        setRoles(self.portal, TEST_USER_ID, ['Manager'])

        portal.invokeFactory('Folder', 'newsite')
        portal.newsite.invokeFactory('Folder', 'subfolder')
        portal.invokeFactory('Folder', 'subfolder2')
        portal.subfolder2.invokeFactory('Folder', 'subfolder3')

        directlyProvides(portal.newsite, ISite)
        self.assertTrue(ISite.providedBy(portal.newsite))
Exemplo n.º 24
0
def find_next_sitemanager(site):
    """Find the closest sitemanager that is not the specified site's
    sitemanager.
    """
    while True:
        site = get_parent(site, default=None)
        if site is None:
            return None

        if ISite.providedBy(site):
            return site.getSiteManager()
Exemplo n.º 25
0
def _extend_destaques(portal):
    folder = portal['destaques']
    if not ISite.providedBy(folder):
        make_objectmanager_site(folder)
    sm = folder.getSiteManager()
    sm.registerAdapter(
        DestaquesExtender,
        (IATNewsItem,),
        ISchemaModifier,
        name=u'DestaqueExtended'
    )
Exemplo n.º 26
0
def find_next_sitemanager(site):
    """Find the closest sitemanager that is not the specified site's
    sitemanager.
    """
    while True:
        site = get_parent(site, default=None)
        if site is None:
            return None

        if ISite.providedBy(site):
            return site.getSiteManager()
Exemplo n.º 27
0
    def bootstrapSchoolTool(self, db):
        """Bootstrap SchoolTool database."""
        connection = db.open()
        root = connection.root()
        app_obj = root.get(ZopePublication.root_name)
        if app_obj is None:
            app = SchoolToolApplication()

            # Run school specific initialization code
            initializationUtility = getUtility(
                ISchoolToolInitializationUtility)
            initializationUtility.initializeApplication(app)

            directlyProvides(app, directlyProvidedBy(app) + IContainmentRoot)
            root[ZopePublication.root_name] = app
            # savepoint to make sure that the app object has
            # a _p_jar. This is needed to make things like
            # KeyReference work, which in turn is needed to
            # make the catalog work. We make this savepoint
            # optimistic because it will then work with any registered
            # data managers that do not support this feature.
            transaction.savepoint(optimistic=True)

            # set up the site so that local utility setups and catalog
            # indexing would work properly
            if not ISite.providedBy(app):
                app.setSiteManager(LocalSiteManager(app))

            setSite(app)

            # We must set up the int ids utility before setting up any
            # of the plugin specific catalogs, as catalogs rely on
            # IntIds being present
            setUpUtilities(app, [UtilitySpecification(IntIds, IIntIds)])

            # tell plugins to initialize their catalogs, must be done
            # before initializing plugins themselves or else all the
            # initial groups, persons, resources will not get indexed
            notify(CatalogSetUpEvent(app))
            notify(CatalogStartUpEvent(app))

            # initialize plugins themselves
            notify(ApplicationInitializationEvent(app))

            notify(ObjectAddedEvent(app))

            # unset the site so we would not confuse other
            # bootstraping code
            setSite(None)

            self.restoreManagerUser(app, MANAGER_PASSWORD)
            self.initializePreferences(app)
        transaction.commit()
        connection.close()
Exemplo n.º 28
0
    def setUp(self):
        self.portal = portal = self.layer["portal"]
        setRoles(self.portal, TEST_USER_ID, ["Manager"])

        portal.invokeFactory("Folder", "newsite")
        portal.newsite.invokeFactory("Folder", "subfolder")
        portal.invokeFactory("Folder", "subfolder2")
        portal.subfolder2.invokeFactory("Folder", "subfolder3")

        directlyProvides(portal.newsite, ISite)
        self.assertTrue(ISite.providedBy(portal.newsite))
def enable_childsite(context):
    notify(ChildSiteWillBeCreatedEvent(context))

    # enable site
    if not ISite.providedBy(context):
        make_objectmanager_site(context)

    # provide IChildSite
    alsoProvides(context, IChildSite)

    context.reindexObject(idxs=('object_provides'))
    notify(ChildSiteCreatedEvent(context))
Exemplo n.º 30
0
def acquire_vendor_or_shop_root(context):
    """Returns the acquired vendor or the main shop by traversing up the
    content tree, starting from a context.

    :param context: The context to start searching for the nearest vendor.
    :type context: Content object
    :returns: The vendor, a shop item is belonging to.
    :rtype: Content object
    """
    while not IVendor.providedBy(context) and not ISite.providedBy(context):
        context = aq_parent(aq_inner(context))
    return context
Exemplo n.º 31
0
    def _maybePlacefullyAuthenticate(self, request, ob):
        if not IUnauthenticatedPrincipal.providedBy(request.principal):
            # We've already got an authenticated user. There's nothing to do.
            # Note that beforeTraversal guarentees that user is not None.
            return

        if not ISite.providedBy(ob):
            # We won't find an authentication utility here, so give up.
            return

        sm = removeSecurityProxy(ob).getSiteManager()
        self.authenticate(request, sm)
Exemplo n.º 32
0
def enable_childsite(context):
    notify(ChildSiteWillBeCreatedEvent(context))

    # enable site
    if not ISite.providedBy(context):
        make_objectmanager_site(context)

    # provide IChildSite
    alsoProvides(context, IChildSite)

    context.reindexObject(idxs=('object_provides'))
    notify(ChildSiteCreatedEvent(context))
Exemplo n.º 33
0
 def create_indices(self):
     """
     will create all non existent indices in database
     """
     sitem = zapi.getSiteManager(self)
     site = zapi.getParent(sitem)
     tmpEvent = TmpEvent()
     if IZopeSite.providedBy(site) or \
         IIctSite.providedBy(site) or \
         zapi.getParent(site) is None:
         tmpEvent.object = site
         createLocalUtils(tmpEvent)
Exemplo n.º 34
0
 def create_app(db):
     conn = db.open()
     try:
         root = conn.root()
         if not name in root:
             with transaction_manager:
                 app = root[name] = model()
                 if (not ISite.providedBy(app) and
                         IPossibleSite.providedBy(app)):
                     LocalSiteManager(app)
                 notify(events.ApplicationInitializedEvent(app))
     finally:
         conn.close()
Exemplo n.º 35
0
 def __init__(self, context, request):
     # acquire desired context
     interfaces = [IBuyable, IFolder, ISite]
     context = self.acquire_context(context, interfaces=interfaces)
     # call super class constructor
     super(CartItemDiscountLink, self).__init__(context, request)
     # check whether context is site or discount settings are enabled on
     # context
     if self.display:
         self.display = ISite.providedBy(context) \
             or IDiscountSettingsEnabled.providedBy(context)
     # set target URL
     self.url = '{}/@@item_discount'.format(context.absolute_url())
Exemplo n.º 36
0
 def create_app(db):
     conn = db.open()
     try:
         root = conn.root()
         if not name in root:
             with transaction_manager:
                 app = root[name] = model()
                 if (not ISite.providedBy(app)
                         and IPossibleSite.providedBy(app)):
                     LocalSiteManager(app)
                 notify(events.ApplicationInitializedEvent(app))
     finally:
         conn.close()
Exemplo n.º 37
0
 def __init__(self, context, request):
     # acquire desired context
     interfaces = [IBuyable, IFolder, ISite]
     context = self.acquire_context(context, interfaces=interfaces)
     # call super class constructor
     super(CartItemDiscountLink, self).__init__(context, request)
     # check whether context is site or discount settings are enabled on
     # context
     if self.display:
         self.display = ISite.providedBy(
             context) or IDiscountSettingsEnabled.providedBy(context)
     # set target URL
     self.url = "{}/@@item_discount".format(context.absolute_url())
Exemplo n.º 38
0
 def __init__(self, context, request):
     # acquire desired context
     context = self.acquire_context(context, interfaces=[ISite])
     # call super class constructor
     super(ControlPanelLink, self).__init__(context, request)
     # set title by context interface
     if IPloneSiteRoot.providedBy(context):
         self.title = _("shop_controlpanel_global",
                        default=u"Shop Controlpanel (global)")
     elif ISite.providedBy(context):
         self.title = _("shop_controlpanel_site",
                        default=u"Shop Controlpanel (site-wide)")
     # set target URL
     self.url = "{}/@@shop_controlpanel".format(context.absolute_url())
Exemplo n.º 39
0
def enableChildRegistry(context, event):
    """
    """
    if not ISite.providedBy(context):
        make_objectmanager_site(context)
    # reindex so that the object_provides index is aware of our
    # new interface
    catalog = getToolByName(context, 'portal_catalog')
    catalog.reindexObject(context, idxs=['object_provides'])
    sm = getSiteManager(context=context)
    if REGISTRY_NAME not in context.objectIds():
        context[REGISTRY_NAME] = LocalRegistry(REGISTRY_NAME).__of__(context)
    sm.registerUtility(component=context[REGISTRY_NAME], provided=IRegistry)
    zope.event.notify(LocalRegistryCreatedEvent(context))
Exemplo n.º 40
0
def get_site(conn, name):
    """Get a site in a database.

    it simply fetch object under key 'name' at the root.

    :param conn: the ZODB connection
    :param name: name of the site
    :raises KeyError: the site does not exist
    :raises TypeError: the object is not an ISite
    """
    root = conn.root()
    site = root[name]
    if not ISite.providedBy(site):
        raise TypeError("Site %r does not exist in the current ZODB." % name)
    return site
Exemplo n.º 41
0
def make_site(obj, iface=ISite):
    """Give the specified object required qualities to identify it as a proper
    ISite.
    """
    if ISite.providedBy(obj):
        raise ValueError('This is already a site')

    next = find_next_sitemanager(obj)
    if next is None:
        next = base

    enableSite(obj, iface=iface)

    components = PersistentComponents('++etc++site', bases=(next,))
    obj.setSiteManager(components)
    components.__parent__ = aq_base(obj)
Exemplo n.º 42
0
def make_site(obj, iface=ISite):
    """Give the specified object required qualities to identify it as a proper
    ISite.
    """
    if ISite.providedBy(obj):
        raise ValueError('This is already a site')

    next = find_next_sitemanager(obj)
    if next is None:
        next = base

    enableSite(obj, iface=iface)

    components = PersistentComponents('++etc++site', bases=(next, ))
    obj.setSiteManager(components)
    components.__parent__ = aq_base(obj)
def enableChildRegistry(context, event):
    """
    """
    if not ISite.providedBy(context):
        make_objectmanager_site(context)
    # reindex so that the object_provides index is aware of our
    # new interface
    catalog = getToolByName(context, 'portal_catalog')
    catalog.reindexObject(
        context,
        idxs=['object_provides']
    )
    sm = getSiteManager(context=context)
    if REGISTRY_NAME not in context.objectIds():
        context[REGISTRY_NAME] = LocalRegistry(REGISTRY_NAME).__of__(context)
    sm.registerUtility(component=context[REGISTRY_NAME], provided=IRegistry)
    zope.event.notify(LocalRegistryCreatedEvent(context))
Exemplo n.º 44
0
 def __init__(self, context, request):
     # acquire desired context
     context = self.acquire_context(context, interfaces=[IVendor, ISite])
     # call super class constructor
     super(MailTemplatesLink, self).__init__(context, request)
     # set title by context interface
     if IPloneSiteRoot.providedBy(context):
         self.title = _('mailtemplates_global',
                        default=u'Notification Templates (global)')
     elif ISite.providedBy(context):
         self.title = _('mailtemplates_site',
                        default=u'Notification Templates (site-wide)')
     elif IVendor.providedBy(context):
         self.title = _('mailtemplates_vendor',
                        default=u'Notification Templates (vendor specific)')
     # set target URL
     self.url = '{}/@@mailtemplates'.format(context.absolute_url())
Exemplo n.º 45
0
    def enable(self):
        """Enable a lineage subsite on this context.
        """
        ctx = self.context
        notify(ChildSiteWillBeCreatedEvent(ctx))

        # enable site
        if not ISite.providedBy(ctx):
            make_objectmanager_site(ctx)

        # provide IChildSite
        alsoProvides(ctx, IChildSite)

        ctx.reindexObject(idxs=('object_provides'))
        notify(ChildSiteCreatedEvent(ctx))

        # redirect
        self.request.response.redirect(ctx.absolute_url())
Exemplo n.º 46
0
 def __init__(self, context, request):
     # acquire desired context
     context = self.acquire_context(context, interfaces=[ISite])
     # call super class constructor
     super(ControlPanelLink, self).__init__(context, request)
     # set title by context interface
     if IPloneSiteRoot.providedBy(context):
         self.title = _(
             'shop_controlpanel_global',
             default=u'Shop Controlpanel (global)'
         )
     elif ISite.providedBy(context):
         self.title = _(
             'shop_controlpanel_site',
             default=u'Shop Controlpanel (site-wide)'
         )
     # set target URL
     self.url = '{}/@@shop_controlpanel'.format(context.absolute_url())
Exemplo n.º 47
0
 def __init__(self, context, request):
     # acquire desired context
     context = self.acquire_context(context, interfaces=[IVendor, ISite])
     # call super class constructor
     super(BookingsLink, self).__init__(context, request)
     # check if authenticated user is vendor
     if self.display and not get_vendors_for():
         self.display = False
         return
     # set title by context interface
     if IPloneSiteRoot.providedBy(context):
         self.title = _("bookings_global", default=u"Bookings (global)")
     elif ISite.providedBy(context):
         self.title = _("bookings_site", default=u"Bookings (site-wide)")
     elif IVendor.providedBy(context):
         self.title = _("bookings_vendor",
                        default=u"Bookings (vendor specific)")
     # set target URL
     self.url = "{}/@@bookings".format(context.absolute_url())
Exemplo n.º 48
0
    def rules(self, portal_type=None):
        """Return rules to apply, most outer first.

        Aggregate rules through hierarchy until Plone root is reached.

        Container objects get ignored if ``IDiscountSettingsEnabled`` not
        provided.

        For each context only the first found rule from lookup chain is
        considered.

        Stops hierarchical lookup if found rule for context sets it's ``block``
        flag.
        """
        rules = list()
        context = self.context
        # traverse down at most until plone root
        while True:
            # ignore context if no discount settings enabled or no site
            if not (IDiscountSettingsEnabled.providedBy(context)
                    or ISite.providedBy(context)):
                context = aq_parent(aq_inner(context))
                continue
            rule = None
            # iterate lookup chain, break on first rule found
            for lookup in self.lookup_chain(context):
                rule = lookup.lookup(portal_type=portal_type)
                if rule:
                    break
            # add rule if found
            if rule:
                rules.append(rule)
                # break aggregating if defined
                if rule.attrs['block']:
                    break
            # plone root reached
            if IPloneSiteRoot.providedBy(context):
                break
            context = aq_parent(aq_inner(context))
        # aggregated rules are applied most outer first
        return reversed(rules)
Exemplo n.º 49
0
 def __init__(self, context, request):
     # acquire desired context
     interfaces = [IBuyable, IFolder, ISite]
     context = self.acquire_context(context, interfaces=interfaces)
     # skip link if context is site
     if self.context_provides(context, interfaces=[ISite]):
         self.display = False
         return
     # call super class constructor
     super(ExportOrdersInContext, self).__init__(context, request)
     # do not display on site
     if self.display and ISite.providedBy(context):
         self.display = False
         return
     # check if buyables in context
     if self.display and not self.buyables_in_context(context):
         self.display = False
         return
     # set target URL
     self.url = "{}/@@exportorders_contextual".format(
         context.absolute_url())
Exemplo n.º 50
0
def get_top_site_from_url(context, request):
    """Find the top-most site, which is still in the url path.

    If the current context is within a subsite within a PloneSiteRoot and no
    virtual hosting is in place, the PloneSiteRoot is returned.
    When at the same context but in a virtual hosting environment with the
    virtual host root pointing to the subsite, it returns the subsite instead
    the PloneSiteRoot.

    For this given content structure:

    /Plone/Subsite

    It should return the following in these cases:

    - No virtual hosting, URL path: /Plone, Returns: Plone Site
    - No virtual hosting, URL path: /Plone/Subsite, Returns: Plone
    - Virtual hosting roots to Subsite, URL path: /, Returns: Subsite
    """
    site = getSite()
    try:
        url_path = urlparse(context.absolute_url()).path.split('/')
        for idx in range(len(url_path)):
            _path = '/'.join(url_path[:idx + 1]) or '/'
            site_path = request.physicalPathFromURL(_path)
            if six.PY2:
                site_path = safe_encode('/'.join(site_path)) or '/'
            else:
                site_path = '/'.join(site_path) or '/'
            _site = context.restrictedTraverse(site_path)
            if ISite.providedBy(_site):
                break
        if _site:
            site = _site
    except (ValueError, AttributeError):
        # On error, just return getSite.
        # Refs: https://github.com/plone/plone.app.content/issues/103
        # Also, TestRequest doesn't have physicalPathFromURL
        pass
    return site
Exemplo n.º 51
0
async def traverse(request, parent, path):
    """Do not use outside the main router function."""
    if IApplication.providedBy(parent):
        request.application = parent

    if not path:
        return parent, path

    assert request is not None  # could be used for permissions, etc

    try:
        if path[0].startswith('_'):
            raise HTTPUnauthorized()
        context = parent[path[0]]
    except TypeError:
        return parent, path
    except KeyError:
        return parent, path

    if IDatabase.providedBy(context):
        if SHARED_CONNECTION:
            request.conn = context.conn
        else:
            # Create a new conection
            request.conn = context.open()
        # Check the transaction
        request._db_write_enabled = False
        request._db_id = context.id
        context = request.conn.root()

    if ISite.providedBy(context):
        request._site_id = context.id
        request.site = context
        request.site_settings = context['_registry']
        layers = request.site_settings.get(ACTIVE_LAYERS_KEY, [])
        for layer in layers:
            alsoProvides(request, import_class(layer))

    return await traverse(request, context, path[1:])
Exemplo n.º 52
0
def setUpLocalAuth(site, auth=None):
    """Set up local authentication for SchoolTool.

    Creates a site management folder in a site and sets up local
    authentication.
    """

    if auth is None:
        auth = SchoolToolAuthenticationUtility()

    if not ISite.providedBy(site):
        site.setSiteManager(LocalSiteManager(site))

    # go to the site management folder
    default = traverse(site, '++etc++site/default')
    # if we already have the auth utility registered, we're done
    if 'SchoolToolAuth' in default:
        return
    # otherwise add it and register it
    default['SchoolToolAuth'] = auth
    manager = site.getSiteManager()
    manager.registerUtility(auth, IAuthentication)
Exemplo n.º 53
0
 def rules(self):
     # return rules to apply, most outer first
     rules = list()
     context = self.context
     while True:
         if not (IDiscountSettingsEnabled.providedBy(context)
                 or ISite.providedBy(context)):
             context = aq_parent(aq_inner(context))
             continue
         rule = None
         for lookup in self.lookup_cascade(context):
             rule = lookup.lookup()
             if rule:
                 break
         if rule:
             rules.append(rule)
             if rule.attrs['block']:
                 break
         if IPloneSiteRoot.providedBy(context):
             break
         context = aq_parent(aq_inner(context))
     return reversed(rules)
Exemplo n.º 54
0
 def get(self, key, default=None):
     if key == '++etc++site' and ISite.providedBy(self.context):
         return self.context.getSiteManager()
     return self.context.get(key, default)
Exemplo n.º 55
0
 def _acquire_site(context):
     if ISite.providedBy(context):
         return context
     return _acquire_site(aq_parent(context))
Exemplo n.º 56
0
 def __len__(self):
     l = len(self.context)
     if ISite.providedBy(self.context):
         l += 1
     return l
Exemplo n.º 57
0
 def keys(self):
     keys = self.context.keys()
     if ISite.providedBy(self.context):
         return list(keys) + ['++etc++site']
     return keys