コード例 #1
0
ファイル: CopySupport.py プロジェクト: ryan2858/erp5
  def manage_copyObjects(self, ids=None, uids=None, REQUEST=None, RESPONSE=None):
      """
        Put a reference to the objects named in ids in the clip board
      """
      #LOG("Manage Copy",0, "ids:%s uids:%s" % (str(ids), str(uids)))
      if ids is not None:
        # Use default methode
        return OriginalCopyContainer.manage_copyObjects(self, ids, REQUEST,
            RESPONSE)
      if uids is None and REQUEST is not None:
          return eNoItemsSpecified
      elif uids is None:
          raise ValueError, 'uids must be specified'

      if isinstance(uids, (str, int)):
          ids=[uids]
      oblist=[]
      for uid in uids:
          ob=self.getPortalObject().portal_catalog.getObject(uid)
          if not ob.cb_isCopyable():
              raise CopyError, eNotSupported % uid
          m=Moniker.Moniker(ob)
          oblist.append(m.dump())
      cp=(0, oblist)
      cp=_cb_encode(cp)
      if REQUEST is not None:
          resp=REQUEST['RESPONSE']
          resp.setCookie('__cp', cp, path='%s' % cookie_path(REQUEST))
          REQUEST['__cp'] = cp
          return self.manage_main(self, REQUEST)
      return cp
コード例 #2
0
    def _getSourceObjects(self, cb_copy_data, REQUEST):
        """get the source objects to link"""
        cp = None
        if cb_copy_data is not None:
            cp = cb_copy_data
        else:
            if REQUEST and REQUEST.has_key('__cp'):
                cp = REQUEST['__cp']
        if cp is None:
            raise CopyError(eNoData)

        try:
            cp = _cb_decode(cp)
        except Exception:
            raise CopyError(eInvalid)

        oblist = []
        app = self.getPhysicalRoot()

        for mdata in cp[1]:
            m = Moniker.loadMoniker(mdata)
            try:
                ob = m.bind(app)
            except Exception:
                raise CopyError(eNotFound)
            self._verifyObjectLink()
            oblist.append(ob)
        return oblist
コード例 #3
0
    def manage_cutObjects(self,
                          ids=None,
                          uids=None,
                          REQUEST=None,
                          RESPONSE=None):
        """ manage cutting objects, ie objects will be copied ans deleted

      """
        #LOG("Manage Copy",0, "ids:%s uids:%s" % (str(ids), str(uids)))
        if ids is not None:
            # Use default methode
            return OriginalCopyContainer.manage_cutObjects(self, ids, REQUEST)
        if uids is None and REQUEST is not None:
            return eNoItemsSpecified
        elif uids is None:
            raise ValueError('uids must be specified')

        if isinstance(uids, (str, int)):
            ids = [uids]
        oblist = []
        for uid in uids:
            ob = self.getPortalObject().portal_catalog.getObject(uid)
            if not ob.cb_isMoveable():
                raise CopyError(eNotSupported % id)
            m = Moniker.Moniker(ob)
            oblist.append(m.dump())
        cp = (1, oblist)  # 0->1 This is the difference with manage_copyObject
        cp = _cb_encode(cp)
        if REQUEST is not None:
            resp = REQUEST['RESPONSE']
            resp.setCookie('__cp', cp, path='%s' % cookie_path(REQUEST))
            REQUEST['__cp'] = cp
            return self.manage_main(self, REQUEST)
        return cp
コード例 #4
0
    def _getSourceObjects(self, cb_copy_data, REQUEST):
        """get the source objects to link"""
        cp = None
        if cb_copy_data is not None:
            cp = cb_copy_data
        else:
            if REQUEST and REQUEST.has_key("__cp"):
                cp = REQUEST["__cp"]
        if cp is None:
            raise CopyError, eNoData

        try:
            cp = _cb_decode(cp)
        except:
            raise CopyError, eInvalid

        oblist = []
        app = self.getPhysicalRoot()

        for mdata in cp[1]:
            m = Moniker.loadMoniker(mdata)
            try:
                ob = m.bind(app)
            except:
                raise CopyError, eNotFound
            self._verifyObjectLink()
            oblist.append(ob)
        return oblist
コード例 #5
0
    def fClipboardOperationAndElements(
        self,
        theModelDDvlPloneTool=None,
        theContextualElement=None,
    ):

        aRequest = theContextualElement.REQUEST
        if not aRequest:
            return (
                0,
                [],
            )

        if not aRequest.has_key(cClipboardCookieName):
            return (
                0,
                [],
            )

        aClipboard = aRequest[cClipboardCookieName]

        if aClipboard is None:
            return (
                0,
                [],
            )

        try:
            anOperation, someMonikerDatas = self.fClipboardDecode(
                aClipboard)  # _cb_decode(cp)
        except:
            return (
                0,
                [],
            )

        someObjects = []
        anApplication = theContextualElement.getPhysicalRoot()
        for aMonikerData in someMonikerDatas:
            aMoniker = Moniker.loadMoniker(aMonikerData)
            anObject = None
            try:
                anObject = aMoniker.bind(anApplication)
            except:
                None
            if not (anObject == None):
                someObjects.append(anObject)

        return (anOperation, someObjects)
コード例 #6
0
    def _get_clipboard_item(self):
        cp = self.request.get('__cp')
        op, mdatas = _cb_decode(cp)  # see OFS/CopySupport.py

        # just get the first item on the clipboard
        mdata = mdatas[0]
        m = Moniker.loadMoniker(mdata)

        app = self.context.getPhysicalRoot()
        try:
            ob = m.bind(app)
        except (ConflictError, AttributeError, KeyError, TypeError):
            return None

        return ob
コード例 #7
0
    def _get_clipboard_item(self):
        cp = self.request.get('__cp')
        op, mdatas = _cb_decode(cp) # see OFS/CopySupport.py

        # just get the first item on the clipboard
        mdata = mdatas[0]
        m = Moniker.loadMoniker(mdata)

        app = self.context.getPhysicalRoot()
        try:
            ob = m.bind(app)
        except (ConflictError, AttributeError, KeyError, TypeError):
            return None

        return ob
コード例 #8
0
    def _get_obs(self, cp):

        try:
            cp = _cb_decode(cp)
        except:
            standard.writeError(self, '[CopySupport._get_obs]: eInvalid')
            #raise CopyError, eInvalid

        oblist = []
        op = cp[0]
        app = self.getPhysicalRoot()

        for mdata in cp[1]:
            m = Moniker.loadMoniker(mdata)
            try:
                ob = m.bind(app)
            except:
                standard.writeError(self, '[CopySupport._get_obs]: eNotFound')
                #raise CopyError, eNotFound
            self._verifyObjectPaste(ob)
            oblist.append(ob)

        return oblist
コード例 #9
0
ファイル: CopySupport.py プロジェクト: ryan2858/erp5
 def __duplicate(self, cp, duplicate, is_indexable, reindex_kw, immediate_reindex):
   try:
     cp = _cb_decode(cp)
   except:
     raise CopyError(eInvalid)
   oblist = []
   op = cp[0]
   app = self.getPhysicalRoot()
   for mdata in cp[1]:
     m = Moniker.loadMoniker(mdata)
     try:
       ob = m.bind(app)
     except:
       raise CopyError(eNotFound)
     self._verifyObjectPaste(ob, validate_src=op + 1)
     oblist.append(ob)
   result = []
   def doMove(self, ob):
     aq_parent(aq_inner(ob))._delObject(ob.getId())
     return aq_base(ob)
   is_doable_id, notify_error, do_sanity_check, do, set_owner, is_clone = (
     ( # 0: Copy
       'cb_isCopyable',
       'Copy Error',
       lambda self, ob: True,
       lambda self, ob: ob._getCopy(self),
       1, # Take ownership.
       True,
     ),
     ( # 1: Move
       'cb_isMoveable',
       'Move Error',
       sanity_check,
       doMove,
       0, # Retain original ownership.
       False,
     ),
   )[op]
   for ob in oblist:
     if not getattr(ob, is_doable_id)():
       raise CopyError(eNotSupported % escape(ob.getId()))
     try:
       ob._notifyOfCopyTo(self, op=op)
     except:
       raise CopyError(MessageDialog(
         title=notify_error,
         message=sys.exc_info()[1],
         action='manage_main',
       ))
     if not do_sanity_check(self, ob):
       raise CopyError('This object cannot be pasted into itself')
     if not set_owner:
       # try to make ownership explicit so that it gets carried
       # along to the new location if needed.
       ob.manage_changeOwnershipType(explicit=1)
     new_ob = do(self, ob)
     orig_id = ob.getId()
     new_id = self._get_id(orig_id)
     result.append({'id': orig_id, 'new_id': new_id})
     new_ob._setId(new_id)
     if reindex_kw is not None:
       new_ob.setDefaultReindexParameterDict(reindex_kw)
     if is_indexable is not None and not is_indexable:
       new_ob._setNonIndexable()
     self._setObject(new_id, new_ob, set_owner=set_owner)
     new_ob = self._getOb(new_id)
     new_ob._postCopy(self, op=op)
     if is_clone:
       if duplicate:
         new_ob._postDuplicate()
       else:
         new_ob.manage_afterClone(new_ob)
       new_ob.wl_clearLocks()
     if not set_owner:
       # try to make ownership implicit if possible
       new_ob.manage_changeOwnershipType(explicit=0)
     method = new_ob.immediateReindexObject
     if reindex_kw is not None:
       method = partial(method, **reindex_kw)
     if isinstance(immediate_reindex, ImmediateReindexContextManager):
       immediate_reindex.append(method)
     elif immediate_reindex:
       # Immediately reindexing document that we just pasted is safe, as no
       # other transaction can by definition see it, so there cannot be a race
       # condition leading to stale catalog content.
       method()
   return op, result
コード例 #10
0
    def manage_pasteObjects(self,
                            cb_copy_data=None,
                            is_indexable=True,
                            REQUEST=None):
        """Paste previously copied objects into the current object.

    If calling manage_pasteObjects from python code, pass the result of a
    previous call to manage_cutObjects or manage_copyObjects as the first
    argument.

    If is_indexable is False, we will avoid indexing the pasted objects and
    subobjects
    """
        cp = None
        if cb_copy_data is not None:
            cp = cb_copy_data
        else:
            if REQUEST and REQUEST.has_key('__cp'):
                cp = REQUEST['__cp']
        if cp is None:
            raise CopyError, eNoData

        try:
            cp = _cb_decode(cp)
        except:
            raise CopyError, eInvalid

        oblist = []
        op = cp[0]
        app = self.getPhysicalRoot()
        result = []

        for mdata in cp[1]:
            m = Moniker.loadMoniker(mdata)
            try:
                ob = m.bind(app)
            except:
                raise CopyError, eNotFound
            self._verifyObjectPaste(ob, validate_src=op + 1)
            oblist.append(ob)

        if op == 0:
            # Copy operation
            for ob in oblist:
                if not ob.cb_isCopyable():
                    raise CopyError, eNotSupported % escape(ob.getId())
                try:
                    ob._notifyOfCopyTo(self, op=0)
                except:
                    raise CopyError, MessageDialog(title='Copy Error',
                                                   message=sys.exc_info()[1],
                                                   action='manage_main')
                ob = ob._getCopy(self)
                orig_id = ob.getId()
                id = self._get_id(ob.getId())
                result.append({'id': orig_id, 'new_id': id})
                ob._setId(id)
                if not is_indexable:
                    ob._setNonIndexable()
                self._setObject(id, ob)
                ob = self._getOb(id)
                ob._postCopy(self, op=0)
                ob.manage_afterClone(ob)
                ob.wl_clearLocks()

            if REQUEST is not None:
                return self.manage_main(self,
                                        REQUEST,
                                        update_menu=1,
                                        cb_dataValid=1)

        if op == 1:
            # Move operation
            for ob in oblist:
                id = ob.getId()
                if not ob.cb_isMoveable():
                    raise CopyError, eNotSupported % escape(id)
                try:
                    ob._notifyOfCopyTo(self, op=1)
                except:
                    raise CopyError, MessageDialog(title='Move Error',
                                                   message=sys.exc_info()[1],
                                                   action='manage_main')
                if not sanity_check(self, ob):
                    raise CopyError, 'This object cannot be pasted into itself'

                # try to make ownership explicit so that it gets carried
                # along to the new location if needed.
                ob.manage_changeOwnershipType(explicit=1)

                aq_parent(aq_inner(ob))._delObject(id)
                ob = aq_base(ob)
                orig_id = id
                id = self._get_id(id)
                result.append({'id': orig_id, 'new_id': id})

                ob._setId(id)
                if not is_indexable:
                    ob._setNonIndexable()
                self._setObject(id, ob, set_owner=0)
                ob = self._getOb(id)
                ob._postCopy(self, op=1)

                # try to make ownership implicit if possible
                ob.manage_changeOwnershipType(explicit=0)

            if REQUEST is not None:
                REQUEST['RESPONSE'].setCookie(
                    '__cp',
                    'deleted',
                    path='%s' % cookie_path(REQUEST),
                    expires='Wed, 31-Dec-97 23:59:59 GMT')
                REQUEST['__cp'] = None
                return self.manage_main(self,
                                        REQUEST,
                                        update_menu=1,
                                        cb_dataValid=0)
        return result
コード例 #11
0
    def _duplicate(self, cp):
        try:
            cp = _cb_decode(cp)
        except:
            raise CopyError, 'Clipboard Error'

        oblist = []
        op = cp[0]
        app = self.getPhysicalRoot()
        result = []

        for mdata in cp[1]:
            m = Moniker.loadMoniker(mdata)
            try:
                ob = m.bind(app)
            except:
                raise CopyError, 'Not Found'
            self._verifyObjectPaste(ob, validate_src=1)
            oblist.append(ob)

        if op == 0:
            for ob in oblist:
                if not ob.cb_isCopyable():
                    raise CopyError, 'Not Supported'
                try:
                    ob._notifyOfCopyTo(self, op=0)
                except:
                    raise CopyError, 'Copy Error'
                ob = ob._getCopy(self)
                orig_id = ob.getId()
                id = self._get_id(ob.getId())
                result.append({'id': orig_id, 'new_id': id})
                ob._setId(id)
                self._setObject(id, ob)
                ob = self._getOb(id)
                ob._postCopy(self, op=0)
                ob._postDuplicate()
                ob.wl_clearLocks()

        if op == 1:
            # Move operation
            for ob in oblist:
                id = ob.getId()
                if not ob.cb_isMoveable():
                    raise CopyError, 'Not Supported'
                try:
                    ob._notifyOfCopyTo(self, op=1)
                except:
                    raise CopyError, 'Move Error'
                if not sanity_check(self, ob):
                    raise CopyError, 'This object cannot be pasted into itself'

                # try to make ownership explicit so that it gets carried
                # along to the new location if needed.
                ob.manage_changeOwnershipType(explicit=1)

                aq_parent(aq_inner(ob))._delObject(id)
                ob = aq_base(ob)
                orig_id = id
                id = self._get_id(id)
                result.append({'id': orig_id, 'new_id': id})

                ob._setId(id)
                self._setObject(id, ob, set_owner=0)
                ob = self._getOb(id)
                ob._postCopy(self, op=1)

                # try to make ownership implicit if possible
                ob.manage_changeOwnershipType(explicit=0)

        return result
コード例 #12
0
  def manage_pasteObjects(self, cb_copy_data=None, is_indexable=True, REQUEST=None):
    """Paste previously copied objects into the current object.

    If calling manage_pasteObjects from python code, pass the result of a
    previous call to manage_cutObjects or manage_copyObjects as the first
    argument.

    If is_indexable is False, we will avoid indexing the pasted objects and
    subobjects
    """
    cp=None
    if cb_copy_data is not None:
      cp=cb_copy_data
    else:
      if REQUEST and REQUEST.has_key('__cp'):
        cp=REQUEST['__cp']
    if cp is None:
      raise CopyError, eNoData

    try:  cp=_cb_decode(cp)
    except: raise CopyError, eInvalid

    oblist=[]
    op=cp[0]
    app = self.getPhysicalRoot()
    result = []

    for mdata in cp[1]:
      m = Moniker.loadMoniker(mdata)
      try: ob = m.bind(app)
      except: raise CopyError, eNotFound
      self._verifyObjectPaste(ob, validate_src=op+1)
      oblist.append(ob)

    if op==0:
      # Copy operation
      for ob in oblist:
        if not ob.cb_isCopyable():
          raise CopyError, eNotSupported % escape(ob.getId())
        try:  ob._notifyOfCopyTo(self, op=0)
        except: raise CopyError, MessageDialog(
          title='Copy Error',
          message=sys.exc_info()[1],
          action ='manage_main')
        ob=ob._getCopy(self)
        orig_id=ob.getId()
        id=self._get_id(ob.getId())
        result.append({'id':orig_id, 'new_id':id})
        ob._setId(id)
        if not is_indexable:
          ob._setNonIndexable()
        self._setObject(id, ob)
        ob = self._getOb(id)
        ob._postCopy(self, op=0)
        ob.manage_afterClone(ob)
        ob.wl_clearLocks()

      if REQUEST is not None:
        return self.manage_main(self, REQUEST, update_menu=1,
                    cb_dataValid=1)

    if op==1:
      # Move operation
      for ob in oblist:
        id=ob.getId()
        if not ob.cb_isMoveable():
          raise CopyError, eNotSupported % escape(id)
        try:  ob._notifyOfCopyTo(self, op=1)
        except: raise CopyError, MessageDialog(
          title='Move Error',
          message=sys.exc_info()[1],
          action ='manage_main')
        if not sanity_check(self, ob):
          raise CopyError, 'This object cannot be pasted into itself'

        # try to make ownership explicit so that it gets carried
        # along to the new location if needed.
        ob.manage_changeOwnershipType(explicit=1)

        aq_parent(aq_inner(ob))._delObject(id)
        ob = aq_base(ob)
        orig_id=id
        id=self._get_id(id)
        result.append({'id':orig_id, 'new_id':id })

        ob._setId(id)
        if not is_indexable:
          ob._setNonIndexable()
        self._setObject(id, ob, set_owner=0)
        ob=self._getOb(id)
        ob._postCopy(self, op=1)

        # try to make ownership implicit if possible
        ob.manage_changeOwnershipType(explicit=0)

      if REQUEST is not None:
        REQUEST['RESPONSE'].setCookie('__cp', 'deleted',
                  path='%s' % cookie_path(REQUEST),
                  expires='Wed, 31-Dec-97 23:59:59 GMT')
        REQUEST['__cp'] = None
        return self.manage_main(self, REQUEST, update_menu=1,
                    cb_dataValid=0)
    return result
コード例 #13
0
  def _duplicate(self, cp):
    try:    cp = _cb_decode(cp)
    except: raise CopyError, 'Clipboard Error'

    oblist=[]
    op=cp[0]
    app = self.getPhysicalRoot()
    result = []

    for mdata in cp[1]:
      m = Moniker.loadMoniker(mdata)
      try: ob = m.bind(app)
      except: raise CopyError, 'Not Found'
      self._verifyObjectPaste(ob, validate_src=1)
      oblist.append(ob)

    if op==0:
      for ob in oblist:
        if not ob.cb_isCopyable():
            raise CopyError, 'Not Supported'
        try:    ob._notifyOfCopyTo(self, op=0)
        except: raise CopyError, 'Copy Error'
        ob = ob._getCopy(self)
        orig_id = ob.getId()
        id = self._get_id(ob.getId())
        result.append({'id':orig_id, 'new_id':id})
        ob._setId(id)
        self._setObject(id, ob)
        ob = self._getOb(id)
        ob._postCopy(self, op=0)
        ob._postDuplicate()
        ob.wl_clearLocks()

    if op==1:
      # Move operation
      for ob in oblist:
        id = ob.getId()
        if not ob.cb_isMoveable():
          raise CopyError, 'Not Supported'
        try:    ob._notifyOfCopyTo(self, op=1)
        except: raise CopyError, 'Move Error'
        if not sanity_check(self, ob):
          raise CopyError, 'This object cannot be pasted into itself'

        # try to make ownership explicit so that it gets carried
        # along to the new location if needed.
        ob.manage_changeOwnershipType(explicit=1)

        aq_parent(aq_inner(ob))._delObject(id)
        ob = aq_base(ob)
        orig_id = id
        id = self._get_id(id)
        result.append({'id':orig_id, 'new_id':id })

        ob._setId(id)
        self._setObject(id, ob, set_owner=0)
        ob = self._getOb(id)
        ob._postCopy(self, op=1)

        # try to make ownership implicit if possible
        ob.manage_changeOwnershipType(explicit=0)

    return result
コード例 #14
0
def paste_as_related_items(context, cb_copy_data=None, REQUEST=None,
                           fieldname='relatedItems'):
    """Paste previously copied objects into the current object as
    related items.

    Note that this is additive: no currently related items are removed.

    If calling this function from python code, pass the result of a
    previous call to OFS.manage_copyObjects as the first argument.

    Note that the results from a copy are accepted, not from a cut (move).

    This function is mostly a stripped down version of
    manage_pasteObjects from OFS.CopySupport.
    """
    if cb_copy_data is not None:
        cp = cb_copy_data
    elif REQUEST is not None and '__cp' in REQUEST.keys():
        cp = REQUEST['__cp']
    else:
        cp = None
    if cp is None:
        raise CopyError

    if not context.cb_dataValid:
        raise CopyError

    try:
        op, mdatas = _cb_decode(cp)
    except:
        raise CopyError

    if op != 0:
        # We only support pasting from a copy operation, not from a move/cut.
        raise CopyError
    oblist = []
    app = context.getPhysicalRoot()
    for mdata in mdatas:
        m = Moniker.loadMoniker(mdata)
        try:
            ob = m.bind(app)
        except ConflictError:
            raise
        except:
            raise CopyError
        oblist.append(ob)

    field = context.getField(fieldname)
    related = field.getRaw(context)
    new_ids = []
    for ob in oblist:
        uid = ob.UID()
        if uid not in related:
            related.append(uid)
            new_ids.append(ob.getId())

    if new_ids:
        field.set(context, related)

    # Report back
    return new_ids
コード例 #15
0
    def fGroupAction_CutOrCopy(self,
                               theTimeProfilingResults=None,
                               theModelDDvlPloneTool=None,
                               theModelDDvlPloneTool_Retrieval=None,
                               theContainerObject=None,
                               theGroupUIDs=[],
                               theReferenceFieldName=None,
                               theIsCut=False,
                               theAdditionalParams=None):
        """Prepare for Cut or Copy the elements given their UIDs, by setting a cookie in the HTTP request response including references ( monikers) for the selected elements, and whether the operation is a move (cut) or not (just copy).        

        """
        if not theModelDDvlPloneTool_Retrieval:
            return CopyError, 'Internal Parameter missing theModelDDvlPloneTool_Retrieval'

        if not theGroupUIDs:
            return self.fExceptionDialog_NoItemsSpecified(
                theModelDDvlPloneTool, theContainerObject)

        unasGroupUIDs = theGroupUIDs
        if not (unasGroupUIDs.__class__.__name__ in ['list', 'tuple', 'set']):
            unasGroupUIDs = [
                unasGroupUIDs,
            ]

        unosMonikers = []

        for unaUID in unasGroupUIDs:
            unElemento = theModelDDvlPloneTool_Retrieval.fElementoPorUID(
                unaUID, theContainerObject)
            if unElemento:

                if unElemento.wl_isLocked():
                    raise ResourceLockedError, 'Object "%s" is locked via WebDAV' % '/'.join(
                        unElemento.getPhysicalPath())

                if theIsCut and not unElemento.cb_isMoveable():
                    raise CopyError, self.fExceptionDialog_MoveNotSupported(
                        theModelDDvlPloneTool, theContainerObject)

                if (not theIsCut) and not unElemento.cb_isCopyable():
                    raise CopyError, self.fExceptionDialog_CopyNotSupported(
                        theModelDDvlPloneTool, theContainerObject)

                unMoniker = Moniker.Moniker(unElemento)

                unosMonikers.append(unMoniker.dump())

        if not unosMonikers:
            raise CopyError, self.fExceptionDialog_NoItemsCopied(
                theModelDDvlPloneTool, theContainerObject)

        unIsMoveClipboardParameter = (theIsCut and 1) or 0

        unClipBoardContent = (unIsMoveClipboardParameter, unosMonikers)

        unClipBoardCookieContent = self.fClipboardEncode(unClipBoardContent)

        aRequest = None
        try:
            aRequest = theContainerObject.REQUEST
        except:
            None
        if (aRequest == None):
            return True

        aResponse = aRequest.response
        if aResponse:
            aResponse.setCookie(cClipboardCookieName,
                                unClipBoardCookieContent,
                                path='%s' % self.fPathForCookie(aRequest))
        aRequest[cClipboardCookieName] = unClipBoardCookieContent

        return len(unosMonikers)
コード例 #16
0
ファイル: event.py プロジェクト: eea/ALiSS_agents
def manage_pasteObjects(self, cb_copy_data=None, REQUEST=None):
    """Paste previously copied objects into the current object.

    If calling manage_pasteObjects from python code, pass the result of a
    previous call to manage_cutObjects or manage_copyObjects as the first
    argument.

    Also sends IObjectCopiedEvent or IObjectMovedEvent.
    """
    if cb_copy_data is not None:
        cp = cb_copy_data
    elif REQUEST is not None and REQUEST.has_key('__cp'):
        cp = REQUEST['__cp']
    else:
        cp = None
    if cp is None:
        raise CopyError, eNoData

    try:
        op, mdatas = _cb_decode(cp)
    except:
        raise CopyError, eInvalid

    oblist = []
    app = self.getPhysicalRoot()
    for mdata in mdatas:
        m = Moniker.loadMoniker(mdata)
        try:
            ob = m.bind(app)
        except ConflictError:
            raise
        except:
            raise CopyError, eNotFound
        self._verifyObjectPaste(ob, validate_src=op+1)
        oblist.append(ob)

    result = []
    if op == 0:
        # Copy operation
        for ob in oblist:
            orig_id = ob.getId()
            if not ob.cb_isCopyable():
                raise CopyError, eNotSupported % escape(orig_id)

            try:
                ob._notifyOfCopyTo(self, op=0)
            except ConflictError:
                raise
            except:
                raise CopyError, MessageDialog(
                    title="Copy Error",
                    message=sys.exc_info()[1],
                    action='manage_main')

            id = self._get_id(orig_id)
            result.append({'id': orig_id, 'new_id': id})

            orig_ob = ob
            ob = ob._getCopy(self)
            ob._setId(id)
            notify(ObjectCopiedEvent(ob, orig_ob))

            self._setObject(id, ob)
            ob = self._getOb(id)
            ob.wl_clearLocks()

            ob._postCopy(self, op=0)

            compatibilityCall('manage_afterClone', ob, ob)

            notify(ObjectClonedEvent(ob))

        if REQUEST is not None:
            return self.manage_main(self, REQUEST, update_menu=1,
                                    cb_dataValid=1)

    elif op == 1:
        # Move operation
        for ob in oblist:
            orig_id = ob.getId()
            if not ob.cb_isMoveable():
                raise CopyError, eNotSupported % escape(orig_id)

            try:
                ob._notifyOfCopyTo(self, op=1)
            except ConflictError:
                raise
            except:
                raise CopyError, MessageDialog(
                    title="Move Error",
                    message=sys.exc_info()[1],
                    action='manage_main')

            if not sanity_check(self, ob):
                raise CopyError, "This object cannot be pasted into itself"

            orig_container = aq_parent(aq_inner(ob))
            if aq_base(orig_container) is aq_base(self):
                id = orig_id
            else:
                id = self._get_id(orig_id)
            result.append({'id': orig_id, 'new_id': id})

            notify(ObjectWillBeMovedEvent(ob, orig_container, orig_id,
                                          self, id))

            # try to make ownership explicit so that it gets carried
            # along to the new location if needed.
            ob.manage_changeOwnershipType(explicit=1)

            try:
                orig_container._delObject(orig_id, suppress_events=True)
            except TypeError:
                # BBB: removed in Zope 2.11
                orig_container._delObject(orig_id)
                warnings.warn(
                    "%s._delObject without suppress_events is deprecated "
                    "and will be removed in Zope 2.11." %
                    orig_container.__class__.__name__, DeprecationWarning)
            ob = aq_base(ob)
            ob._setId(id)

            try:
                self._setObject(id, ob, set_owner=0, suppress_events=True)
            except TypeError:
                # BBB: removed in Zope 2.11
                self._setObject(id, ob, set_owner=0)
                warnings.warn(
                    "%s._setObject without suppress_events is deprecated "
                    "and will be removed in Zope 2.11." %
                    self.__class__.__name__, DeprecationWarning)
            ob = self._getOb(id)

            notify(ObjectMovedEvent(ob, orig_container, orig_id, self, id))
            notifyContainerModified(orig_container)
            if aq_base(orig_container) is not aq_base(self):
                notifyContainerModified(self)

            ob._postCopy(self, op=1)
            # try to make ownership implicit if possible
            ob.manage_changeOwnershipType(explicit=0)

        if REQUEST is not None:
            REQUEST['RESPONSE'].setCookie('__cp', 'deleted',
                                path='%s' % cookie_path(REQUEST),
                                expires='Wed, 31-Dec-97 23:59:59 GMT')
            REQUEST['__cp'] = None
            return self.manage_main(self, REQUEST, update_menu=1,
                                    cb_dataValid=0)

    return result
コード例 #17
0
    def __duplicate(self, cp, duplicate, is_indexable, reindex_kw,
                    immediate_reindex):
        try:
            cp = _cb_decode(cp)
        except:
            raise CopyError(eInvalid)
        oblist = []
        op = cp[0]
        app = self.getPhysicalRoot()
        for mdata in cp[1]:
            m = Moniker.loadMoniker(mdata)
            try:
                ob = m.bind(app)
            except:
                raise CopyError(eNotFound)
            self._verifyObjectPaste(ob, validate_src=op + 1)
            oblist.append(ob)
        result = []

        def doMove(self, ob):
            aq_parent(aq_inner(ob))._delObject(ob.getId())
            return aq_base(ob)

        is_doable_id, notify_error, do_sanity_check, do, set_owner, is_clone = (
            (  # 0: Copy
                'cb_isCopyable',
                'Copy Error',
                lambda self, ob: True,
                lambda self, ob: ob._getCopy(self),
                1,  # Take ownership.
                True,
            ),
            (  # 1: Move
                'cb_isMoveable',
                'Move Error',
                sanity_check,
                doMove,
                0,  # Retain original ownership.
                False,
            ),
        )[op]
        for ob in oblist:
            if not getattr(ob, is_doable_id)():
                raise CopyError(eNotSupported % escape(ob.getId()))
            try:
                ob._notifyOfCopyTo(self, op=op)
            except:
                raise CopyError(
                    MessageDialog(
                        title=notify_error,
                        message=sys.exc_info()[1],
                        action='manage_main',
                    ))
            if not do_sanity_check(self, ob):
                raise CopyError('This object cannot be pasted into itself')
            if not set_owner:
                # try to make ownership explicit so that it gets carried
                # along to the new location if needed.
                ob.manage_changeOwnershipType(explicit=1)
            new_ob = do(self, ob)
            orig_id = ob.getId()
            new_id = self._get_id(orig_id)
            result.append({'id': orig_id, 'new_id': new_id})
            new_ob._setId(new_id)
            if reindex_kw is not None:
                new_ob.setDefaultReindexParameterDict(reindex_kw)
            if is_indexable is not None and not is_indexable:
                new_ob._setNonIndexable()
            if is_clone:
                # Clear uids before spawning indexation activities, so the activity does
                # not do an uid check (as the uid is still the old one, and a new one
                # will be allocated by _postDuplicate, which must run after object gets
                # a parent).
                # Note: do not use __recurse as it only iterates over immediate content,
                # and then stop instead of calling itself into them. It relies on called
                # methods to call it back, and we do not want that for _setUid .
                # Basically this block of code is for ERP5ish objects only.
                todo_list = [new_ob]
                while todo_list:
                    document = todo_list.pop()
                    todo_list.extend(document.objectValues())
                    opaqueValues = getattr(document, 'opaqueValues', None)
                    if opaqueValues is not None:
                        todo_list.extend(opaqueValues())
                    _setUid = getattr(document, '_setUid', None)
                    if _setUid is not None:
                        _setUid(None)
            self._setObject(new_id, new_ob, set_owner=set_owner)
            new_ob = self._getOb(new_id)
            new_ob._postCopy(self, op=op)
            if is_clone:
                if duplicate:
                    new_ob._postDuplicate()
                else:
                    new_ob.manage_afterClone(new_ob)
                new_ob.wl_clearLocks()
            if not set_owner:
                # try to make ownership implicit if possible
                new_ob.manage_changeOwnershipType(explicit=0)
            method = new_ob.immediateReindexObject
            if reindex_kw is not None:
                method = partial(method, **reindex_kw)
            if isinstance(immediate_reindex, ImmediateReindexContextManager):
                immediate_reindex.append(method)
            elif immediate_reindex:
                # Immediately reindexing document that we just pasted is safe, as no
                # other transaction can by definition see it, so there cannot be a race
                # condition leading to stale catalog content.
                method()
        return op, result
コード例 #18
0
ファイル: event.py プロジェクト: bendavis78/zope
def manage_pasteObjects(self, cb_copy_data=None, REQUEST=None):
    """Paste previously copied objects into the current object.

    If calling manage_pasteObjects from python code, pass the result of a
    previous call to manage_cutObjects or manage_copyObjects as the first
    argument.

    Also sends IObjectCopiedEvent or IObjectMovedEvent.
    """
    if cb_copy_data is not None:
        cp = cb_copy_data
    elif REQUEST is not None and REQUEST.has_key('__cp'):
        cp = REQUEST['__cp']
    else:
        cp = None
    if cp is None:
        raise CopyError, eNoData

    try:
        op, mdatas = _cb_decode(cp)
    except:
        raise CopyError, eInvalid

    oblist = []
    app = self.getPhysicalRoot()
    for mdata in mdatas:
        m = Moniker.loadMoniker(mdata)
        try:
            ob = m.bind(app)
        except ConflictError:
            raise
        except:
            raise CopyError, eNotFound
        self._verifyObjectPaste(ob, validate_src=op + 1)
        oblist.append(ob)

    result = []
    if op == 0:
        # Copy operation
        for ob in oblist:
            orig_id = ob.getId()
            if not ob.cb_isCopyable():
                raise CopyError, eNotSupported % escape(orig_id)

            try:
                ob._notifyOfCopyTo(self, op=0)
            except ConflictError:
                raise
            except:
                raise CopyError, MessageDialog(title="Copy Error",
                                               message=sys.exc_info()[1],
                                               action='manage_main')

            id = self._get_id(orig_id)
            result.append({'id': orig_id, 'new_id': id})

            orig_ob = ob
            ob = ob._getCopy(self)
            ob._setId(id)
            notify(ObjectCopiedEvent(ob, orig_ob))

            self._setObject(id, ob)
            ob = self._getOb(id)
            ob.wl_clearLocks()

            ob._postCopy(self, op=0)

            compatibilityCall('manage_afterClone', ob, ob)

            notify(ObjectClonedEvent(ob))

        if REQUEST is not None:
            return self.manage_main(self,
                                    REQUEST,
                                    update_menu=1,
                                    cb_dataValid=1)

    elif op == 1:
        # Move operation
        for ob in oblist:
            orig_id = ob.getId()
            if not ob.cb_isMoveable():
                raise CopyError, eNotSupported % escape(orig_id)

            try:
                ob._notifyOfCopyTo(self, op=1)
            except ConflictError:
                raise
            except:
                raise CopyError, MessageDialog(title="Move Error",
                                               message=sys.exc_info()[1],
                                               action='manage_main')

            if not sanity_check(self, ob):
                raise CopyError, "This object cannot be pasted into itself"

            orig_container = aq_parent(aq_inner(ob))
            if aq_base(orig_container) is aq_base(self):
                id = orig_id
            else:
                id = self._get_id(orig_id)
            result.append({'id': orig_id, 'new_id': id})

            notify(
                ObjectWillBeMovedEvent(ob, orig_container, orig_id, self, id))

            # try to make ownership explicit so that it gets carried
            # along to the new location if needed.
            ob.manage_changeOwnershipType(explicit=1)

            try:
                orig_container._delObject(orig_id, suppress_events=True)
            except TypeError:
                # BBB: removed in Zope 2.11
                orig_container._delObject(orig_id)
                warnings.warn(
                    "%s._delObject without suppress_events is deprecated "
                    "and will be removed in Zope 2.11." %
                    orig_container.__class__.__name__, DeprecationWarning)
            ob = aq_base(ob)
            ob._setId(id)

            try:
                self._setObject(id, ob, set_owner=0, suppress_events=True)
            except TypeError:
                # BBB: removed in Zope 2.11
                self._setObject(id, ob, set_owner=0)
                warnings.warn(
                    "%s._setObject without suppress_events is deprecated "
                    "and will be removed in Zope 2.11." %
                    self.__class__.__name__, DeprecationWarning)
            ob = self._getOb(id)

            notify(ObjectMovedEvent(ob, orig_container, orig_id, self, id))
            notifyContainerModified(orig_container)
            if aq_base(orig_container) is not aq_base(self):
                notifyContainerModified(self)

            ob._postCopy(self, op=1)
            # try to make ownership implicit if possible
            ob.manage_changeOwnershipType(explicit=0)

        if REQUEST is not None:
            REQUEST['RESPONSE'].setCookie(
                '__cp',
                'deleted',
                path='%s' % cookie_path(REQUEST),
                expires='Wed, 31-Dec-97 23:59:59 GMT')
            REQUEST['__cp'] = None
            return self.manage_main(self,
                                    REQUEST,
                                    update_menu=1,
                                    cb_dataValid=0)

    return result