def impersonateOwner(portal,object):
    #get owner of an object
    impersonateWithObjectOwner(object)
    if getSecurityManager().getUser().getId() is None:
        impersonateSiteadmin(portal)
        if getSecurityManager().getUser().getId() is None:
            impersonateAdminUser(portal)
Ejemplo n.º 2
0
 def testCanAccessWithAccessPermissionSecurityManager(self):
     # manage_main should be accessible if we have the necessary permissions
     self.setPermissions(access_permissions)
     try:
         getSecurityManager().validate(self.ps, self.ps, "manage_main", self.ps.manage_main)
     except Unauthorized:
         self.fail("Access to manage_main was denied")
Ejemplo n.º 3
0
    def test__checkPermission(self):
        from AccessControl import getSecurityManager
        from AccessControl.ImplPython import ZopeSecurityPolicy
        from AccessControl.Permission import Permission
        from AccessControl.SecurityManagement import newSecurityManager
        from AccessControl.SecurityManager import setSecurityPolicy
        from Products.CMFCore.utils import _checkPermission

        setSecurityPolicy(ZopeSecurityPolicy())
        site = self._makeSite()
        newSecurityManager(None, site.acl_users.user_foo)
        o = site.bar_dummy
        Permission('View',(),o).setRoles(('Anonymous',))
        Permission('WebDAV access',(),o).setRoles(('Authenticated',))
        Permission('Manage users',(),o).setRoles(('Manager',))
        eo = site.foo_dummy
        eo._owner = (['acl_users'], 'all_powerful_Oz')
        getSecurityManager().addContext(eo)
        self.failUnless( _checkPermission('View', o) )
        self.failUnless( _checkPermission('WebDAV access', o) )
        self.failIf( _checkPermission('Manage users', o) )

        eo._proxy_roles = ('Authenticated',)
        self.failIf( _checkPermission('View', o) )
        self.failUnless( _checkPermission('WebDAV access', o) )
        self.failIf( _checkPermission('Manage users', o) )

        eo._proxy_roles = ('Manager',)
        self.failIf( _checkPermission('View', o) )
        self.failIf( _checkPermission('WebDAV access', o) )
        self.failUnless( _checkPermission('Manage users', o) )
Ejemplo n.º 4
0
 def getCatalogedObjectsCheckView(self, meta_type=None, approved=0, howmany=-1, sort_on='releasedate', sort_order='reverse', has_local_role=0, **kwargs):
     l_results = []
     l_filter = {}
     l_filter = {'submitted': 1} #only submitted items
     if approved: l_filter['approved'] = 1
     if has_local_role == 1: l_filter['has_local_role'] = 1
     if sort_on != '':
         l_filter['sort_on'] = sort_on
         if sort_order != '':
             l_filter['sort_order'] = sort_order
     if meta_type: l_filter['meta_type'] = self.utConvertToList(meta_type)
     else: l_filter['meta_type'] = self.searchable_content
     #extra filters
     l_filter.update(kwargs)
     #perform the search
     l_results = self.__searchCatalog(l_filter)
     if howmany == -1:
         l_objects = self.__getObjects(l_results)
         return [obj for obj in l_objects if getSecurityManager().checkPermission(view, obj)]
     else:
         if howmany > len(l_results):
             howmany = len(l_results)
         l_temp = l_results[:howmany]
         l_all = len(l_results)
         l_objects = self.__getObjects(l_temp)
         l_output = []
         l_counter = howmany
         while len(l_temp) >= 0:
             l_output.extend([obj for obj in l_objects if getSecurityManager().checkPermission(view, obj)])
             if len(l_output) >= howmany:
                 return l_output[:howmany]
             else:
                 l_temp = l_results[l_counter:l_counter+howmany]
                 l_counter = l_counter + howmany
                 l_objects = self.__getObjects(l_temp)
 def testLogoutLogsOut(self):
     uf = self.app.acl_users
     uf.userFolderAddUser('user_1', '', [], [])
     newSecurityManager(None, uf.getUserById('user_1').__of__(uf))
     self.assertEqual(getSecurityManager().getUser().getUserName(), 'user_1')
     self.logout()
     self.assertEqual(getSecurityManager().getUser().getUserName(), 'Anonymous User')
Ejemplo n.º 6
0
def verifyPermission(permission, obj):
    roles = rolesForPermissionOn(permission, obj)
    if type(roles) is types.StringType:
        roles=[roles]
    # C implementation of validate does not take keyword arguments
    accessed, container, name, value = obj, obj, '', obj
    getSecurityManager().validate(accessed, container, name, value, roles)
def cb_userHasCopyOrMovePermission(self):
    has_copy_or_move = getSecurityManager().checkPermission(copy_or_move, self)
    has_del = getSecurityManager().checkPermission(
        "Delete portal content", self)
    # import ipdb; ipdb.set_trace()
    if has_copy_or_move and has_del:
        return 1
Ejemplo n.º 8
0
def mailPassword(self, login, REQUEST):
    request = REQUEST or self.REQUEST
    portal = getToolByName(self, "portal_url").getPortalObject()
    member = get_member_by_login_name(self, login, raise_exceptions=False)

    # member.getUser gives us the wrong context for setting up a
    # SecurityManager.
    acl_users = getToolByName(portal, "acl_users")
    user = acl_users.getUserById(member.getId())

    orig_sm = getSecurityManager()
    try:
        newSecurityManager(request, user)
        tmp_sm = getSecurityManager()
        if not tmp_sm.checkPermission(SetOwnPassword, portal):

            # Re-use this ready-translated message for now
            exc = exc_class(_(u"Mailing forgotten passwords has been disabled."))

            # Work around bug in mail_password under Py>2.6
            if hasattr(exc, "message"):
                exc.message = exc.message
            raise exc
    finally:
        setSecurityManager(orig_sm)
    return self._original_mailPassword(login, REQUEST)
Ejemplo n.º 9
0
 def check_delete_permission(self):
     """Check if user may delete object"""
     if getSecurityManager().checkPermission("Delete objects", self):
         username = getSecurityManager().getUser().getUserName()
         if username == self.getOwner().getId():
             return True
     return False
Ejemplo n.º 10
0
 def testCanAccessIfManagerSecurityManager(self):
     # manage_main should be accessible to Manager
     self.setRoles(["Manager"])
     try:
         getSecurityManager().validate(self.ps, self.ps, "manage_main", self.ps.manage_main)
     except Unauthorized:
         self.fail("Access to manage_main was denied to Manager")
    def getItems(self, contents=None):
        # needed to circumvent bug :-(
        self.request.debug = False

        # transmute request interfaces
        ifaces = directlyProvidedBy(self.request)
        directlyProvides(self.request, ICollageBrowserLayer)

        views = []

        if not contents:
            contents = self.context.folderlistingFolderContents()

        for context in contents:
            target = context
            manager = IDynamicViewManager(context)
            layout = manager.getLayout()

            if not layout:
                layout, title = manager.getDefaultLayout()

            if ICollageAlias.providedBy(context):
                target = context.get_target()

                # if not set, revert to context
                if target is None:
                    target = context

                # verify that target is accessible
                try:
                    getSecurityManager().validate(self, self, target.getId(), target)
                except Unauthorized:
                    continue

            # Filter out translation duplicates:
            # If a non-alias object is translatable, check if its language
            # is set to the currently selected language or to neutral,
            # or if it is the canonical version
            elif isTranslatable(target):
                language = self.request.get('LANGUAGE','')
                if target.Language() not in (language, ''):
                    # Discard the object, if it is not the canonical version
                    # or a translation is available in the requested language.
                    if not target.isCanonical() or target.getTranslation(language) in contents:
                        continue

            # assume that a layout is always available
            view = getMultiAdapter((target, self.request), name=layout)

            # store reference to alias if applicable
            if ICollageAlias.providedBy(context):
                view.__alias__ = context

            views.append(view)

        # restore interfaces
        directlyProvides(self.request, ifaces)

        return views
Ejemplo n.º 12
0
    def _verifyObjectPaste(self, object, validate_src=1):
        # This assists the version in OFS.CopySupport.
        # It enables the clipboard to function correctly
        # with objects created by a multi-factory.
        if (hasattr(object, '__factory_meta_type__') and
            hasattr(self, 'all_meta_types')):
            mt = object.__factory_meta_type__
            method_name=None
            permission_name = None
            meta_types = self.all_meta_types
            if callable(meta_types): meta_types = meta_types()
            for d in meta_types:
                if d['name']==mt:
                    method_name=d['action']
                    permission_name = d.get('permission', None)
                    break

            if permission_name is not None:
                if getSecurityManager().checkPermission(permission_name,self):
                    if not validate_src:
                        # We don't want to check the object on the clipboard
                        return
                    try: parent = aq_parent(aq_inner(object))
                    except: parent = None
                    if getSecurityManager().validate(None, parent,
                                                     None, object):
                        # validation succeeded
                        return
                    raise 'Unauthorized', absattr(object.id)
                else:
                    raise 'Unauthorized', permission_name
            #
            # Old validation for objects that may not have registered 
            # themselves in the proper fashion.
            #
            elif method_name is not None:
                meth=self.unrestrictedTraverse(method_name)
                if hasattr(meth, 'im_self'):
                    parent = meth.im_self
                else:
                    try:    parent = aq_parent(aq_inner(meth))
                    except: parent = None
                if getSecurityManager().validate(None, parent, None, meth):
                    # Ensure the user is allowed to access the object on the
                    # clipboard.
                    if not validate_src:
                        return
                    try: parent = aq_parent(aq_inner(object))
                    except: parent = None
                    if getSecurityManager().validate(None, parent,
                                                     None, object):
                        return
                    id = object.id
                    if callable(id): id = id()
                    raise 'Unauthorized', id
                else:
                    raise 'Unauthorized', method_name
        PortalFolder.inheritedAttribute(
            '_verifyObjectPaste')(self, object, validate_src)
Ejemplo n.º 13
0
    def __call__(self):
        self.errors = []
        self.protect()
        context = aq_inner(self.context)

        catalog = getToolByName(context, 'portal_catalog')
        mtool = getToolByName(context, 'portal_membership')

        missing = []
        for key in self.request.form.keys():
            if not key.startswith('UID_'):
                continue
            index = key.split('_')[-1]
            uid = self.request.form[key]
            brains = catalog(UID=uid)
            if len(brains) == 0:
                missing.append(uid)
                continue
            obj = brains[0].getObject()
            title = self.objectTitle(obj)
            if not mtool.checkPermission('Copy or Move', obj):
                self.errors(_(u'Permission denied to rename ${title}.',
                              mapping={u'title': title}))
                continue

            sp = transaction.savepoint(optimistic=True)

            newid = self.request.form['newid_' + index].encode('utf8')
            newtitle = self.request.form['newtitle_' + index]
            try:
                obid = obj.getId()
                title = obj.Title()
                change_title = newtitle and title != newtitle
                if change_title:
                    getSecurityManager().validate(obj, obj, 'setTitle',
                                                  obj.setTitle)
                    obj.setTitle(newtitle)
                    notify(ObjectModifiedEvent(obj))
                if newid and obid != newid:
                    parent = aq_parent(aq_inner(obj))
                    # Make sure newid is safe
                    newid = INameChooser(parent).chooseName(newid, obj)
                    # Update the default_page on the parent.
                    context_state = getMultiAdapter(
                        (obj, self.request), name='plone_context_state')
                    if context_state.is_default_page():
                        parent.setDefaultPage(newid)
                    parent.manage_renameObjects((obid, ), (newid, ))
                elif change_title:
                    # the rename will have already triggered a reindex
                    obj.reindexObject()
            except ConflictError:
                raise
            except Exception:
                sp.rollback()
                self.errors.append(_('Error renaming ${title}', mapping={
                    'title': title}))

        return self.message(missing)
Ejemplo n.º 14
0
 def __call__(self, *arg, **kw):
     # get method from acquisition path
     method = getattr(self, self.method_name)
     # check if we have 'View' permission for this method
     # (raises error if not)
     getSecurityManager().checkPermission('View', method)
     # okay, execute it with supplied arguments
     return apply(method, arg, kw)
Ejemplo n.º 15
0
    def testSecurityContext(self):
        # The authenticated user should not change as a result of publish
        self.assertEqual(getSecurityManager().getUser().getId(), user_name)

        self.folder.acl_users.userFolderAddUser('barney', 'secret', [], [])
        self.publish(self.folder_path, basic='barney:secret')

        self.assertEqual(getSecurityManager().getUser().getId(), user_name)
Ejemplo n.º 16
0
def renameObjectsByPaths(self, paths, new_ids, new_titles,
                         handle_errors=True, REQUEST=None):
    """ CMFPlone override
    """
    smanager = getSecurityManager()
    obj = self
    if not smanager.checkPermission('Delete objects', obj) and not \
                        smanager.checkPermission('Copy or Move', obj):
        return Unauthorized("You may not modify this object")
    failure = {}
    success = {}
    # use the portal for traversal in case we have relative paths
    portal = getToolByName(self, 'portal_url').getPortalObject()
    traverse = portal.restrictedTraverse
    for i, path in enumerate(paths):
        new_id = new_ids[i]
        new_title = new_titles[i]
        if handle_errors:
            sp = transaction.savepoint(optimistic=True)
        try:
            obj = traverse(path, None)
            obid = obj.getId()
            title = obj.Title()
            change_title = new_title and title != new_title
            changed = False
            if change_title:
                getSecurityManager().validate(obj, obj, 'setTitle',
                                              obj.setTitle)
                obj.setTitle(new_title)
                notify(ObjectModifiedEvent(obj))
                changed = True
            if new_id and obid != new_id:
                parent = aq_parent(aq_inner(obj))

                # Don't forget default page.
                if hasattr(parent, 'getDefaultPage'):
                    default_page = getDefaultPage(parent, request=REQUEST)
                    if default_page == obid:
                        parent.setDefaultPage(new_id)

                parent.manage_renameObjects((obid,), (new_id,))
                changed = True

            elif change_title:
                # the rename will have already triggered a reindex
                obj.reindexObject()
            if changed:
                success[path] = (new_id, new_title)
        except ConflictError:
            raise
        except Exception, e:
            if handle_errors:
                # skip this object but continue with sub-objects.
                sp.rollback()
                failure[path] = e
            else:
                raise
Ejemplo n.º 17
0
def onObjectEditedEvent(object,event):
    from AccessControl import getSecurityManager
    sm = getSecurityManager()

    currentuserid = getSecurityManager().getUser().getId()
    if currentuserid <> None:
        setProperties(object)
        onObjectModification(object,last_change_action_edit,object.modified())
        object.reindexObject()
Ejemplo n.º 18
0
    def getCatalogedMapObjects(
        self,
        meta_type=None,
        approved=0,
        howmany=-1,
        sort_on="releasedate",
        sort_order="reverse",
        has_local_role=0,
        **kwargs
    ):
        from AccessControl.User import nobody
        from AccessControl.SecurityManagement import newSecurityManager

        auth_user = self.REQUEST.AUTHENTICATED_USER.getUserName()
        newSecurityManager(None, nobody)

        l_results = []
        l_filter = {}
        l_filter = {"submitted": 1}  # only submitted items
        if approved:
            l_filter["approved"] = 1
        if has_local_role == 1:
            l_filter["has_local_role"] = 1
        if sort_on != "":
            l_filter["sort_on"] = sort_on
            if sort_order != "":
                l_filter["sort_order"] = sort_order
        if meta_type:
            l_filter["meta_type"] = self.utConvertToList(meta_type)
        else:
            l_filter["meta_type"] = self.searchable_content
        # extra filters
        l_filter.update(kwargs)
        # perform the search
        l_results = self.__searchCatalog(l_filter)

        if howmany == -1:
            l_objects = self.__getObjects(l_results)
            return [obj for obj in l_objects if getSecurityManager().checkPermission(view, obj)]
        else:
            if howmany > len(l_results):
                howmany = len(l_results)
            l_temp = l_results[:howmany]
            l_all = len(l_results)
            l_objects = self.__getObjects(l_temp)
            l_output = []
            l_counter = howmany
            while len(l_temp) >= 0:
                l_output.extend([obj for obj in l_objects if getSecurityManager().checkPermission(view, obj)])
                if len(l_output) >= howmany:
                    return l_output[:howmany]
                else:
                    l_temp = l_results[l_counter : l_counter + howmany]
                    l_counter = l_counter + howmany
                    l_objects = self.__getObjects(l_temp)
        newSecurityManager(None, auth_user)
def Added(event):
    activities = getUtility(IRecentActivityUtility)
    username = getSecurityManager().getUser().getId()
    fullname = getSecurityManager().getUser().getProperty('fullname')
    activities.addActivity(DateTime(),
                           "added",
                            username,
                            fullname,
                            event.object,
                            aq_parent(event.object))
Ejemplo n.º 20
0
def migrateuserareas(object):

    portal = object.portal_url.getPortalObject()

    #make owner of the object as user in context for creating inner objects
    getCurrentUser(object)

    from AccessControl import getSecurityManager
    currentuserid = getSecurityManager().getUser().getId()
    if currentuserid is None:
        getAdminUser(portal)
        currentuserid = getSecurityManager().getUser().getId()

    if currentuserid <> None and object <> None:
        ids = object.objectIds()
        try:
            myimporteditems = getattr(object,'myimporteditems')
        except AttributeError:
            myimporteditems = getOrCreateType(object,object,'myimporteditems','GenericContainer')

        myimporteditems.title = "My Imported Items"
        myimporteditems.reindexObject()

        for jid in ids:
            try:
                cb = object.manage_copyObjects(ids = jid)
                myimporteditems.manage_pasteObjects(cb)
                transaction.savepoint()
            except Unauthorized:
                getAdminUser(portal)
                cb = object.manage_copyObjects(ids = jid)
                myimporteditems.manage_pasteObjects(cb)
                transaction.savepoint()
                getCurrentUser(object)

        #cb = object.manage_copyObjects(ids= ids)
        #myimporteditems.manage_pasteObjects(cb)
        #transaction.savepoint()

        object.manage_delObjects(ids=ids)
        transaction.savepoint()

        setup_users_privatespace(object)
        setup_users_publicspace(object)

        publicspace = getattr(object,'public')

        cb1 = object.manage_cutObjects(ids=('myimporteditems',))
        publicspace.manage_pasteObjects(cb1)
        transaction.savepoint()

        set_placeful_workflow_policy(object,USER_SPACEFOLDER_WORKFLOW_POLICY,None)

    #make admin as user in context for creating inner objects
    getAdminUser(portal)
Ejemplo n.º 21
0
 def test_login_2(self):
     # A specified user should be logged in
     self.app = self._app()
     self._setupFolder()
     self._setupUserFolder()
     self.folder.acl_users.userFolderAddUser('user_2', 'secret', [], [])
     auth_name = getSecurityManager().getUser().getUserName()
     self.assertEqual(auth_name, 'Anonymous User')
     self.login('user_2')
     auth_name = getSecurityManager().getUser().getId()
     self.assertEqual(auth_name, 'user_2')
Ejemplo n.º 22
0
    def __call__(self):
        self.errors = []
        self.protect()
        context = aq_inner(self.context)

        torename = json_loads(self.request.form["torename"])

        catalog = getToolByName(context, "portal_catalog")
        mtool = getToolByName(context, "portal_membership")

        missing = []
        for data in torename:
            uid = data["UID"]
            brains = catalog(UID=uid)
            if len(brains) == 0:
                missing.append(uid)
                continue
            obj = brains[0].getObject()
            title = self.objectTitle(obj)
            if not mtool.checkPermission("Copy or Move", obj):
                self.errors(_(u"Permission denied to rename ${title}.", mapping={u"title": title}))
                continue

            sp = transaction.savepoint(optimistic=True)

            newid = data["newid"].encode("utf8")
            newtitle = data["newtitle"]
            try:
                obid = obj.getId()
                title = obj.Title()
                change_title = newtitle and title != newtitle
                if change_title:
                    getSecurityManager().validate(obj, obj, "setTitle", obj.setTitle)
                    obj.setTitle(newtitle)
                    notify(ObjectModifiedEvent(obj))
                if newid and obid != newid:
                    parent = aq_parent(aq_inner(obj))
                    # Make sure newid is safe
                    newid = INameChooser(parent).chooseName(newid, obj)
                    # Update the default_page on the parent.
                    context_state = getMultiAdapter((obj, self.request), name="plone_context_state")
                    if context_state.is_default_page():
                        parent.setDefaultPage(newid)
                    parent.manage_renameObjects((obid,), (newid,))
                elif change_title:
                    # the rename will have already triggered a reindex
                    obj.reindexObject()
            except ConflictError:
                raise
            except Exception:
                sp.rollback()
                self.errors.append(_("Error renaming ${title}", mapping={"title": title}))

        return self.message(missing)
Ejemplo n.º 23
0
    def manage_FTPstat(self,REQUEST):
        """Psuedo stat, used by FTP for directory listings.
        """
        from AccessControl.User import nobody
        mode=0100000

        if (hasattr(aq_base(self),'manage_FTPget')):
            try:
                if getSecurityManager().validate(
                    None, self, 'manage_FTPget', self.manage_FTPget):
                    mode=mode | 0440
            except Unauthorized:
                pass

            if nobody.allowed(
                self.manage_FTPget,
                getRoles(self, 'manage_FTPget', self.manage_FTPget, ()),
                ):
                mode=mode | 0004

        # check write permissions
        if hasattr(aq_base(self),'PUT'):
            try:
                if getSecurityManager().validate(None, self, 'PUT', self.PUT):
                    mode=mode | 0220
            except Unauthorized:
                pass

            if nobody.allowed(
                self.PUT,
                getRoles(self, 'PUT', self.PUT, ()),
                ):
                mode=mode | 0002

        # get size
        if hasattr(aq_base(self), 'get_size'):
            size=self.get_size()
        elif hasattr(aq_base(self),'manage_FTPget'):
            size=len(self.manage_FTPget())
        else:
            size=0
        # get modification time
        if hasattr(aq_base(self), 'bobobase_modification_time'):
            mtime=self.bobobase_modification_time().timeTime()
        else:
            mtime=time.time()
        # get owner and group
        owner=group='Zope'
        if hasattr(aq_base(self), 'get_local_roles'):
            for user, roles in self.get_local_roles():
                if 'Owner' in roles:
                    owner=user
                    break
        return marshal.dumps((mode,0,0,1,owner,group,size,mtime,mtime,mtime))
Ejemplo n.º 24
0
 def test_login(self):
     # User should be able to log in
     self.app = self._app()
     self._setupFolder()
     self._setupUserFolder()
     self._setupUser()
     auth_name = getSecurityManager().getUser().getUserName()
     self.assertEqual(auth_name, 'Anonymous User')
     self.login()
     auth_name = getSecurityManager().getUser().getId()
     self.assertEqual(auth_name, user_name)
Ejemplo n.º 25
0
 def _getContainer(self):
     # Utility for bindcode.
     while 1:
         self = self.aq_inner.aq_parent
         if not getattr(self, "_is_wrapperish", None):
             parent = getattr(self, "aq_parent", None)
             inner = getattr(self, "aq_inner", None)
             container = getattr(inner, "aq_parent", None)
             try:
                 getSecurityManager().validate(parent, container, "", self)
             except Unauthorized:
                 return UnauthorizedBinding("container", self)
             return self
Ejemplo n.º 26
0
 def check_user_cannot_view_or_edit(self, card, userid):
     " if userid then login as that user otherwise logout (use Anonymous User) "
     if userid:
         self.login(userid)
     else:
         self.logout()
     # some_retrieved_value = card.getComments() # no worky: this doesn't check security!
     # check if the card is viewable by anon
     self.assertEqual(security.checkPermission('zope2.View', card), False)
     # but can't find an equivalent zope2 permission for Modify so
     # try this way:
     self.assertEqual(getSecurityManager().checkPermission( "View", card), None)
     self.assertEqual(getSecurityManager().checkPermission( "Modify portal content", card), None)
Ejemplo n.º 27
0
    def __call__(self):
        self.errors = []
        self.protect()
        context = aq_inner(self.context)

        torename = json.loads(self.request.form['torename'])

        catalog = getToolByName(context, 'portal_catalog')
        mtool = getToolByName(context, 'portal_membership')

        missing = []
        for data in torename:
            uid = data['UID']
            brains = catalog(UID=uid)
            if len(brains) == 0:
                missing.append(uid)
                continue
            obj = brains[0].getObject()
            title = self.objectTitle(obj)
            if not mtool.checkPermission('Copy or Move', obj):
                self.errors(_(u'Permission denied to rename ${title}.',
                              mapping={u'title': title}))
                continue

            sp = transaction.savepoint(optimistic=True)

            newid = data['newid'].encode('utf8')
            newtitle = data['newtitle']
            try:
                obid = obj.getId()
                title = obj.Title()
                change_title = newtitle and title != newtitle
                if change_title:
                    getSecurityManager().validate(obj, obj, 'setTitle',
                                                  obj.setTitle)
                    obj.setTitle(newtitle)
                    notify(ObjectModifiedEvent(obj))
                if newid and obid != newid:
                    parent = aq_parent(aq_inner(obj))
                    parent.manage_renameObjects((obid,), (newid,))
                elif change_title:
                    # the rename will have already triggered a reindex
                    obj.reindexObject()
            except ConflictError:
                raise
            except Exception:
                sp.rollback()
                self.errors.append(_('Error renaming ${title}', mapping={
                    'title': title}))

        return self.message(missing)
Ejemplo n.º 28
0
    def getSortedKeys(self):
        """ returns a list of keys sorted accordingly to the
        selected sort method (may be unsorted if method = no sort)
        """
        sortMethod = self.getSortMethod()
        keys, values = zip(*self.getTermItems())
        keys = list(keys)

        if not hasattr(self, 'sortMethod'):
            # smooth upgrade from previous releases
            return keys
        if sortMethod == atvm_config.SORT_METHOD_LEXICO_KEYS:
            keys.sort()
            return keys
        if sortMethod == atvm_config.SORT_METHOD_LEXICO_VALUES:
            # returns keys sorted by lexicogarphic order of VALUES
            sm = getSecurityManager()
            terms = [
                t for t in self.contentValues()
                if IPleiadesVocabularyTerm.providedBy(t)
                and sm.checkPermission(View, t)
            ]
            terms.sort(
                lambda x, y: cmp(
                    x.getVocabularyValue(), y.getVocabularyValue()))
            return [term.getVocabularyKey() for term in terms]
        if sortMethod == atvm_config.SORT_METHOD_FOLDER_ORDER:
            return keys
        if sortMethod == SORT_METHOD_TEMPORAL:
            sm = getSecurityManager()
            kvdict = dict(
                (k, t) for k, t in self.contentItems()
                if IPleiadesVocabularyTerm.providedBy(t)
                and sm.checkPermission(View, t)
            )

            def range(key):
                term = kvdict[key]
                descr = term.Description()
                m = re.search(
                    r"\[\[(-{0,1}\d*\.{0,1}\d*)\s*,\s*(-{0,1}\d*\.{0,1}\d*)\]\]",
                    descr)
                if m is not None:
                    min = float(m.group(1))
                    max = float(m.group(2))
                    return min, max
                else:
                    return None
            keys.sort(lambda x, y: cmp(range(x), range(y)))
        # fallback
        return keys
Ejemplo n.º 29
0
    def handleDelete(self, action):
        (data, errors) = self.extractData()
        if errors:
            return

        user = getSecurityManager().getUser()
        if user.password != data["password"]:
            raise WidgetActionExecutionError("password",
                    Invalid(_(u"Invalid password")))

        user = getSecurityManager().getUser()
        Session.delete(user)
        self.logout()
        self.request.response.redirect(self.request.client.absolute_url())
Ejemplo n.º 30
0
 def available(self, context):
     """ field is addable in the current context """
     securityManager = getSecurityManager()
     permission = queryUtility(IPermission, name=self.permission)
     if permission is None:
         return True
     return bool(securityManager.checkPermission(permission.title, context))
Ejemplo n.º 31
0
 def can_manage(self):
     secman = getSecurityManager()
     return secman.checkPermission(ManagePortal, self.context)
Ejemplo n.º 32
0
def DA__call__(self, REQUEST=None, __ick__=None, src__=0, test__=0, **kw):
    """Call the database method

    The arguments to the method should be passed via keyword
    arguments, or in a single mapping object. If no arguments are
    given, and if the method was invoked through the Web, then the
    method will try to acquire and use the Web REQUEST object as
    the argument mapping.

    The returned value is a sequence of record objects.
    """
    __traceback_supplement__ = (SQLMethodTracebackSupplement, self)

    c = kw.pop("connection_id", None)
    #if c is not None:
      #LOG("DA", 300, "connection %s provided to %s" %(c, self.id))
    # patch: dynamic brain configuration
    zsql_brain = kw.pop('zsql_brain', None) 
    # patch end
    
      
    if REQUEST is None:
        if kw: REQUEST=kw
        else:
            if hasattr(self, 'REQUEST'): REQUEST=self.REQUEST
            else: REQUEST={}

    # Patch to implement dynamic connection id
    # Connection id is retrieve from user preference
    if c is None:
      physical_path = self.getPhysicalPath()
      # XXX cleaner solution will be needed
      if 'portal_catalog' not in physical_path and\
         'cmf_activity' not in self.connection_id and\
         'transactionless' not in self.connection_id:
        try:
          archive_id = self.portal_preferences.getPreferredArchive()
        except AttributeError:
          pass
        else:
          if archive_id not in (None, ''):
            archive_id = archive_id.split('/')[-1]
            #LOG("DA__call__, archive_id 2", 300, archive_id)
            archive = self.portal_archives._getOb(archive_id, None)
            if archive is not None:
              c = archive.getConnectionId()
              #LOG("DA call", INFO, "retrieved connection %s from preference" %(c,))

    if c is None:
      # connection hook
      c = self.connection_id
      # for backwards compatability
      hk = self.connection_hook
      # go get the connection hook and call it
      if hk: c = getattr(self, hk)()
    #LOG("DA__call__ connection", 300, c)
    try: dbc=getattr(self, c)
    except AttributeError:
        raise AttributeError, (
            "The database connection <em>%s</em> cannot be found." % (
            c))

    try: DB__=dbc()
    except: raise DatabaseError, (
        '%s is not connected to a database' % self.id)

    p = aq_parent(self) # None if no aq_parent

    argdata=self._argdata(REQUEST)
    argdata['sql_delimiter']='\0'
    argdata['sql_quote__']=dbc.sql_quote__

    security=getSecurityManager()
    security.addContext(self)
    try:
        try:     query=apply(self.template, (p,), argdata)
        except TypeError, msg:
            msg = str(msg)
            if find(msg,'client') >= 0:
                raise NameError("'client' may not be used as an " +
                    "argument name in this context")
            else: raise
    finally: security.removeContext(self)

    if src__: return query

    if self.cache_time_ > 0 and self.max_cache_ > 0:
        result=self._cached_result(DB__, query, self.max_rows_, c)
    else:
      try:
#         if 'portal_ids' in query:
#           LOG("DA query", INFO, "query = %s" %(query,))
        result=DB__.query(query, self.max_rows_)
      except:
        LOG("DA call raise", ERROR, "DB = %s, c = %s, query = %s" %(DB__, c, query), error=sys.exc_info())
        raise

    # patch: dynamic brain configuration
    if zsql_brain is not None:
        try:
          class_file_, class_name_ = zsql_brain.rsplit('.', 1)
        except:
          #import pdb; pdb.post_mortem()
          raise
        brain = getBrain(class_file_, class_name_)
        # XXX remove this logging for performance
        LOG(__name__, INFO, "Using special brain: %r\n" % (brain,))
    else:
        brain = getBrain(self.class_file_, self.class_name_)

    if type(result) is type(''):
        f=StringIO()
        f.write(result)
        f.seek(0)
        result=RDB.File(f,brain,p)
    else:
        result=Results(result, brain, p)
    columns=result._searchable_result_columns()
    if test__ and columns != self._col: self._col=columns

    # If run in test mode, return both the query and results so
    # that the template doesn't have to be rendered twice!
    if test__: return query, result

    return result
Ejemplo n.º 33
0
# wrap the previous method in a cache
getItemList = CachingMethod(getItemList,
                            id='AccountingTransactionLine_getNodeItemList',
                            cache_factory='erp5_content_long')

# the cache vary with the simulation state of the current transaction,
# to display all accounts when the transaction is already delivered.
simulation_state = 'no_simulation_state'
if hasattr(context, 'getSimulationState'):
    simulation_state = context.getSimulationState()
item_list = getItemList(
    category=category,
    portal_path=context.getPortalObject().getPhysicalPath(),
    mirror=mirror,
    omit_filter=omit_filter,  # XXX possible optim: only one cache if omit_filter
    user_name=str(getSecurityManager().getUser()),
    simulation_state=simulation_state)

# make sure that the current value is included in this list, this is
# mostly for compatibility with old versions. XXX This is slow.
if omit_filter:
    return item_list

if not hasattr(context, 'getSource'):
    return item_list

for node in (context.getSource(portal_type='Account'),
             context.getDestination(portal_type='Account')):
    if node:
        if node not in [x[1] for x in item_list]:
            return context.AccountingTransactionLine_getNodeItemList(
Ejemplo n.º 34
0
## Script (Python) "filterObjectValues"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=values=None
##title=
##
from ZTUtils import LazyFilter
from AccessControl import getSecurityManager
checkPermission=getSecurityManager().checkPermission
items = []
raw_items = context.objectValues(values)
secure_items = LazyFilter(raw_items, skip='')
for item in secure_items:
    if checkPermission('Access contents information', item):
        items.append(item)
return items
Ejemplo n.º 35
0
    def __call__(self):
        portal = getToolByName(self.context, 'portal_url').getPortalObject()
        portal_types = getToolByName(portal, 'portal_types')
        context = aq_inner(self.context)
        target_folder = getattr(
            interfaces.ISolgemaFullcalendarProperties(context, None),
            'target_folder', None)
        target_folder = target_folder \
                    and portal.unrestrictedTraverse('/'+ portal.id + target_folder) \
                    or aq_parent(context)

        if not getSecurityManager().checkPermission('Add portal content',
                                                    target_folder):
            raise Unauthorized, "You can't add an event on %s" % str(
                target_folder)

        query = hasattr(self.context,
                        'buildQuery') and self.context.buildQuery() or {}
        query = normalize_type_query(query, portal)
        copyDict = getCopyObjectsUID(self.request)

        # The 'Item Type' criteria uses the 'Type' index while the 'Item Type
        # (internal)' criteria uses the 'portal_type' index.
        #
        # We need to check for both, portal_type first, because it's more
        # specific than 'Type', which just indexes the content type's Title
        # property (which can be non-unique).
        index = query.get('portal_type', query.get('Type'))
        self.request.response.setHeader("Content-type", "application/json")
        if index:
            if isinstance(index, (list, tuple)) and len(index) > 1:
                return json.dumps({'display': True})

            portal_type = isinstance(index,
                                     (tuple, list)) and index[0] or index
            if copyDict and portal.restrictedTraverse(
                    copyDict['url']).portal_type == portal_type:
                return json.dumps({'display': True})
            elif query.get('Type'):
                portal_type = isinstance(
                    query['Type'],
                    (tuple, list)) and query['Type'][0] or query['Type']
                if copyDict and portal.restrictedTraverse(
                        copyDict['url']).portal_type == portal_type:
                    return json.dumps({'display': True})
        else:
            portal_type = getattr(
                interfaces.ISolgemaFullcalendarProperties(context, None),
                'eventType', 'Event')

        pTypes = [
            a for a in portal_types.listTypeInfo() if a.id == portal_type
        ]
        pTypeTitle = pTypes and pTypes[0].Title() or portal_type
        typeTitle = translate(pTypeTitle, context=self.request)
        if HAS_PLONE40:
            title = PLMF(u'heading_add_item',
                         default='Add ${itemtype}',
                         mapping={'itemtype': typeTitle})
        else:
            title = PLMF(u'label_add_type',
                         default='Add ${type}',
                         mapping={'type': typeTitle})
        is_dx = False
        if HAS_DEXTERITY:
            is_dx = pTypes and IDexterityFTI.providedBy(pTypes[0]) or False

        return json.dumps({
            'display': False,
            'type': portal_type,
            'title': translate(title, context=self.request),
            'is_dx': is_dx
        })
Ejemplo n.º 36
0
def _checkPermission(permission, obj):
    return getSecurityManager().checkPermission(permission, obj)
Ejemplo n.º 37
0
def checkPermission(permission, object):
    """  Generic function to check a given permission on the current object. """
    return getSecurityManager().checkPermission(permission, object)
Ejemplo n.º 38
0
 def can_add_member(self):
     sm = getSecurityManager()
     return sm.checkPermission(AddPortalMember, self.context)
Ejemplo n.º 39
0
from AccessControl import getSecurityManager
from AccessControl.User import UnrestrictedUser
from AccessControl.SecurityManagement import newSecurityManager
from bika.lims import api
import csv
portal = api.get_portal()
me = UnrestrictedUser(getSecurityManager().getUser().getUserName(), '', ['LabManager'], '')
me = me.__of__(portal.acl_users)
newSecurityManager(None, me)

clients = map(api.get_object, api.search({'portal_type':'Client'}))
data = []
cols = ['NAL Number','Client ID','Email Address','Phone','Grower Number','Country','State','District','City','Zip','Address']
for i in clients:
    thisclient = {}
    thisclient[cols[0]] = i.ClientID
    thisclient[cols[1]] = i.Name
    thisclient[cols[2]] = i.EmailAddress
    thisclient[cols[3]] = i.Phone
    thisclient[cols[4]] = i.TaxNumber
    thisclient[cols[5]] = i.PhysicalAddress['country']
    thisclient[cols[6]] = i.PhysicalAddress['state']
    thisclient[cols[7]] = i.PhysicalAddress['district']
    thisclient[cols[8]] = i.PhysicalAddress['city']
    thisclient[cols[9]] = i.PhysicalAddress['zip']
    thisclient[cols[10]] = i.PhysicalAddress['address']
    data.append(thisclient)

try:
    with open("clients_export.csv", 'w') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=cols)
Ejemplo n.º 40
0
    def __call__(self):
        ar = self.context
        workflow = getToolByName(self.context, 'portal_workflow')
        if 'transition' in self.request.form:
            doActionFor(self.context, self.request.form['transition'])

        # If the analysis request has been received and hasn't been yet
        # verified yet, redirect the user to manage_results view, but only if
        # the user has privileges to Edit(Field)Results, cause otherwise she/he
        # will receive an InsufficientPrivileges error!
        if (self.request.PATH_TRANSLATED.endswith(self.context.id)
                and check_permission(EditResults, self.context)
                and check_permission(EditFieldResults, self.context)
                and wasTransitionPerformed(self.context, 'receive')
                and not wasTransitionPerformed(self.context, 'verify')):
            # Redirect to manage results view if not cancelled
            if api.get_workflow_status_of(ar, 'cancellation_state') != \
                    "cancelled":
                manage_results_url = "/".join(
                    [self.context.absolute_url(), 'manage_results'])
                self.request.response.redirect(manage_results_url)
                return

        # Contacts get expanded for view
        contact = self.context.getContact()
        contacts = []
        for cc in self.context.getCCContact():
            contacts.append(cc)
        if contact in contacts:
            contacts.remove(contact)
        ccemails = []
        for cc in contacts:
            ccemails.append(
                "%s &lt;<a href='mailto:%s'>%s</a>&gt;" %
                (cc.Title(), cc.getEmailAddress(), cc.getEmailAddress()))
        # CC Emails become mailto links
        emails = self.context.getCCEmails()
        if isinstance(emails, str):
            emails = emails and [
                emails,
            ] or []
        cc_emails = []
        cc_hrefs = []
        for cc in emails:
            cc_emails.append(cc)
            cc_hrefs.append("<a href='mailto:%s'>%s</a>" % (cc, cc))
        # render header table
        self.header_table = HeaderTableView(self.context, self.request)()
        # Create Partitions View for this ARs sample
        p = SamplePartitionsView(self.context.getSample(), self.request)
        p.show_column_toggles = False
        self.parts = p.contents_table()
        # Create Field and Lab Analyses tables
        self.tables = {}
        for poc in POINTS_OF_CAPTURE:
            if self.context.getAnalyses(getPointOfCapture=poc):
                t = self.createAnalysesView(
                    ar,
                    self.request,
                    getPointOfCapture=poc,
                    show_categories=self.context.bika_setup.
                    getCategoriseAnalysisServices(),
                    getRequestUID=self.context.UID())
                t.allow_edit = True
                t.form_id = "%s_analyses" % poc
                t.review_states[0]['transitions'] = [{
                    'id': 'submit'
                }, {
                    'id': 'retract'
                }, {
                    'id': 'verify'
                }]
                t.show_workflow_action_buttons = True
                t.show_select_column = True
                if getSecurityManager().checkPermission(EditFieldResults, self.context) \
                   and poc == 'field':
                    t.review_states[0]['columns'].remove('DueDate')
                self.tables[POINTS_OF_CAPTURE.getValue(
                    poc)] = t.contents_table()
        # Create QC Analyses View for this AR
        show_cats = self.context.bika_setup.getCategoriseAnalysisServices()
        qcview = self.createQCAnalyesView(ar,
                                          self.request,
                                          show_categories=show_cats)
        qcview.allow_edit = False
        qcview.show_select_column = False
        qcview.show_workflow_action_buttons = False
        qcview.form_id = "%s_qcanalyses"
        qcview.review_states[0]['transitions'] = [{
            'id': 'submit'
        }, {
            'id': 'retract'
        }, {
            'id': 'verify'
        }]
        self.qctable = qcview.contents_table()

        # Create the ResultsInterpretation by department view
        from resultsinterpretation import ARResultsInterpretationView
        self.riview = ARResultsInterpretationView(ar, self.request)

        # If a general retracted is done, rise a waring
        if workflow.getInfoFor(ar, 'review_state') == 'sample_received':
            allstatus = list()
            for analysis in ar.getAnalyses():
                status = workflow.getInfoFor(analysis.getObject(),
                                             'review_state')
                if status not in ['retracted', 'to_be_verified', 'verified']:
                    allstatus = []
                    break
                else:
                    allstatus.append(status)
            if len(allstatus) > 0:
                message = "General Retract Done.  Submit this AR manually."
                self.addMessage(message, 'warning')

        self.renderMessages()
        return self.template()
Ejemplo n.º 41
0
class BaseVocabularyView(BrowserView):
    def __call__(self):
        """
        Accepts GET parameters of:
        name: Name of the vocabulary
        field: Name of the field the vocabulary is being retrieved for
        query: string or json object of criteria and options.
            json value consists of a structure:
                {
                    criteria: object,
                    sort_on: index,
                    sort_order: (asc|reversed)
                }
        attributes: comma seperated, or json object list
        batch: {
            page: 1-based page of results,
            size: size of paged results
        }
        """
        context = self.get_context()
        self.request.response.setHeader('Content-Type',
                                        'application/json; charset=utf-8')

        try:
            vocabulary = self.get_vocabulary()
        except VocabLookupException, e:
            return json_dumps({'error': e.message})

        results_are_brains = False
        if hasattr(vocabulary, 'search_catalog'):
            query = self.parsed_query()
            results = vocabulary.search_catalog(query)
            results_are_brains = True
        elif hasattr(vocabulary, 'search'):
            try:
                query = self.parsed_query()['SearchableText']['query']
            except KeyError:
                results = iter(vocabulary)
            else:
                results = vocabulary.search(query)
        else:
            results = vocabulary

        try:
            total = len(results)
        except TypeError:
            # do not error if object does not support __len__
            # we'll check again later if we can figure some size
            # out
            total = 0

        # get batch
        batch = _parseJSON(self.request.get('batch', ''))
        if batch and ('size' not in batch or 'page' not in batch):
            batch = None  # batching not providing correct options
        if batch:
            # must be slicable for batching support
            page = int(batch['page'])
            size = int(batch['size'])
            if size > MAX_BATCH_SIZE:
                raise Exception('Max batch size is 500')
            # page is being passed in is 1-based
            start = (max(page - 1, 0)) * size
            end = start + size
            # Try __getitem__-based slice, then iterator slice.
            # The iterator slice has to consume the iterator through
            # to the desired slice, but that shouldn't be the end
            # of the world because at some point the user will hopefully
            # give up scrolling and search instead.
            try:
                results = results[start:end]
            except TypeError:
                results = itertools.islice(results, start, end)

        # build result items
        items = []

        attributes = _parseJSON(self.request.get('attributes', ''))
        if isinstance(attributes, basestring) and attributes:
            attributes = attributes.split(',')

        translate_ignored = [
            'author_name',
            'cmf_uid',
            'commentators',
            'created',
            'CreationDate',
            'Creator',
            'Date',
            'Description',
            'effective',
            'EffectiveDate',
            'end',
            'exclude_from_nav',
            'ExpirationDate',
            'expires',
            'getIcon',
            'getId',
            'getObjSize',
            'getRemoteUrl',
            'getURL',
            'id',
            'in_response_to',
            'is_folderish',
            'last_comment_date',
            'listCreators',
            'location',
            'meta_type',
            'ModificationDate',
            'modified',
            'path',
            'portal_type',
            'review_state',
            'start',
            'Subject',
            'sync_uid',
            'Title',
            'total_comments'
            'UID',
        ]
        if attributes:
            base_path = getNavigationRoot(context)
            sm = getSecurityManager()
            can_edit = sm.checkPermission(DEFAULT_PERMISSION_SECURE, context)
            for vocab_item in results:
                if not results_are_brains:
                    vocab_item = vocab_item.value
                item = {}
                for attr in attributes:
                    key = attr
                    if ':' in attr:
                        key, attr = attr.split(':', 1)
                    if attr in _unsafe_metadata and not can_edit:
                        continue
                    if key == 'path':
                        attr = 'getPath'
                    val = getattr(vocab_item, attr, None)
                    if callable(val):
                        if attr in _safe_callable_metadata:
                            val = val()
                        else:
                            continue
                    if key == 'path':
                        val = val[len(base_path):]
                    if (key not in translate_ignored
                            and isinstance(val, basestring)):
                        item[key] = translate(_(safe_unicode(val)),
                                              context=self.request)
                    else:
                        item[key] = val
                items.append(item)
        else:
            for item in results:
                items.append({'id': item.value, 'text': item.title})

        if total == 0:
            total = len(items)

        return json_dumps({'results': items, 'total': total})
Ejemplo n.º 42
0
def _getAuthenticatedUser( self ):
    return getSecurityManager().getUser()
Ejemplo n.º 43
0
 def testResultsPermission(self):
     s1 = getattr(self.portal, 's1')
     assert getSecurityManager().checkPermission(
         permissions.ViewSurveyResults, s1)
Ejemplo n.º 44
0
    def __init__(self,
                 id,
                 title='',
                 description='',
                 abbrev='',
                 email=None,
                 topics=None,
                 classifications=None,
                 importances=None,
                 managers=None,
                 supporters=None,
                 dispatching=None,
                 version_info_spiel=None):

        SkinnedFolder.__init__(self, id, title)

        self._setup_internal_catalog()

        self.last_issue_id = 0

        self.description = description
        self.abbrev = abbrev

        username = str(getSecurityManager().getUser())
        util.add_local_role(self, username, 'Manager')
        util.add_local_role(self, username, 'Owner')
        if managers is None:
            if username: managers = [username]
            else: managers = []
        elif username and username not in managers:
            managers.append(username)
        self.managers = managers
        if supporters is None:
            supporters = []
        self.supporters = supporters
        self._adjust_staff_roles(no_reindex=1)

        # XXX We need to ensure *some* collector email addr...
        self.email = email

        if topics is None:
            self.topics = [
                'Zope', 'Collector', 'Database', 'Catalog', 'ZServer'
            ]
        else:
            self.topics = topics

        if classifications is None:
            self.classifications = self.DEFAULT_CLASSIFICATIONS
        else:
            self.classifications = classifications

        if importances is None:
            self.importances = self.DEFAULT_IMPORTANCES
        else:
            self.importances = importances

        if version_info_spiel is None:
            self.version_info_spiel = self.DEFAULT_VERSION_INFO_SPIEL
        else:
            self.version_info_spiel = version_info_spiel

        return self
Ejemplo n.º 45
0
 def _checkViewType(self, t):
     try:
         return getSecurityManager().validate(t, t, 'Title', t.Title)
     except Unauthorized:
         return 0
Ejemplo n.º 46
0
    def __call__(self):
        ar = self.context
        workflow = getToolByName(self.context, 'portal_workflow')
        if 'transition' in self.request.form:
            doActionFor(self.context, self.request.form['transition'])
        # Contacts get expanded for view
        contact = self.context.getContact()
        contacts = []
        for cc in self.context.getCCContact():
            contacts.append(cc)
        if contact in contacts:
            contacts.remove(contact)
        ccemails = []
        for cc in contacts:
            ccemails.append(
                "%s &lt;<a href='mailto:%s'>%s</a>&gt;" %
                (cc.Title(), cc.getEmailAddress(), cc.getEmailAddress()))
        # CC Emails become mailto links
        emails = self.context.getCCEmails()
        if isinstance(emails, str):
            emails = emails and [
                emails,
            ] or []
        cc_emails = []
        cc_hrefs = []
        for cc in emails:
            cc_emails.append(cc)
            cc_hrefs.append("<a href='mailto:%s'>%s</a>" % (cc, cc))
        # render header table
        self.header_table = HeaderTableView(self.context, self.request)()
        # Create Partitions View for this ARs sample
        p = SamplePartitionsView(self.context.getSample(), self.request)
        p.show_column_toggles = False
        self.parts = p.contents_table()
        # Create Field and Lab Analyses tables
        self.tables = {}
        for poc in POINTS_OF_CAPTURE:
            if self.context.getAnalyses(getPointOfCapture=poc):
                t = self.createAnalysesView(
                    ar,
                    self.request,
                    getPointOfCapture=poc,
                    show_categories=self.context.bika_setup.
                    getCategoriseAnalysisServices())
                t.allow_edit = True
                t.form_id = "%s_analyses" % poc
                t.review_states[0]['transitions'] = [{
                    'id': 'submit'
                }, {
                    'id': 'retract'
                }, {
                    'id': 'verify'
                }]
                t.show_workflow_action_buttons = True
                t.show_select_column = True
                if getSecurityManager().checkPermission(EditFieldResults, self.context) \
                   and poc == 'field':
                    t.review_states[0]['columns'].remove('DueDate')

                self.tables[POINTS_OF_CAPTURE.getValue(
                    poc)] = t.contents_table()
        # Un-captured field analyses may cause confusion
        if ar.getAnalyses(getPointOfCapture='field',
                          review_state=['sampled', 'sample_due']):
            message = _("There are field analyses without submitted results.")
            self.addMessage(message, 'info')
        # Create QC Analyses View for this AR
        show_cats = self.context.bika_setup.getCategoriseAnalysisServices()
        qcview = self.createQCAnalyesView(ar,
                                          self.request,
                                          show_categories=show_cats)
        qcview.allow_edit = False
        qcview.show_select_column = False
        qcview.show_workflow_action_buttons = False
        qcview.form_id = "%s_qcanalyses"
        qcview.review_states[0]['transitions'] = [{
            'id': 'submit'
        }, {
            'id': 'retract'
        }, {
            'id': 'verify'
        }]
        self.qctable = qcview.contents_table()

        # Create the ResultsInterpretation by department view
        from resultsinterpretation import ARResultsInterpretationView
        self.riview = ARResultsInterpretationView(ar, self.request)

        # If a general retracted is done, rise a waring
        if workflow.getInfoFor(ar, 'review_state') == 'sample_received':
            allstatus = list()
            for analysis in ar.getAnalyses():
                status = workflow.getInfoFor(analysis.getObject(),
                                             'review_state')
                if status not in ['retracted', 'to_be_verified', 'verified']:
                    allstatus = []
                    break
                else:
                    allstatus.append(status)
            if len(allstatus) > 0:
                self.addMessage("General Retract Done", 'warning')

        # If is a retracted AR, show the link to child AR and show a warn msg
        if workflow.getInfoFor(ar, 'review_state') == 'invalid':
            childar = hasattr(ar, 'getChildAnalysisRequest') \
                        and ar.getChildAnalysisRequest() or None
            message = _(
                'These results have been withdrawn and are '
                'listed here for trace-ability purposes. Please follow '
                'the link to the retest')
            if childar:
                message = (message + " %s.") % childar.getRequestID()
            else:
                message = message + "."
            self.addMessage(message, 'warning')
        # If is an AR automatically generated due to a Retraction, show it's
        # parent AR information
        if hasattr(ar, 'getParentAnalysisRequest') \
            and ar.getParentAnalysisRequest():
            par = ar.getParentAnalysisRequest()
            message = _(
                'This Analysis Request has been '
                'generated automatically due to '
                'the retraction of the Analysis '
                'Request ${retracted_request_id}.',
                mapping={'retracted_request_id': par.getRequestID()})
            self.addMessage(message, 'info')
        self.renderMessages()
        return self.template()
Ejemplo n.º 47
0
 def __init__(self, context):
     self.context = context
     registry = getUtility(IRegistry)
     self.vat = registry.get("plone.types_use_view_action_in_listings", [])
     self.security = getSecurityManager()
     self.order = self.context.objectIds()
Ejemplo n.º 48
0
def getAllLocalRoles(self, context):
    # Perform security check on destination object
    if not getSecurityManager().checkPermission(change_permissions, context):
        raise Unauthorized(name="getAllLocalRoles")
    return self._getAllLocalRoles(context)
Ejemplo n.º 49
0
def mangleQuery(keywords, config, schema):
    """ translate / mangle query parameters to replace zope specifics
        with equivalent constructs for solr """
    extras = {}
    for key, value in keywords.items():
        if key.endswith('_usage'):  # convert old-style parameters
            category, spec = value.split(':', 1)
            extras[key[:-6]] = {category: spec}
            del keywords[key]
        elif isinstance(value, dict):  # unify dict parameters
            keywords[key] = value['query']
            del value['query']
            extras[key] = value
        elif hasattr(value, 'query'):  # unify object parameters
            keywords[key] = value.query
            extra = dict()
            for arg in query_args:
                arg_val = getattr(value, arg, None)
                if arg_val is not None:
                    extra[arg] = arg_val
            extras[key] = extra
        elif key in ignored:
            del keywords[key]

    # find EPI indexes
    if schema:
        epi_indexes = {}
        for name in schema.keys():
            parts = name.split('_')
            if parts[-1] in ['string', 'depth', 'parents']:
                count = epi_indexes.get(parts[0], 0)
                epi_indexes[parts[0]] = count + 1
        epi_indexes = [k for k, v in epi_indexes.items() if v == 3]
    else:
        epi_indexes = ['path']

    for key, value in keywords.items():
        args = extras.get(key, {})
        if key == 'SearchableText':
            pattern = getattr(config, 'search_pattern', '')
            if pattern and isSimpleSearch(value):
                value = mangle_searchable_text_query(value, pattern)
                keywords[key] = set([value])  # add literal query parameter
                continue
            elif isSimpleTerm(value):  # use prefix/wildcard search
                keywords[key] = '(%s* OR %s)' % (prepare_wildcard(value),
                                                 value)
                continue
        if key in epi_indexes:
            path = keywords['%s_parents' % key] = value
            del keywords[key]
            if 'depth' in args:
                depth = int(args['depth'])
                if depth >= 0:
                    if not isinstance(value, (list, tuple)):
                        path = [path]
                    tmpl = '(+%s_depth:[%d TO %d] AND +%s_parents:%s)'
                    params = keywords['%s_parents' % key] = set()
                    for p in path:
                        base = len(p.split('/'))
                        params.add(tmpl % (key, base, base + depth, key, p))
                del args['depth']
        elif key == 'effectiveRange':
            if isinstance(value, DateTime):
                steps = getattr(config, 'effective_steps', 1)
                if steps > 1:
                    value = DateTime(value.timeTime() // steps * steps)
                value = iso8601date(value)
            del keywords[key]
            keywords['effective'] = '[* TO %s]' % value
            keywords['expires'] = '[%s TO *]' % value
        elif key == 'show_inactive':
            del keywords[key]  # marker for `effectiveRange`
        elif 'range' in args:
            if not isinstance(value, (list, tuple)):
                value = [value]
            payload = map(iso8601date, value)
            keywords[key] = ranges[args['range']] % tuple(payload)
            del args['range']
        elif 'operator' in args:
            if isinstance(value, (list, tuple)) and len(value) > 1:
                sep = ' %s ' % args['operator'].upper()
                value = sep.join(map(str, map(iso8601date, value)))
                keywords[key] = '(%s)' % value
            del args['operator']
        elif key == 'allowedRolesAndUsers':
            if getattr(config, 'exclude_user', False):
                token = 'user$' + getSecurityManager().getUser().getId()
                if token in value:
                    value.remove(token)
        elif isinstance(value, DateTime):
            keywords[key] = iso8601date(value)
        elif not isinstance(value, basestring):
            assert not args, 'unsupported usage: %r' % args
Ejemplo n.º 50
0
 def available(self):
     permission = "Plone Social: Add Microblog Status Update"
     have_permission = getSecurityManager().checkPermission(
         permission, self.context)
     is_installed = queryUtility(IMicroblogTool)
     return have_permission and is_installed
Ejemplo n.º 51
0
    def __init__(self, context, request):
        self.context = context
        self.request = request

        self.sm = getSecurityManager()
        self.permission_cache = {}
Ejemplo n.º 52
0
def can_review(comment):
    """Returns true if current user has the 'Review comments' permission.
    """
    return bool(getSecurityManager().checkPermission('Review comments',
                                                     aq_inner(comment)))
Ejemplo n.º 53
0
 def can_review(self):
     """Returns true if current user has the 'Review comments' permission.
     """
     return getSecurityManager().checkPermission('Review comments',
                                                 aq_inner(self.context))
Ejemplo n.º 54
0
 def validate(self, inst, parent, name, value, md=None):
     return getSecurityManager().validate(inst, parent, name, value)
Ejemplo n.º 55
0
 def can_set_own_password(self):
     sm = getSecurityManager()
     return sm.checkPermission(SetOwnPassword, self.context)
Ejemplo n.º 56
0
 def can_reply(self):
     """Returns true if current user has the 'Reply to item' permission.
     """
     return getSecurityManager().checkPermission('Reply to item',
                                                 aq_inner(self.context))
Ejemplo n.º 57
0
 def can_manage_users(self):
     sm = getSecurityManager()
     return sm.checkPermission('plone.app.controlpanel.UsersAndGroups',
                               self.context)
Ejemplo n.º 58
0
 def onCompletion(self):
     self.passCheckpoint(config.CHECKPOINT_COMPLETE)
     self.completed_by = getSecurityManager().getUser().getUserName()
Ejemplo n.º 59
0
 def available(self):
     root = aq_inner(self.context).getPhysicalRoot()
     sm = getSecurityManager()
     return sm.checkPermission(view_management_screens, root)
Ejemplo n.º 60
0
    def handleComment(self, action):
        context = aq_inner(self.context)

        # Check if conversation is enabled on this content object
        if not self.__parent__.restrictedTraverse(
                '@@conversation_view').enabled():
            raise Unauthorized("Discussion is not enabled for this content "
                               "object.")

        # Validation form
        data, errors = self.extractData()
        if errors:
            return

        # Validate Captcha
        registry = queryUtility(IRegistry)
        settings = registry.forInterface(IDiscussionSettings, check=False)
        portal_membership = getToolByName(self.context, 'portal_membership')
        captcha_enabled = settings.captcha != 'disabled'
        anonymous_comments = settings.anonymous_comments
        anon = portal_membership.isAnonymousUser()
        if captcha_enabled and anonymous_comments and anon:
            if not 'captcha' in data:
                data['captcha'] = u""
            captcha = CaptchaValidator(self.context, self.request, None,
                                       ICaptcha['captcha'], None)
            captcha.validate(data['captcha'])

        # some attributes are not always set
        author_name = u""

        # Create comment
        comment = createObject('plone.Comment')

        # Set comment mime type to current setting in the discussion registry
        comment.mime_type = settings.text_transform

        # Set comment attributes (including extended comment form attributes)
        for attribute in self.fields.keys():
            setattr(comment, attribute, data[attribute])
        # Make sure author_name is properly encoded
        if 'author_name' in data:
            author_name = data['author_name']
            if isinstance(author_name, str):
                author_name = unicode(author_name, 'utf-8')

        # Set comment author properties for anonymous users or members
        can_reply = getSecurityManager().checkPermission(
            'Reply to item', context)
        portal_membership = getToolByName(self.context, 'portal_membership')
        if anon and anonymous_comments:
            # Anonymous Users
            comment.author_name = author_name
            comment.author_email = u""
            comment.user_notification = None
            comment.creation_date = datetime.utcnow()
            comment.modification_date = datetime.utcnow()
        elif not portal_membership.isAnonymousUser() and can_reply:
            # Member
            member = portal_membership.getAuthenticatedMember()
            username = member.getUserName()
            email = member.getProperty('email')
            fullname = member.getProperty('fullname')
            if not fullname or fullname == '':
                fullname = member.getUserName()
            # memberdata is stored as utf-8 encoded strings
            elif isinstance(fullname, str):
                fullname = unicode(fullname, 'utf-8')
            if email and isinstance(email, str):
                email = unicode(email, 'utf-8')
            comment.creator = username
            comment.author_username = username
            comment.author_name = fullname
            comment.author_email = email
            comment.creation_date = datetime.utcnow()
            comment.modification_date = datetime.utcnow()
        else:  # pragma: no cover
            raise Unauthorized(
                u"Anonymous user tries to post a comment, but anonymous "
                u"commenting is disabled. Or user does not have the "
                u"'reply to item' permission.")

        # Add comment to conversation
        conversation = IConversation(self.__parent__)
        if data['in_reply_to']:
            # Add a reply to an existing comment
            conversation_to_reply_to = conversation.get(data['in_reply_to'])
            replies = IReplies(conversation_to_reply_to)
            comment_id = replies.addComment(comment)
        else:
            # Add a comment to the conversation
            comment_id = conversation.addComment(comment)

        # Redirect after form submit:
        # If a user posts a comment and moderation is enabled, a message is
        # shown to the user that his/her comment awaits moderation. If the user
        # has 'review comments' permission, he/she is redirected directly
        # to the comment.
        can_review = getSecurityManager().checkPermission(
            'Review comments', context)
        workflowTool = getToolByName(context, 'portal_workflow')
        comment_review_state = workflowTool.getInfoFor(comment, 'review_state',
                                                       None)
        if comment_review_state == 'pending' and not can_review:
            # Show info message when comment moderation is enabled
            IStatusMessage(self.context.REQUEST).addStatusMessage(
                _("Your comment awaits moderator approval."), type="info")
            self.request.response.redirect(self.action)
        else:
            # Redirect to comment (inside a content object page)
            self.request.response.redirect(self.action + '#' + str(comment_id))