示例#1
0
文件: tool.py 项目: goschtl/zope
 def useClipboard(self, func, REQUEST,
                  source_paths=None, target_path=None, target_index=None):
     """Clipboard interaction.
     """
     resp = REQUEST['RESPONSE']
     if func in ("cut", "copy"):
         assert source_paths
         items = []  # list of path tuples
         cut = (func == 'cut')
         for p in str(source_paths).split(':'):
             items.append(p.split('/'))
         data = _cb_encode((cut, items))
         resp.setCookie('__cp', data, path=cookie_path(REQUEST))
     elif func == 'paste':
         assert target_path
         assert target_index
         assert REQUEST is not None
         data = REQUEST['__cp']
         cut, items = _cb_decode(data)
         self.moveElements(
             items, target_path, int(target_index), not cut)
         resp.expireCookie('__cp', path=cookie_path(REQUEST))
     else:
         raise ValueError("Clipboard function %s unknown" % func)
     resp.redirect(REQUEST["HTTP_REFERER"])
示例#2
0
 def useClipboard(self,
                  func,
                  REQUEST,
                  source_paths=None,
                  target_path=None,
                  target_index=None):
     """Clipboard interaction.
     """
     resp = REQUEST['RESPONSE']
     if func in ("cut", "copy"):
         assert source_paths
         items = []  # list of path tuples
         cut = (func == 'cut')
         for p in str(source_paths).split(':'):
             items.append(p.split('/'))
         data = _cb_encode((cut, items))
         resp.setCookie('__cp', data, path=cookie_path(REQUEST))
     elif func == 'paste':
         assert target_path
         assert target_index
         assert REQUEST is not None
         data = REQUEST['__cp']
         cut, items = _cb_decode(data)
         self.moveElements(items, target_path, int(target_index), not cut)
         resp.expireCookie('__cp', path=cookie_path(REQUEST))
     else:
         raise ValueError("Clipboard function %s unknown" % func)
     resp.redirect(REQUEST["HTTP_REFERER"])
示例#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 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
 def handleCopySupport(self, form, container):
     "handle the copy and paste stuff"
     if form.pop('cut',None) and 'ids' in form and self.allowAddRemove:
         cp = container.manage_cutObjects(form['ids'])
         resp=self.REQUEST.RESPONSE
         resp.setCookie('__cp', cp, path='%s' % cookie_path(self.REQUEST))
         self.REQUEST['__cp'] = cp
     
     if form.pop('copy',None) and 'ids' in form:
         cp = container.manage_copyObjects(form['ids'])
         resp=self.REQUEST.RESPONSE
         resp.setCookie('__cp', cp, path='%s' % cookie_path(self.REQUEST))
         self.REQUEST['__cp'] = cp
     
     if form.pop('paste',None) and self.allowAddRemove and self.cb_dataValid(): #part of CopySupport
         container.manage_pasteObjects(self.REQUEST['__cp'])
示例#6
0
  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
示例#7
0
    def __call__(self):
        request = self.request
        obj_list = []
        for obj in self.items:
            if obj and obj.cb_isCopyable():
                m = Moniker(obj)
                obj_list.append(m.dump())
        # now store copydata into a cookie
        # TODO: what if there's nothing in the list?
        cp_data = (0, obj_list)
        cp_data = _cb_encode(cp_data)  # probably means "clipboard encode"?

        response = request.response
        path = '{0}'.format(cookie_path(request))
        response.setCookie('__cp', cp_data, path=path)
        request['__cp'] = cp_data

        msg = _(
            u"batch_copied_success",
            default=u"${num_elems} Files were copied to your cloud clipboard.",
            mapping={"num_elems": len(obj_list)})
        api.portal.show_message(
            message=msg,
            request=request,
            type="info",
        )
        return self.index()
示例#8
0
 def finish(self):
     oblist = []
     for ob in self.oblist:
         if ob.wl_isLocked():
             self.errors.append(
                 _(u'${title} is being edited and cannot be cut.',
                   mapping={u'title': self.objectTitle(ob)}))
             continue
         if not ob.cb_isMoveable():
             self.errors.append(
                 _(u'${title} is being edited and can not be cut.',
                   mapping={u'title': self.objectTitle(ob)}))
             continue
         m = Moniker(ob)
         oblist.append(m.dump())
     if len(oblist) > 20 and cache.redis_installed():
         cache_key = str(uuid4())
         cache.set(cache_key, oblist, expire=60 * 60 * 24)
         cp = (1, [['cache:' + cache_key]])
     else:
         cp = (1, oblist)
     cp = _cb_encode(cp)
     resp = self.request.response
     resp.setCookie('__cp', cp, path='%s' % cookie_path(self.request))
     self.request['__cp'] = cp
示例#9
0
    def __call__(self):
        """Cut all items currently in cart and add them to clipboard.

        The tricky part here is that the method that Plone uses
        (manage_cutObjects) was only ment to work on objects of the same
        parent. However, our use case allows cutting objects of different
        parents. Hence we need to go one level deeper and reimplement some
        stuff that manage_cutObjects does in our own way.

        """

        request = self.request
        obj_list = []
        cannot_cut = []
        for obj in self.items:
            if obj:
                is_allowed = api.user.has_permission('Delete objects', obj=obj)
                is_locked = obj.wl_isLocked()
                is_movable = obj.cb_isMoveable()
                can_cut = is_allowed and is_movable and not is_locked
                if can_cut:
                    m = Moniker(obj)
                    obj_list.append(m.dump())
                else:
                    cannot_cut.append(u'"%s"' % safe_unicode(obj.Title()))

        if obj_list:
            # now store cutdata into a cookie
            # TODO: what if there's nothing in the list?
            ct_data = (1, obj_list)
            ct_data = _cb_encode(ct_data)  # probably means "clipboard encode"?

            response = request.response
            path = '{0}'.format(cookie_path(request))
            response.setCookie('__cp', ct_data, path=path)
            request['__cp'] = ct_data

            msg = _(
                u"batch_cut_success",
                default=
                u"${num_elems} Files were cut and moved to your cloud clipboard.",  # noqa
                mapping={"num_elems": len(obj_list)})
            api.portal.show_message(
                message=msg,
                request=request,
                type="info",
            )

        if cannot_cut:
            msg = _(
                u"batch_cut_failure",
                default=u"The following items could not be cut: ${num_elems}",
                mapping={"num_elems": ', '.join(sorted(cannot_cut))})
            api.portal.show_message(
                message=msg,
                request=request,
                type="info",
            )
        return self.index()
    def handleCopySupport(self, form, container):
        "handle the copy and paste stuff"
        if form.pop('cut', None) and 'ids' in form and self.allowAddRemove:
            cp = container.manage_cutObjects(form['ids'])
            resp = self.REQUEST.RESPONSE
            resp.setCookie('__cp', cp, path='%s' % cookie_path(self.REQUEST))
            self.REQUEST['__cp'] = cp

        if form.pop('copy', None) and 'ids' in form:
            cp = container.manage_copyObjects(form['ids'])
            resp = self.REQUEST.RESPONSE
            resp.setCookie('__cp', cp, path='%s' % cookie_path(self.REQUEST))
            self.REQUEST['__cp'] = cp

        if form.pop('paste',
                    None) and self.allowAddRemove and self.cb_dataValid(
                    ):  #part of CopySupport
            container.manage_pasteObjects(self.REQUEST['__cp'])
示例#11
0
    def manage_pasteObjects(self,
                            cb_copy_data=None,
                            is_indexable=None,
                            reindex_kw=None,
                            immediate_reindex=False,
                            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

    immediate_reindex (bool)
      Immediately (=during current transaction) reindex created document, so
      it is possible to find it in catalog before transaction ends.
      Note: this does not apply to subobjects which may be created during
      pasting. Only the topmost object will be immediately reindexed. Any
      subobject will be reindexed later, using activities.

      If a ImmediateReindexContextManager instance is given, a context (in
      python sense) must have been entered with it, and indexation will
      occur when that context is exited, allowing further changes before
      first indexation (ex: workflow state change, property change).
    """
        cp = None
        if cb_copy_data is not None:
            cp = cb_copy_data
        elif REQUEST is not None and REQUEST.has_key('__cp'):
            cp = REQUEST['__cp']
        if cp is None:
            raise CopyError(eNoData)
        op, result = self.__duplicate(
            cp,
            duplicate=False,
            is_indexable=is_indexable,
            reindex_kw=reindex_kw,
            immediate_reindex=immediate_reindex,
        )
        if REQUEST is None:
            return result
        if op == 0:
            cb_dataValid = 1
        else:
            cb_dataValid = 0
            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=cb_dataValid)
示例#12
0
 def _cleanup(self):
     """ Cleanup __cp from self.request
     """
     if self.request is not None:
         self.request.response.setCookie('__cp', 'deleted',
             path='%s' % cookie_path(self.request),
             expires='Wed, 31-Dec-97 23:59:59 GMT'
         )
         self.request['__cp'] = None
示例#13
0
 def _cleanup(self):
     """ Cleanup __cp from self.request
     """
     if self.request is not None:
         self.request.response.setCookie(
             '__cp',
             'deleted',
             path='%s' % cookie_path(self.request),
             expires='Wed, 31-Dec-97 23:59:59 GMT')
         self.request['__cp'] = None
示例#14
0
文件: copy.py 项目: kkdhanesh/NBADEMO
 def finish(self):
     oblist = []
     for ob in self.oblist:
         if not ob.cb_isCopyable():
             raise CopyError(eNotSupported % escape(id))
         m = Moniker(ob)
         oblist.append(m.dump())
     cp = (0, oblist)
     cp = _cb_encode(cp)
     resp = self.request.response
     resp.setCookie('__cp', cp, path='%s' % cookie_path(self.request))
     self.request['__cp'] = cp
示例#15
0
 def finish(self):
     oblist = []
     for ob in self.oblist:
         if not ob.cb_isCopyable():
             raise CopyError(eNotSupported % escape(id))
         m = Moniker(ob)
         oblist.append(m.dump())
     cp = (0, oblist)
     cp = _cb_encode(cp)
     resp = self.request.response
     resp.setCookie('__cp', cp, path='%s' % cookie_path(self.request))
     self.request['__cp'] = cp
示例#16
0
文件: cut.py 项目: syslabcom/slc.cart
    def run(self):
        """Cut all items currently in cart and add them to clipboard.

        The tricky part here is that the method that Plone uses
        (manage_cutObjects) was only ment to work on objects of the same
        parent. However, our use case allows cutting objects of different
        parents. Hence we need to go one level deeper and reimplement some
        stuff that manage_cutObjects does in our own way.

        """
        cart_view = self.context.restrictedTraverse('cart')
        request = self.context.REQUEST
        cart = cart_view.cart

        # create a list of "Monik-ed" object paths for those objects
        # that we will store into clipboard
        obj_list = []

        for obj_uuid in cart:
            obj = api.content.get(UID=obj_uuid)
            if obj is None:
                # An object that is in cart was apparently deleted by someone
                # else and dosn't exist anymore, so there's nothing to do.
                continue

            if obj.wl_isLocked():
                continue

            if not obj.cb_isMoveable():
                continue

            m = Moniker(obj)
            obj_list.append(m.dump())

        # now store cutdata into a cookie
        # TODO: what if there's nothing in the list?
        ct_data = (1, obj_list)
        ct_data = _cb_encode(ct_data)  # probably means "clipboard encode"?

        response = request.response
        path = '{0}'.format(cookie_path(request))
        response.setCookie('__cp', ct_data, path=path)
        request['__cp'] = ct_data

        api.portal.show_message(
            message="{0} item(s) cut.".format(len(obj_list)),
            request=request,
            type="info")

        portal = api.portal.get()
        response.redirect(portal.absolute_url() + '/@@cart')
示例#17
0
    def run(self):
        """Cut all items currently in cart and add them to clipboard.

        The tricky part here is that the method that Plone uses
        (manage_cutObjects) was only ment to work on objects of the same
        parent. However, our use case allows cutting objects of different
        parents. Hence we need to go one level deeper and reimplement some
        stuff that manage_cutObjects does in our own way.

        """
        cart_view = self.context.restrictedTraverse('cart')
        request = self.context.REQUEST
        cart = cart_view.cart

        # create a list of "Monik-ed" object paths for those objects
        # that we will store into clipboard
        obj_list = []

        for obj_uuid in cart:
            obj = api.content.get(UID=obj_uuid)
            if obj is None:
                # An object that is in cart was apparently deleted by someone
                # else and dosn't exist anymore, so there's nothing to do.
                continue

            if obj.wl_isLocked():
                continue

            if not obj.cb_isMoveable():
                continue

            m = Moniker(obj)
            obj_list.append(m.dump())

        # now store cutdata into a cookie
        # TODO: what if there's nothing in the list?
        ct_data = (1, obj_list)
        ct_data = _cb_encode(ct_data)  # probably means "clipboard encode"?

        response = request.response
        path = '{0}'.format(cookie_path(request))
        response.setCookie('__cp', ct_data, path=path)
        request['__cp'] = ct_data

        api.portal.show_message(message="{0} item(s) cut.".format(
            len(obj_list)),
                                request=request,
                                type="info")

        portal = api.portal.get()
        response.redirect(portal.absolute_url())
示例#18
0
 def finish(self):
     oblist = []
     for ob in self.oblist:
         if not ob.cb_isCopyable():
             self.errors.append(_(u'${title} cannot be copied.',
                                  mapping={u'title': self.objectTitle(ob)}))
             continue
         m = Moniker(ob)
         oblist.append(m.dump())
     cp = (0, oblist)
     cp = _cb_encode(cp)
     resp = self.request.response
     resp.setCookie('__cp', cp, path='%s' % cookie_path(self.request))
     self.request['__cp'] = cp
示例#19
0
 def finish(self):
     oblist = []
     for ob in self.oblist:
         if not ob.cb_isCopyable():
             self.errors.append(
                 _('${title} cannot be copied.',
                   mapping={'title': self.objectTitle(ob)}))
             continue
         m = Moniker(ob)
         oblist.append(m.dump())
     cp = (0, oblist)
     cp = _cb_encode(cp)
     resp = self.request.response
     resp.setCookie('__cp', cp, path='%s' % cookie_path(self.request))
     self.request['__cp'] = cp
示例#20
0
 def _generate_cp_cookie(self, ids, flag, REQUEST=None):
     if type(ids) is StringType:
         ids=[ids]
         
     try:
         oblist = [Moniker(self[id]).dump() for id in ids]
     except KeyError:
         # Plone expects attribute errors here
         raise AttributeError
     cp = _cb_encode((flag, oblist))
     
     if REQUEST is not None:
         resp = REQUEST['RESPONSE']
         resp.setCookie('__cp', cp, path=cookie_path(REQUEST))
         REQUEST['__cp'] = cp
     return cp
示例#21
0
    def finish(self):
        oblist = []
        for ob in self.oblist:
            if ob.wl_isLocked():
                raise ResourceLockedError('Object "%s" is locked via WebDAV'
                                          % ob.getId())

            if not ob.cb_isMoveable():
                raise CopyError(eNotSupported % escape(id))
            m = Moniker(ob)
            oblist.append(m.dump())
        cp = (1, oblist)
        cp = _cb_encode(cp)
        resp = self.request.response
        resp.setCookie('__cp', cp, path='%s' % cookie_path(self.request))
        self.request['__cp'] = cp
示例#22
0
    def _generate_cp_cookie(self, ids, flag, REQUEST=None):
        if type(ids) is StringType:
            ids = [ids]

        try:
            oblist = [Moniker(self[id]).dump() for id in ids]
        except KeyError:
            # Plone expects attribute errors here
            raise AttributeError
        cp = _cb_encode((flag, oblist))

        if REQUEST is not None:
            resp = REQUEST['RESPONSE']
            resp.setCookie('__cp', cp, path=cookie_path(REQUEST))
            REQUEST['__cp'] = cp
        return cp
示例#23
0
    def finish(self):
        oblist = []
        for ob in self.oblist:
            if ob.wl_isLocked():
                raise ResourceLockedError('Object "%s" is locked via WebDAV' %
                                          ob.getId())

            if not ob.cb_isMoveable():
                raise CopyError(eNotSupported % escape(id))
            m = Moniker(ob)
            oblist.append(m.dump())
        cp = (1, oblist)
        cp = _cb_encode(cp)
        resp = self.request.response
        resp.setCookie('__cp', cp, path='%s' % cookie_path(self.request))
        self.request['__cp'] = cp
 def __call__(self):
     oblist = []
     request = self.request
     paths = request.get('paths', [])
     brains = api.portal.get_tool('portal_catalog')(path=paths)
     for brain in brains:
         ob = brain.getObject()
         if not ob.cb_isCopyable():
             raise CopyError(eNotSupported % escape(id))
         m = Moniker(ob)
         oblist.append(m.dump())
     cp=(0, oblist)
     cp=_cb_encode(cp)
     resp=request.response
     resp.setCookie('__cp', cp, path='%s' % cookie_path(request))
     request.set('__cp', cp)
     request.response.redirect(request.get('HTTP_REFERER'))
示例#25
0
 def __call__(self):
     oblist = []
     request = self.request
     paths = request.get('paths', [])
     brains = api.portal.get_tool('portal_catalog')(path=paths)
     for brain in brains:
         ob = brain.getObject()
         if not ob.cb_isCopyable():
             raise CopyError(eNotSupported % escape(id))
         m = Moniker(ob)
         oblist.append(m.dump())
     cp = (0, oblist)
     cp = _cb_encode(cp)
     resp = request.response
     resp.setCookie('__cp', cp, path='%s' % cookie_path(request))
     request.set('__cp', cp)
     request.response.redirect(request.get('HTTP_REFERER'))
示例#26
0
 def finish(self):
     oblist = []
     for ob in self.oblist:
         if ob.wl_isLocked():
             self.errors.append(_(u'${title} is being edited and cannot be cut.',
                                  mapping={u'title': self.objectTitle(ob)}))
             continue
         if not ob.cb_isMoveable():
             self.errors.append(_(u'${title} is being edited and cannot be cut.',
                                  mapping={u'title': self.objectTitle(ob)}))
             continue
         m = Moniker(ob)
         oblist.append(m.dump())
     cp = (1, oblist)
     cp = _cb_encode(cp)
     resp = self.request.response
     resp.setCookie('__cp', cp, path='%s' % cookie_path(self.request))
     self.request['__cp'] = cp
示例#27
0
 def finish(self):
     oblist = []
     for ob in self.oblist:
         if ob.wl_isLocked():
             self.errors.append(_(u'${title} is being edited and cannot be cut.',
                                  mapping={u'title': self.objectTitle(ob)}))
             continue
         if not ob.cb_isMoveable():
             self.errors.append(_(u'${title} is being edited and cannot be cut.',
                                  mapping={u'title': self.objectTitle(ob)}))
             continue
         m = Moniker(ob)
         oblist.append(m.dump())
     cp = (1, oblist)
     cp = _cb_encode(cp)
     resp = self.request.response
     resp.setCookie('__cp', cp, path='%s' % cookie_path(self.request))
     self.request['__cp'] = cp
def copy_collected(objects, REQUEST=None):
    """Put a reference to the objects in the clip board

    This function is derived from manage_copyObjects in
    OFS.CopySupport.
    """
    oblist = []
    for ob in objects:
        if not ob.cb_isCopyable():
            raise CopyError
        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 cp
示例#29
0
    def run(self):
        """Copy all items currently in cart to clipboard."""
        cart_view = self.context.restrictedTraverse('cart')
        request = self.context.REQUEST
        cart = cart_view.cart

        # create a list of "Monik-ed" object paths for those objects
        # that we will store into clipboard
        obj_list = []

        for obj_uuid in cart:
            obj = api.content.get(UID=obj_uuid)
            if obj is None:
                # An object that is in cart was apparently deleted by someone
                # else and dosn't exist anymore, so there's nothing to do.
                continue

            if not obj.cb_isCopyable():
                continue

            m = Moniker(obj)
            obj_list.append(m.dump())

        # now store copydata into a cookie
        # TODO: what if there's nothing in the list?
        cp_data = (0, obj_list)
        cp_data = _cb_encode(cp_data)  # probably means "clipboard encode"?

        response = request.response
        path = '{0}'.format(cookie_path(request))
        response.setCookie('__cp', cp_data, path=path)
        request['__cp'] = cp_data

        api.portal.show_message(
            message="{0} item(s) copied.".format(len(obj_list)),
            request=request,
            type="info")

        portal = api.portal.get()
        response.redirect(portal.absolute_url() + '/@@cart')
示例#30
0
    def run(self):
        """Copy all items currently in cart to clipboard."""
        cart_view = self.context.restrictedTraverse('cart')
        request = self.context.REQUEST
        cart = cart_view.cart

        # create a list of "Monik-ed" object paths for those objects
        # that we will store into clipboard
        obj_list = []

        for obj_uuid in cart:
            obj = api.content.get(UID=obj_uuid)
            if obj is None:
                # An object that is in cart was apparently deleted by someone
                # else and dosn't exist anymore, so there's nothing to do.
                continue

            if not obj.cb_isCopyable():
                continue

            m = Moniker(obj)
            obj_list.append(m.dump())

        # now store copydata into a cookie
        # TODO: what if there's nothing in the list?
        cp_data = (0, obj_list)
        cp_data = _cb_encode(cp_data)  # probably means "clipboard encode"?

        response = request.response
        path = '{0}'.format(cookie_path(request))
        response.setCookie('__cp', cp_data, path=path)
        request['__cp'] = cp_data

        api.portal.show_message(message="{0} item(s) copied.".format(
            len(obj_list)),
                                request=request,
                                type="info")

        portal = api.portal.get()
        response.redirect(portal.absolute_url())
示例#31
0
def content_object_moved(obj, event):
    # ignore if oldParent or newParent is None or if obj has just
    # been created or removed
    if event.oldParent is None or event.newParent is None:
        return
    if aq_base(event.oldParent) is aq_base(event.newParent):
        return
    if IGroupingStoragable.providedBy(event.oldParent):
        old_storage = getAdapter(event.oldParent, IGroupingStorage)
        old_storage.remove_from_groupings(obj)
    if IGroupingStoragable.providedBy(event.newParent):
        new_storage = getAdapter(event.newParent, IGroupingStorage)
        new_storage.update_groupings(obj)
    # Since OFS.CopySupport.manage_pasteObjects is called without a REQUEST
    # parameter, cb_dataValid() will still be true, because __cp will not
    # be reset. We do that manually here, so that the "paste" action will
    # disappear from the action list.
    request = getattr(obj, "REQUEST", None)
    if request:
        request["RESPONSE"].setCookie(
            "__cp", "deleted", path="%s" % cookie_path(request), expires="Wed, 31-Dec-97 23:59:59 GMT"
        )
        request["__cp"] = None
示例#32
0
def content_object_moved(obj, event):
    # ignore if oldParent or newParent is None or if obj has just
    # been created or removed
    if event.oldParent is None or event.newParent is None:
        return
    if aq_base(event.oldParent) is aq_base(event.newParent):
        return
    if IGroupingStoragable.providedBy(event.oldParent):
        old_storage = getAdapter(event.oldParent, IGroupingStorage)
        old_storage.remove_from_groupings(obj)
    if IGroupingStoragable.providedBy(event.newParent):
        new_storage = getAdapter(event.newParent, IGroupingStorage)
        new_storage.update_groupings(obj)
    # Since OFS.CopySupport.manage_pasteObjects is called without a REQUEST
    # parameter, cb_dataValid() will still be true, because __cp will not
    # be reset. We do that manually here, so that the "paste" action will
    # disappear from the action list.
    request = getattr(obj, 'REQUEST', None)
    if request:
        request['RESPONSE'].setCookie(
            '__cp', 'deleted',
            path='%s' % cookie_path(request),
            expires='Wed, 31-Dec-97 23:59:59 GMT')
        request['__cp'] = None
示例#33
0
 def set_objs(self, objs):
     uuids = [IUUID(obj) for obj in objs]
     value = json.dumps(uuids).encode('base64')
     self.request.RESPONSE.setCookie(
         self.key, value, path=str(cookie_path(self.request)))
示例#34
0
def manage_pasteObjects_Version(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 and IObjectClonedEvent
    or IObjectWillBeMovedEvent and IObjectMovedEvent.
    """
    ### due to the ticket #14598: the need to also handle a cb_copy_data
    ### structure that contains the desired new id on a copy/paste operation.
    ### this feature will be used when creating a new version for an object.
    ### if there is no new id also incapsulated in the cb_copy_data then
    ### the copy/paste will work as default.
    ### also the cut/paste remains the same.
    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, newids = _cb_decode(cp)
    except Exception:
        try:
            op, mdatas = _cb_decode(cp)
            newids = []
        except Exception:
            raise CopyError(eInvalid)
    else:
        if len(mdatas) != len(newids):
            raise CopyError(eInvalid)

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

    if len(newids) == 0:
        newids = ['']*len(oblist)

    result = []
    if op == 0:
        # Copy operation
        for ob, new_id in zip(oblist, newids):
            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'))

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

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

            self._setObject(new_id, ob)
            ob = self._getOb(new_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):
                new_id = orig_id
            else:
                new_id = self._get_id(orig_id)
            result.append({'id': orig_id, 'new_id': new_id})

            notify(ObjectWillBeMovedEvent(ob, orig_container, orig_id,
                                          self, new_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:
                orig_container._delObject(orig_id)
                warnings.warn(
                    "%s._delObject without suppress_events is discouraged."
                    % orig_container.__class__.__name__,
                    DeprecationWarning)
            ob = aq_base(ob)
            ob._setId(new_id)

            try:
                self._setObject(new_id, ob, set_owner=0, suppress_events=True)
            except TypeError:
                self._setObject(new_id, ob, set_owner=0)
                warnings.warn(
                    "%s._setObject without suppress_events is discouraged."
                    % self.__class__.__name__, DeprecationWarning)
            ob = self._getOb(new_id)

            notify(ObjectMovedEvent(ob, orig_container, orig_id, self, new_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
示例#35
0
 def set_objs(self, objs):
     uuids = [IUUID(obj) for obj in objs]
     value = json.dumps(uuids).encode('base64')
     self.request.RESPONSE.setCookie(self.key,
                                     value,
                                     path=str(cookie_path(self.request)))
示例#36
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
示例#37
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
示例#38
0
def manage_pasteObjects_Version(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 and IObjectClonedEvent
    or IObjectWillBeMovedEvent and IObjectMovedEvent.
    """
    # due to the ticket #14598: the need to also handle a cb_copy_data
    # structure that contains the desired new id on a copy/paste operation.
    # this feature will be used when creating a new version for an object.
    # if there is no new id also incapsulated in the cb_copy_data then
    # the copy/paste will work as default.
    # also the cut/paste remains the same.
    if cb_copy_data is not None:
        cp = cb_copy_data
    elif REQUEST is not None and '__cp' in REQUEST:
        cp = REQUEST['__cp']
    else:
        cp = None
    if cp is None:
        raise CopyError(eNoData)

    try:
        op, mdatas, newids = _cb_decode(cp)
    except Exception:
        try:
            op, mdatas = _cb_decode(cp)
            newids = []
        except Exception:
            raise CopyError(eInvalid)
    else:
        if len(mdatas) != len(newids):
            raise CopyError(eInvalid)

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

    if len(newids) == 0:
        newids = [''] * len(oblist)

    result = []
    if op == 0:
        # Copy operation
        for ob, new_id in zip(oblist, newids):
            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 Exception:
                raise CopyError(
                    MessageDialog(title="Copy Error",
                                  message=sys.exc_info()[1],
                                  action='manage_main'))

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

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

            self._setObject(new_id, ob)
            ob = self._getOb(new_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 Exception:
                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):
                new_id = orig_id
            else:
                new_id = self._get_id(orig_id)
            result.append({'id': orig_id, 'new_id': new_id})

            notify(
                ObjectWillBeMovedEvent(ob, orig_container, orig_id, self,
                                       new_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:
                orig_container._delObject(orig_id)
                warnings.warn(
                    "%s._delObject without suppress_events is discouraged." %
                    orig_container.__class__.__name__, DeprecationWarning)
            ob = aq_base(ob)
            ob._setId(new_id)

            try:
                self._setObject(new_id, ob, set_owner=0, suppress_events=True)
            except TypeError:
                self._setObject(new_id, ob, set_owner=0)
                warnings.warn(
                    "%s._setObject without suppress_events is discouraged." %
                    self.__class__.__name__, DeprecationWarning)
            ob = self._getOb(new_id)

            notify(ObjectMovedEvent(ob, orig_container, orig_id, self, new_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
示例#39
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
示例#40
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