Esempio n. 1
0
def zope_root():
    this = getSite()

    while not IApplication.providedBy(this):
        this = this.aq_inner.aq_parent

    return this
Esempio n. 2
0
def zope_root():
    this = getSite()

    while not IApplication.providedBy(this):
        this = this.aq_inner.aq_parent

    return this
Esempio n. 3
0
    def __call__(self):
        mship = getToolByName(self.context, 'portal_membership')
        current_auth = mship.getAuthenticatedMember()
        if IApplication.providedBy(aq_parent(aq_parent(
                current_auth.getUser()))):
            IStatusMessage(self.request).addStatusMessage(_(
                u"Unfortunately it is not possible to send messages using your user account. Please use a Plone user rather than a Zope user."
            ),
                                                          type='error')
            return self.request.response.redirect(self.context.absolute_url())

        self.request.set('disable_border', True)

        self.form_fields.get('receiver').field.default = None
        self.form_fields.get('receiver').field.readonly = False
        self.form_fields.get('subject').field.default = None
        self.form_fields.get('message').field.default = None

        if self.request.get('receiver', None) is not None:
            self.form_fields.get('receiver').field.default = self.request.get(
                'receiver', None)

        if self.request.get('subject', None) is not None:
            self.form_fields.get('subject').field.default = self.request.get(
                'subject', None).decode('utf-8')

        return super(NewMessageForm, self).__call__()
Esempio n. 4
0
    def getPhysicalPath(self):
        # Get the physical path of the object.
        #
        # We need to override this because the new Zope implementations
        # uses self.id instead of self.getId, which make a big difference in our case
        id = self.getId()

        path = (id, )
        p = aq_parent(aq_inner(self))
        if p is None:
            return path

        func = self.getPhysicalPath.__func__
        while p is not None:
            if func is p.getPhysicalPath.__func__:
                pid = p.getId()
                path = (pid, ) + path
                p = aq_parent(aq_inner(p))
            else:
                if IApplication.providedBy(p):
                    path = ("", ) + path
                else:
                    path = p.getPhysicalPath() + path
                break

        return path
Esempio n. 5
0
    def _check(self):
        registered = self._registered_objects()
        if len(registered) > 0 and \
                not IDisableCSRFProtection.providedBy(self.request):
            # Okay, we're writing here, we need to protect!
            try:
                check(self.request)
                return True
            except ComponentLookupError:
                # okay, it's possible we're at the zope root and the KeyManager
                # hasn't been installed yet. Let's check and carry on
                # if this is the case
                if IApplication.providedBy(self.getContext()):
                    LOGGER.info('skipping csrf protection on zope root until '
                                'keymanager gets installed')
                    return True
                raise
            except Forbidden:
                if self.request.REQUEST_METHOD != 'GET':
                    # only try to be "smart" with GET requests
                    raise

                # XXX
                # okay, so right now, we're going to check if the current
                # registered objects to write, are just portlet assignments.
                # I don't know why, but when a site is created, these
                # cause some writes on read. ALL, registered objects
                # need to be portlet assignments. XXX needs to be fixed
                # somehow...
                safe = True
                for obj in registered:
                    if (not IPortletAssignment.providedBy(obj) and
                            not getattr(obj, '_v_safe_write', False)):
                        safe = False
                        break
                if not safe:
                    LOGGER.info('aborting transaction due to no CSRF '
                                'protection on url %s' % self.request.URL)
                    transaction.abort()

                    # conditions for doing the confirm form are:
                    #   1. 301, 302 response code
                    #   2. text/html response
                    #   3. getSite could be none, zope root maybe, carry on
                    # otherwise,
                    #   just abort with a log entry because we tried to
                    #   write on read, without a POST request and we don't
                    #   know what to do with it gracefully.
                    resp = self.request.response
                    ct = resp.headers.get('content-type')
                    if self.site and (
                            resp.status in (301, 302) or 'text/html' in ct):
                        data = self.request.form.copy()
                        data['original_url'] = self.request.URL
                        resp.redirect('%s/@@confirm-action?%s' % (
                            self.site.absolute_url(),
                            urlencode(data)
                        ))
                        return False
        return True
Esempio n. 6
0
    def _check(self):
        registered = self._registered_objects()
        if len(registered) > 0 and \
                not IDisableCSRFProtection.providedBy(self.request):
            # Okay, we're writing here, we need to protect!
            try:
                check(self.request)
                return True
            except ComponentLookupError:
                # okay, it's possible we're at the zope root and the KeyManager
                # hasn't been installed yet. Let's check and carry on
                # if this is the case
                if IApplication.providedBy(self.getContext()):
                    LOGGER.info('skipping csrf protection on zope root until '
                                'keymanager gets installed')
                    return True
                raise
            except Forbidden:
                if self.request.REQUEST_METHOD != 'GET':
                    # only try to be "smart" with GET requests
                    raise

                # XXX
                # okay, so right now, we're going to check if the current
                # registered objects to write, are just portlet assignments.
                # I don't know why, but when a site is created, these
                # cause some writes on read. ALL, registered objects
                # need to be portlet assignments. XXX needs to be fixed
                # somehow...
                safe = True
                for obj in registered:
                    if (not IPortletAssignment.providedBy(obj)
                            and not getattr(obj, '_v_safe_write', False)):
                        safe = False
                        break
                if not safe:
                    LOGGER.info('aborting transaction due to no CSRF '
                                'protection on url %s' % self.request.URL)
                    transaction.abort()

                    # conditions for doing the confirm form are:
                    #   1. 301, 302 response code
                    #   2. text/html response
                    #   3. getSite could be none, zope root maybe, carry on
                    # otherwise,
                    #   just abort with a log entry because we tried to
                    #   write on read, without a POST request and we don't
                    #   know what to do with it gracefully.
                    resp = self.request.response
                    ct = resp.headers.get('content-type')
                    if self.site and (resp.status in (301, 302)
                                      or 'text/html' in ct):
                        data = self.request.form.copy()
                        data['original_url'] = self.request.URL
                        resp.redirect(
                            '%s/@@confirm-action?%s' %
                            (self.site.absolute_url(), urlencode(data)))
                        return False
        return True
Esempio n. 7
0
 def _getParentDocument(self, context):
     """Return the parent document (in case of comments)"""
     while True:
         if IBaseContent.providedBy(context):
             return context
         if IApplication.providedBy(context):
             return None
         context = aq_parent(context)
Esempio n. 8
0
 def _getParentRoom(self, context):
     while True:
         if IGroupRoom.providedBy(context):
             break
         context = aq_parent(aq_inner(context))
         if IApplication.providedBy(context):
             return None
     return context
Esempio n. 9
0
def get_system_upgrade_user(context):
    while not IApplication.providedBy(context):
        context = aq_parent(aq_inner(context))

    acl_users = context.acl_users
    if not acl_users.getUserById('system-upgrade'):
        acl_users.userFolderAddUser(
            'system-upgrade', os.urandom(16).encode('hex'), ['Manager'], None)
    return acl_users.getUserById('system-upgrade')
Esempio n. 10
0
 def get_role_adapter(self):
     site = getSite()
     request = site.REQUEST
     context = request.PARENTS[0]
     if IApplication.providedBy(context):
         context = site
     return getMultiAdapter((context, request),
                            IDynamicRoleAdapter,
                            name=self.plonerole)
Esempio n. 11
0
    def intercept(self):
        """ Manage redirects to mobile site.

        @return: True if redirect has been made
        """

        # XXX: Enable this later
        # Abort if gomobile.mobile is not installed
        # - detect by browserlayers.xml
        # if not IGoMobileInstalled.providedBy(self.request):
        #    return False

        # This is needed for templates without views
        context = self.getRealContext()
        if context is None:
            return False

        try:
            getMultiAdapter((context, self.request), IMobileSiteLocationManager)
        except:
            # XXX: gomobile.mobile is not installed.  Should check for
            # IGoMobileInstalled interface, but support is not yet
            # enabled - see intercept()
            return False

        if IApplication.providedBy(context):
            # Do not intercept requests going to the Zope management
            # interface root (one level above Plone sites).
            # Actually, this is not working, as the context is usually
            # <DTMLMethod at /index_html> in that case.
            return False

        discriminator = getUtility(IMobileRequestDiscriminator)
        modes = discriminator.discriminate(context, self.request)

        # Note: just in case redirect logged in users too
        # This might be little stupid and needs to changed later
        is_web = MobileRequestType.WEB in modes

        # print "Sniffed: " + str(self.isSniffedMobile())
        # print "Is web:" + str(is_web)
        # print "ModeS:" + str(modes)

        if self.isSniffedMobile() and is_web:

            # Check taht if we are asked to stay on the web site
            if self.isMobileWantsWeb():
                self.forceWeb()
                return False
            elif self.isCookiedWeb():
                return False
            else:
                return bool(self.redirect())

        else:
            # A web browser
            return False
Esempio n. 12
0
 def get_role_adapter(self):
     site = getSite()
     request = site.REQUEST
     context = request.PARENTS[0]
     if IApplication.providedBy(context):
         context = site
     return getMultiAdapter((context, request),
                            IDynamicRoleAdapter,
                            name=self.plonerole)
Esempio n. 13
0
def getRootKeyManager(root):
    if not IApplication.providedBy(root):
        return
    try:
        manager = root._key_manager
    except AttributeError:
        manager = root._key_manager = KeyManager()
        safeWrite(root._key_manager)
        safeWrite(root)
    return manager
Esempio n. 14
0
def get_system_upgrade_user(context):
    while not IApplication.providedBy(context):
        context = aq_parent(aq_inner(context))

    acl_users = context.acl_users
    if not acl_users.getUserById('system-upgrade'):
        acl_users.userFolderAddUser('system-upgrade',
                                    os.urandom(16).encode('hex'), ['Manager'],
                                    None)
    return acl_users.getUserById('system-upgrade')
Esempio n. 15
0
def getRootKeyManager(root):
    if not IApplication.providedBy(root):
        return
    try:
        manager = root._key_manager
    except AttributeError:
        manager = root._key_manager = KeyManager()
        safeWrite(root._key_manager)
        safeWrite(root)
    return manager
Esempio n. 16
0
 def _getOwner(self, container):
     try:
         user = container.getWrappedOwner()
     except AttributeError, e: # we have a zope rather than a plone user
         owner = [u for u, roles in container.get_local_roles() if 'Owner' in roles][0]
         context = aq_inner(self.context)
         user = context.acl_users.getUserById(owner)
         while not user and not IApplication.providedBy(context):
             context = aq_parent(context)
             user = context.acl_users.getUserById(owner)
Esempio n. 17
0
 def plone_reload(self, zcml=False):
     from Acquisition import aq_inner, aq_parent
     from OFS.interfaces import IApplication
     root = aq_parent(self.context)
     while aq_parent(root) and not IApplication.providedBy(root):
         root = aq_inner(aq_parent(root))
     # get reload view from plone.reload
     reload = root.restrictedTraverse('reload')
     if zcml:
         print reload.zcml_reload()
     else:
         print reload.code_reload()
Esempio n. 18
0
 def _getOwner(self, container):
     try:
         user = container.getWrappedOwner()
     except AttributeError, e:  # we have a zope rather than a plone user
         owner = [
             u for u, roles in container.get_local_roles()
             if 'Owner' in roles
         ][0]
         context = aq_inner(self.context)
         user = context.acl_users.getUserById(owner)
         while not user and not IApplication.providedBy(context):
             context = aq_parent(context)
             user = context.acl_users.getUserById(owner)
Esempio n. 19
0
    def get_role_adapter(self):
        site = getSite()
        request = site.REQUEST
        context = request.PARENTS[0]

        if is_rest_available and isinstance(context, RESTWrapper):
            # when the sharing endpoint is called through the REST-API, the
            # context is a RESTWrapper object, which normally delegates
            # everything to self.context, but this does not work for certain
            # magic methods, like __provides__ breaks get_workflow_for in
            # DynamicRolesAdapter. We therefore pass the real object here.
            context = context.context

        if IApplication.providedBy(context):
            context = site
        return getMultiAdapter((context, request),
                               IDynamicRoleAdapter,
                               name=self.plonerole)
Esempio n. 20
0
    def transform(self, result):
        result = self.parseTree(result)
        if result is None:
            return None
        root = result.tree.getroot()
        url = urlparse(self.request.URL)
        try:
            token = createToken()
        except ComponentLookupError:
            context = self.getContext()
            if IApplication.providedBy(context) or \
                    IResource.providedBy(context):
                # skip here, utility not installed yet on zope root
                return
            raise

        for form in root.cssselect('form'):
            # XXX should we only do POST? If we're logged in and
            # it's an internal form, I'm inclined to say no...
            #method = form.attrib.get('method', 'GET').lower()
            #if method != 'post':
            #    continue

            # some get forms we definitely do not want to protect.
            # for now, we know search we do not want to protect
            method = form.attrib.get('method', 'GET').lower()
            action = form.attrib.get('action', '').strip()
            if method == 'get' and '@@search' in action:
                continue
            action = form.attrib.get('action', '').strip()
            if not self.isActionInSite(action, url):
                continue
            # check if the token is already on the form..
            hidden = form.cssselect('[name="_authenticator"]')
            if len(hidden) == 0:
                hidden = etree.Element("input")
                hidden.attrib['name'] = '_authenticator'
                hidden.attrib['type'] = 'hidden'
                hidden.attrib['value'] = token
                form.append(hidden)

        return result
Esempio n. 21
0
    def __call__(self):
        mship = getToolByName(self.context, 'portal_membership')
        current_auth = mship.getAuthenticatedMember()
        if IApplication.providedBy(aq_parent(aq_parent(current_auth.getUser()))):
            IStatusMessage(self.request).addStatusMessage(_(u"Unfortunately it is not possible to send messages using your user account. Please use a Plone user rather than a Zope user."), type='error')
            return self.request.response.redirect(self.context.absolute_url())
        
        self.request.set('disable_border', True)

        self.form_fields.get('receiver').field.default = None
        self.form_fields.get('receiver').field.readonly = False
        self.form_fields.get('subject').field.default = None
        self.form_fields.get('message').field.default = None

        if self.request.get('receiver', None) is not None:
            self.form_fields.get('receiver').field.default = self.request.get('receiver', None)

        if self.request.get('subject', None) is not None:
            self.form_fields.get('subject').field.default = self.request.get('subject', None).decode('utf-8')

        return super(NewMessageForm, self).__call__()
Esempio n. 22
0
    def getPhysicalPath(self):
        """Get the physical path of the object.

        Returns a path (an immutable sequence of strings) that can be used to
        access this object again later, for example in a copy/paste operation.
        getPhysicalRoot() and getPhysicalPath() are designed to operate
        together.

        This implementation is optimized to avoid excessive amounts of function
        calls while walking up from an object on a deep level.
        """
        try:
            id = self.id or self.getId()
        except AttributeError:
            id = self.getId()

        path = (id, )
        p = aq_parent(aq_inner(self))
        if p is None:
            return path

        func = self.getPhysicalPath.im_func
        while p is not None:
            if func is p.getPhysicalPath.im_func:
                try:
                    pid = p.id or p.getId()
                except AttributeError:
                    pid = p.getId()

                path = (pid, ) + path
                p = aq_parent(aq_inner(p))
            else:
                if IApplication.providedBy(p):
                    path = ('', ) + path
                else:
                    path = p.getPhysicalPath() + path
                break

        return path
Esempio n. 23
0
    def getPhysicalPath(self):
        """Get the physical path of the object.

        Returns a path (an immutable sequence of strings) that can be used to
        access this object again later, for example in a copy/paste operation.
        getPhysicalRoot() and getPhysicalPath() are designed to operate
        together.

        This implementation is optimized to avoid excessive amounts of function
        calls while walking up from an object on a deep level.
        """
        try:
            id = self.id or self.getId()
        except AttributeError:
            id = self.getId()

        path = (id, )
        p = aq_parent(aq_inner(self))
        if p is None:
            return path

        func = self.getPhysicalPath.im_func
        while p is not None:
            if func is p.getPhysicalPath.im_func:
                try:
                    pid = p.id or p.getId()
                except AttributeError:
                    pid = p.getId()

                path = (pid, ) + path
                p = aq_parent(aq_inner(p))
            else:
                if IApplication.providedBy(p):
                    path = ('', ) + path
                else:
                    path = p.getPhysicalPath() + path
                break

        return path
Esempio n. 24
0
def getRoot(context):
    while not IApplication.providedBy(context) and context is not None:
        context = aq_parent(context)
    return context
Esempio n. 25
0
def get_root(app):
    for parent in aq_iter(app, error=AttributeError):
        if IApplication.providedBy(parent):
            return parent
    raise AttributeError, 'No application found'
Esempio n. 26
0
def get_root(app):
    for parent in aq_iter(app, error=AttributeError):
        if IApplication.providedBy(parent):
            return parent
    raise AttributeError('No application found')
Esempio n. 27
0
def getRoot(context):
    while not IApplication.providedBy(context) and context is not None:
        context = aq_parent(context)
    return context
Esempio n. 28
0
 def sitemanager(self):
     if IApplication.providedBy(self.context):
         return getGlobalSiteManager()
     elif IPloneSiteRoot.providedBy(self.context):
         return self.context.getSiteManager()
Esempio n. 29
0
 def _find_app(self, plone_site_obj):
     parent = aq_parent(plone_site_obj)
     if IApplication.providedBy(parent):
         return parent
     else:
         return self._find_app(parent)
Esempio n. 30
0
 def sitemanager(self):
     if IApplication.providedBy(self.context):
         return getGlobalSiteManager()
     elif IPloneSiteRoot.providedBy(self.context):
         return self.context.getSiteManager()