def test_after_checkout(self):
        working_copy = self.do_checkout()
        self.assertTrue(working_copy)
        self.assertTrue(IIterateAware.providedBy(working_copy))
        self.assertFalse(IBaseline.providedBy(working_copy))
        self.assertTrue(IWorkingCopy.providedBy(working_copy))

        self.assertTrue(IIterateAware.providedBy(self.obj))
        self.assertTrue(IBaseline.providedBy(self.obj))
        self.assertFalse(IWorkingCopy.providedBy(self.obj))
Beispiel #2
0
    def test_after_checkout(self):
        working_copy = self.do_checkout()
        self.assertTrue(working_copy)
        self.assertTrue(IIterateAware.providedBy(working_copy))
        self.assertFalse(IBaseline.providedBy(working_copy))
        self.assertTrue(IWorkingCopy.providedBy(working_copy))

        self.assertTrue(IIterateAware.providedBy(self.obj))
        self.assertTrue(IBaseline.providedBy(self.obj))
        self.assertFalse(IWorkingCopy.providedBy(self.obj))
Beispiel #3
0
    def checkin_allowed(self):
        """ Overrided to check for the checkin permission, as it should be normal
        """

        context = aq_inner(self.context)
        checkPermission = getSecurityManager().checkPermission

        if not IIterateAware.providedBy(context):
            return False

        archiver = IObjectArchiver(context)
        if not archiver.isVersionable():
            return False

        if not IWorkingCopy.providedBy(context):
            return False

        policy = ICheckinCheckoutPolicy(context, None)
        if policy is None:
            return False

        try:
            original = policy.getBaseline()
        except:
            return False
        if original is None:
            return False

        checkPermission = getSecurityManager().checkPermission
        if not checkPermission(CheckinPermission, original):
            return False

        return True
def notifyDocumentIsAdded(document, event):
    context = aq_inner(document)
    folder = aq_parent(context)
    if IWorkingCopy.providedBy(context):
       return
    else:
       folder.setDefaultPage(getattr(document,"id"))
Beispiel #5
0
    def checkin_allowed(self):
        """Check if a checkin is allowed
        """
        context = aq_inner(self.context)
        checkPermission = getSecurityManager().checkPermission

        if not interfaces.IIterateAware.providedBy(context):
            return False

        archiver = interfaces.IObjectArchiver(context)
        if not archiver.isVersionable():
            return False

        if not IWorkingCopy.providedBy(context):
            return False

        policy = ICheckinCheckoutPolicy(context, None)
        if policy is None:
            return False

        original = policy.getBaseline()
        if original is None:
            return False

        can_modify = checkPermission(
            Products.CMFCore.permissions.ModifyPortalContent,
            original,
        )
        if not can_modify:
            return False

        return True
Beispiel #6
0
 def __init__( self, context, request ):
     self.context = context
     self.request = request
     if IBaseline.providedBy( self.context ):
         self.baseline = context
         self.working_copy = context.getBackReferences( WorkingCopyRelation.relationship )[0]
     elif IWorkingCopy.providedBy( self.context ):
         self.working_copy = context
         self.baseline = context.getReferences( WorkingCopyRelation.relationship )[0]
     else:
         raise AttributeError("Invalid Context")
 def __init__( self, context, request ):
     self.context = context
     self.request = request
     if IBaseline.providedBy( self.context ):
         self.baseline = context
         self.working_copy = get_working_copy(context)
     elif IWorkingCopy.providedBy( self.context ):
         self.working_copy = context
         self.baseline = get_baseline(context)
     else:
         raise AttributeError("Invalid Context")
Beispiel #8
0
 def __call__(self):
     policy = ICheckinCheckoutPolicy(self.context)
     if IBaseline.providedBy(self.context):
         self.baseline = self.context
         self.working_copy = policy.getWorkingCopy()
     elif IWorkingCopy.providedBy(self.context):
         self.working_copy = self.context
         self.baseline = policy.getBaseline()
     else:
         raise AttributeError('Invalid Context')
     return self.index()
Beispiel #9
0
def handle_ObjectStateModified(site, uid):
    """ Handle when a CaseStudy is published / unpublished

    If published:
        * if this is a working copy, abort
        * check if object already exists in ArcGIS
            * if doesn't exist, add one
            * if exists, update the existing one
    If unpublished:
        * if this is a working copy, abort
        * check if object exists in ArcGIS
            * if exists, remove it
    """
    obj = _get_obj_by_measure_id(site, uid)
    if IWorkingCopy.providedBy(obj):
        logger.debug("Skipping CaseStudy status change processing")
        return

    state = get_state(obj)

    token = get_auth_token()
    fid = _get_obj_FID(obj=obj, token=token)

    if (state != 'published') and fid:
        # it's unpublished, we'll remove the object
        logger.info("ArcGIS: Deleting CaseStudy with FID %s", fid)

        res = apply_edits(fid, op='deletes', token=token)

        assert res['deleteResults']
        assert res['deleteResults'][0]['objectId'] == fid
        return

    if state == "published":
        repr = obj._repr_for_arcgis()

        # new case study, add it to ArcGIS
        if fid is None:
            logger.info("ArcGIS: Adding CaseStudy with measure id %s", uid)
            entry = json.dumps([repr])
            res = apply_edits(entry, op='adds', token=token)
            assert len(res.get('addResults', [])) == 1
            assert res['addResults'][0]['success'] == True

        # existing case study, sync its info
        else:
            logger.info("ArcGIS: Updating CaseStudy with FID %s", fid)

            repr['attributes']['FID'] = fid
            entry = json.dumps([repr])
            res = apply_edits(entry, op='updates', token=token)

            assert res['updateResults']
            assert res['updateResults'][0]['objectId'] == fid
Beispiel #10
0
 def __init__( self, context, request ):
     self.context = context
     self.request = request
     if HAS_STAGINGBEHAVIOR and IIterateAware.providedBy(context):
         if IBaseline.providedBy( self.context ):
             self.baseline = get_baseline(context)
             self.working_copy = get_working_copy(context)
         elif IWorkingCopy.providedBy( self.context ):
             self.working_copy = get_working_copy(context)
             self.baseline = get_baseline(context)
         else:
             raise AttributeError("Invalid Context")
     else:
         if IBaseline.providedBy( self.context ):
             self.baseline = context
             self.working_copy = context.getBackReferences( WorkingCopyRelation.relationship )[0]
         elif IWorkingCopy.providedBy( self.context ):
             self.working_copy = context
             self.baseline = context.getReferences( WorkingCopyRelation.relationship )[0]
         else:
             raise AttributeError("Invalid Context")
def checkInIfNeeded(document, event):
    context = aq_inner(document)
    workflowTool = getToolByName(context, "portal_workflow")
    status = workflowTool.getStatusOf("1MX_wiki_workflow", document)
    if IWorkingCopy.providedBy(context) and status["review_state"] == "internally_published":
       policy = ICheckinCheckoutPolicy(context)
       baseline = policy.checkin("")
       IStatusMessage(context.REQUEST).addStatusMessage(
            _("Checked in"), type='info')
       view_url = baseline.unrestrictedTraverse("@@plone_context_state").view_url()
       transaction.commit()
       raise Redirect(view_url)
Beispiel #12
0
    def is_checkout(self):
        """ Is this object a checkout? Used by WISE for workflow guards
        """
        context = aq_inner(self.context)

        if not IIterateAware.providedBy(context):
            return False

        archiver = IObjectArchiver(context)
        if not archiver.isVersionable():
            return False

        if IWorkingCopy.providedBy(context):
            return True

        return False
Beispiel #13
0
def handle_ObjectStateModified(site, uid):
    """ Handle when a CaseStudy is published / unpublished

    If published:
        * if this is a working copy, abort
        * check if object already exists in ArcGIS
            * if doesn't exist, add one
            * if exists, update the existing one
    If unpublished:
        * if this is a working copy, abort
        * check if object exists in ArcGIS
            * if exists, remove it
    """
    obj = _get_obj_by_measure_id(site, uid)

    if IWorkingCopy.providedBy(obj):
        logger.debug("Skipping CaseStudy status change processing")

        return

    state = get_state(obj)

    try:
        token = get_auth_token()
    except KeyError:
        logger.exception("Could not get an Arcgis auth token")

        return

    fid = _get_obj_OBJECTID(obj=obj, token=token)

    if (state != 'published') and fid:
        # it's unpublished, we'll remove the object
        logger.info("ArcGIS: Deleting CaseStudy with OBJECTID %s", fid)

        res = apply_edits(fid, op='deletes', token=token)

        assert res['deleteResults']
        assert res['deleteResults'][0]['objectId'] == fid

        return

    if state == "published":
        repr = obj._repr_for_arcgis()

        # new case study, add it to ArcGIS

        if fid is None:
            logger.info("ArcGIS: Adding CaseStudy with measure id %s", uid)
            entry = json.dumps([repr])
            res = apply_edits(entry, op='adds', token=token)
            assert len(res.get('addResults', [])) == 1
            assert res['addResults'][0]['success'] is True

        # existing case study, sync its info
        else:
            logger.info("ArcGIS: Updating CaseStudy with OBJECTID %s", fid)

            repr['attributes']['OBJECTID'] = fid
            entry = json.dumps([repr])
            res = apply_edits(entry, op='updates', token=token)

            assert res['updateResults']
            assert res['updateResults'][0]['objectId'] == fid
Beispiel #14
0
 def __call__(self):
     return IWorkingCopy.providedBy(self.context)
Beispiel #15
0
 def test_before_checkout(self):
     self.assertTrue(self.obj)
     self.assertTrue(IIterateAware.providedBy(self.obj))
     self.assertFalse(IBaseline.providedBy(self.obj))
     self.assertFalse(IWorkingCopy.providedBy(self.obj))
 def test_before_checkout(self):
     self.assertTrue(self.obj)
     self.assertTrue(IIterateAware.providedBy(self.obj))
     self.assertFalse(IBaseline.providedBy(self.obj))
     self.assertFalse(IWorkingCopy.providedBy(self.obj))
Beispiel #17
0
    def __call__(self):
        req = getRequest()
        if req.environ.get('disable.auditlog', False):
            return True

        event = self.event
        obj = event.object
        # order of those checks is important since some interfaces
        # base off the others
        rule = inspect.stack()[1][0].f_locals.get('self', None)
        registry = getUtility(IRegistry)
        trackWorkingCopies = registry['collective.auditlog.interfaces.IAuditLogSettings.trackworkingcopies']  # noqa

        if not self.canExecute(rule, req):
            return True  # cut out early, we can't do this event

        data = {
            'info': ''
        }

        if IPloneFormGenField.providedBy(obj):
            # if ploneformgen field, use parent object for modified data
            data['field'] = obj.getId()
            obj = aq_parent(obj)

        # the order of those interface checks matters since some interfaces
        # inherit from others
        if IObjectRemovedEvent.providedBy(event):
            # need to keep track of removed events so it doesn't get called
            # more than once for each object
            action = 'removed'
        elif (IObjectInitializedEvent.providedBy(event) or
                IObjectCreatedEvent.providedBy(event) or
                IObjectAddedEvent.providedBy(event)):
            action = 'added'
        elif IObjectMovedEvent.providedBy(event):
            # moves can also be renames. Check the parent object
            if event.oldParent == event.newParent:
                if rule is None or 'Rename' in rule.rule.title:
                    info = {'previous_id': event.oldName}
                    data['info'] = json.dumps(info)
                    action = 'rename'
                else:
                    # cut out here, double action for this event
                    return True
            else:
                if rule is None or 'Moved' in rule.rule.title:
                    parent_path = '/'.join(event.oldParent.getPhysicalPath())
                    previous_location = parent_path + '/' + event.oldName
                    info = {'previous_location': previous_location}
                    data['info'] = json.dumps(info)
                    action = 'moved'
                else:
                    # step out immediately since this could be a double action
                    return True
        elif IObjectModifiedEvent.providedBy(event):
            action = 'modified'
        elif IActionSucceededEvent.providedBy(event):
            info = {'transition': event.action,
                    'comments': self.get_history_comment()}
            data['info'] = json.dumps(info)
            action = 'workflow'
        elif IObjectClonedEvent.providedBy(event):
            action = 'copied'
        elif ICheckinEvent.providedBy(event):
            info = {'message': event.message}
            data['info'] = json.dumps(info)
            action = 'checked in'
            req.environ['disable.auditlog'] = True
            data['working_copy'] = '/'.join(obj.getPhysicalPath())
            obj = event.baseline
        elif IBeforeCheckoutEvent.providedBy(event):
            action = 'checked out'
            req.environ['disable.auditlog'] = True
        elif ICancelCheckoutEvent.providedBy(event):
            action = 'cancel check out'
            req.environ['disable.auditlog'] = True
            data['working_copy'] = '/'.join(obj.getPhysicalPath())
            obj = event.baseline
        elif IUserLoggedInEvent.providedBy(event):
            action = 'logged in'
            info = {'user': event.object.getUserName()}
            data['info'] = json.dumps(info)
        elif IUserLoggedOutEvent.providedBy(event):
            action = 'logged out'
        else:
            logger.warn('no action matched')
            return True

        if IWorkingCopy.providedBy(obj):
            # if working copy, iterate, check if Track Working Copies is
            # enabled
            if trackWorkingCopies:
                # if enabled in control panel, use original object and move
                # working copy path to working_copy
                data['working_copy'] = '/'.join(obj.getPhysicalPath())
                relationships = obj.getReferences(
                    WorkingCopyRelation.relationship)
                # check relationships, if none, something is wrong, not logging
                # action
                if len(relationships) > 0:
                    obj = relationships[0]
                else:
                    return True
            else:
                # if not enabled, we only care about checked messages
                if 'check' not in action:
                    return True

        data.update(getObjectInfo(obj))
        data['action'] = action

        addLogEntry(obj, data)
        return True
    def getLogEntry(self):
        ''' Get's a log entry for your action
        '''
        event = self.event
        obj = event.object
        data = {'info': ''}

        # order of those checks is important since some interfaces
        # base off the others
        if IPloneFormGenField.providedBy(obj):
            # if ploneformgen field, use parent object for modified data
            data['field'] = obj.getId()
            obj = aq_parent(obj)

        # the order of those interface checks matters since some interfaces
        # inherit from others
        if IObjectRemovedEvent.providedBy(event):
            # need to keep track of removed events so it doesn't get called
            # more than once for each object
            action = 'removed'
        elif (IObjectInitializedEvent.providedBy(event)
              or IObjectCreatedEvent.providedBy(event)
              or IObjectAddedEvent.providedBy(event)):
            action = 'added'
        elif IObjectMovedEvent.providedBy(event):
            # moves can also be renames. Check the parent object
            if event.oldParent == event.newParent:
                if 'Rename' not in self.rule.rule.title:
                    # cut out here, double action for this event
                    return {}
                data['info'] = 'previous id: %s' % event.oldName
                action = 'rename'
            else:
                if 'Moved' not in self.rule.rule.title:
                    # step out immediately since this could be a double action
                    return {}
                data['info'] = 'previous location: %s/%s' % (
                    '/'.join(event.oldParent.getPhysicalPath()),
                    event.oldName,
                )
                action = 'moved'
        elif IObjectModifiedEvent.providedBy(event):
            action = 'modified'
        elif IActionSucceededEvent.providedBy(event):
            data['info'] = 'workflow transition: %s; comments: %s' % (
                event.action,
                self.get_history_comment(),
            )
            action = 'workflow'
        elif IObjectClonedEvent.providedBy(event):
            action = 'copied'
        elif ICheckinEvent.providedBy(event):
            data['info'] = event.message
            action = 'checked in'
            self.request.environ['disable.auditlog'] = True
            data['working_copy'] = '/'.join(obj.getPhysicalPath())
            obj = event.baseline
        elif IBeforeCheckoutEvent.providedBy(event):
            action = 'checked out'
            self.request.environ['disable.auditlog'] = True
        elif ICancelCheckoutEvent.providedBy(event):
            action = 'cancel check out'
            self.request.environ['disable.auditlog'] = True
            data['working_copy'] = '/'.join(obj.getPhysicalPath())
            obj = event.baseline
        else:
            logger.warn('no action matched')
            return {}

        if IWorkingCopy.providedBy(obj):
            # if working copy, iterate, check if Track Working Copies is
            # enabled
            if not self.trackWorkingCopies:
                # if not enabled, we only care about checked messages
                if 'check' not in action:
                    return {}
            # if enabled in control panel, use original object and move
            # working copy path to working_copy
            data['working_copy'] = '/'.join(obj.getPhysicalPath())
            relationships = obj.getReferences(WorkingCopyRelation.relationship)
            # check relationships, if none, something is wrong, not logging
            # action
            if len(relationships) <= 0:
                return {}
            obj = relationships[0]

        data.update(self._getObjectInfo(obj))
        data['action'] = action
        return data
Beispiel #19
0
 def render(self):
     if IWorkingCopy.providedBy(self.context):
         return info.CheckoutInfoViewlet.render(self)
     return ''
 def render(self):
     if IWorkingCopy.providedBy(self.context):
         return info.CheckoutInfoViewlet.render(self)
     return ""
    def getLogEntry(self):
        ''' Get's a log entry for your action
        '''
        event = self.event
        obj = event.object
        data = {'info': ''}

        # order of those checks is important since some interfaces
        # base off the others
        if IPloneFormGenField.providedBy(obj):
            # if ploneformgen field, use parent object for modified data
            data['field'] = obj.getId()
            obj = aq_parent(obj)

        # the order of those interface checks matters since some interfaces
        # inherit from others
        if IObjectRemovedEvent.providedBy(event):
            # need to keep track of removed events so it doesn't get called
            # more than once for each object
            action = 'removed'
        elif (
            IObjectInitializedEvent.providedBy(event) or
            IObjectCreatedEvent.providedBy(event) or
            IObjectAddedEvent.providedBy(event)
        ):
            action = 'added'
        elif IObjectMovedEvent.providedBy(event):
            # moves can also be renames. Check the parent object
            if event.oldParent == event.newParent:
                if 'Rename' not in self.rule.rule.title:
                    # cut out here, double action for this event
                    return {}
                data['info'] = 'previous id: %s' % event.oldName
                action = 'rename'
            else:
                if 'Moved' not in self.rule.rule.title:
                    # step out immediately since this could be a double action
                    return {}
                data['info'] = 'previous location: %s/%s' % (
                    '/'.join(event.oldParent.getPhysicalPath()),
                    event.oldName,
                )
                action = 'moved'
        elif IObjectModifiedEvent.providedBy(event):
            action = 'modified'
        elif IActionSucceededEvent.providedBy(event):
            data['info'] = 'workflow transition: %s; comments: %s' % (
                event.action,
                self.get_history_comment(),
            )
            action = 'workflow'
        elif IObjectClonedEvent.providedBy(event):
            action = 'copied'
        elif ICheckinEvent.providedBy(event):
            data['info'] = event.message
            action = 'checked in'
            self.request.environ['disable.auditlog'] = True
            data['working_copy'] = '/'.join(obj.getPhysicalPath())
            obj = event.baseline
        elif IBeforeCheckoutEvent.providedBy(event):
            action = 'checked out'
            self.request.environ['disable.auditlog'] = True
        elif ICancelCheckoutEvent.providedBy(event):
            action = 'cancel check out'
            self.request.environ['disable.auditlog'] = True
            data['working_copy'] = '/'.join(obj.getPhysicalPath())
            obj = event.baseline
        else:
            logger.warn('no action matched')
            return {}

        if IWorkingCopy.providedBy(obj):
            # if working copy, iterate, check if Track Working Copies is
            # enabled
            if not self.trackWorkingCopies:
                # if not enabled, we only care about checked messages
                if 'check' not in action:
                    return {}
            # if enabled in control panel, use original object and move
            # working copy path to working_copy
            data['working_copy'] = '/'.join(obj.getPhysicalPath())
            relationships = obj.getReferences(
                WorkingCopyRelation.relationship)
            # check relationships, if none, something is wrong, not logging
            # action
            if len(relationships) <= 0:
                return {}
            obj = relationships[0]

        data.update(self._getObjectInfo(obj))
        data['action'] = action
        return data