def manage_pasteObjects(self, cb_copy_data=None, REQUEST=None): """ override normal paste action to see if we're looking at the paste data being stored in cache """ 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 = _cb_decode(cp) except Exception: raise CopyError(eInvalid) try: if mdatas[0][0].startswith('cache:'): cache_key = mdatas[0][0].replace('cache:', '') new_mdatas = cache.get(cache_key) cdata = _cb_encode((op, new_mdatas)) return self._old_manage_pasteObjects(cdata) except IndexError: pass return self._old_manage_pasteObjects(cb_copy_data, REQUEST)
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 manage_pasteObjects(self, cp): """ merge another conversation """ try: op, mdatas = _cb_decode(cp) except Exception: raise CopyError("Invalid content") if op == 0: raise ValueError('Not allowed to copy content into conversation') if op != 1: raise ValueError("Invalid operation of content") obj = self.unrestrictedTraverse(mdatas[0]) if IConversation.providedBy(obj): if obj.getParentNode() != self.getParentNode(): raise ValueError("Invalid parent of content") forum = obj.getForum() obj_id = obj.getId() o_list = obj.objectValues() oblist = [Moniker(o1).dump() for o1 in o_list] cp = (1, oblist) cp = _cb_encode(cp) CopyContainer.manage_pasteObjects(self, cp) forum.manage_delObjects([obj_id]) elif IComment.providedBy(obj): return CopyContainer.manage_pasteObjects(self, cp) else: raise ValueError('Invalid type of content')
def moveObjsToTrashcan(self, ids, REQUEST): if self.meta_id == 'ZMSTrashcan': return trashcan = self.getTrashcan() # Set deletion-date. ids_copy = [] for id in ids: try: context = getattr(self, id) context.del_uid = str(REQUEST.get('AUTHENTICATED_USER', None)) context.del_dt = standard.getDateTime(time.time()) ids_copy.append(id) except: standard.writeBlock( self, "[moveObjsToTrashcan]: Attribute Error %s" % (id)) # Use only successfully tried ids ids = ids_copy # Move (Cut & Paste). children = [getattr(self, x) for x in ids] [ standard.triggerEvent(child, 'beforeDeleteObjsEvt') for child in children ] cb_copy_data = _cb_decode(self.manage_cutObjects(ids)) trashcan.manage_pasteObjects(cb_copy_data=_cb_encode(cb_copy_data)) trashcan.normalizeSortIds() trashcan.run_garbage_collection(forced=1) # Sort-IDs. self.normalizeSortIds() [ standard.triggerEvent(child, 'afterDeleteObjsEvt') for child in children ]
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
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 __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()
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"])
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
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"])
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 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
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
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')
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())
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
def test_get_paste_data(self): login(self.portal, TEST_USER_NAME) setRoles(self.portal, TEST_USER_ID, ('Member', 'Manager')) api.content.create(type='Document', id='newpage', container=self.portal) cp = (0, [('', 'plone', 'newpage')]) cp = _cb_encode(cp) self.request['__cp'] = cp data = utils.get_paste_data(self.request) self.assertEqual(data['count'], 1) self.assertEqual(data['op'], 0) self.assertEqual(data['paths'], ['/plone/newpage'])
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
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
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 _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
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'))
def manage_copyObjects(self, ids, REQUEST=None, RESPONSE=None): """Put a reference to the objects named in ids in the clipboard, marked for a copy operation.""" if type(ids) is type(''): ids=[ids] oblist = [] for id in ids: ob = self._safe_getOb(id) m = FileMoniker(ob) oblist.append(m.ids) cp=(0, oblist) cp=_cb_encode(cp) if REQUEST is not None: resp=REQUEST['RESPONSE'] resp.setCookie('__lcp', cp, path='%s' % REQUEST['SCRIPT_NAME']) return self.manage_main(self, REQUEST, cb_dataValid=1) return 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'))
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 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 manage_pasteObjs(self, REQUEST, RESPONSE=None): """ CopySupport.manage_pasteObjs """ _globals.writeBlock(self, "[manage_pasteObjs]") t0 = time.time() # Analyze request cp = self._get_cb_copy_data(cb_copy_data=None, REQUEST=REQUEST) op = cp[0] cp = (0, cp[1]) cp = _cb_encode(cp) ids = self._get_ids(cp) oblist = self._get_obs(cp) # Paste objects. self.manage_pasteObjects(cb_copy_data=None, REQUEST=REQUEST) # Sort order (I). self._set_sort_ids(ids=ids, op=op, REQUEST=REQUEST) # Move objects. if op == 1: self._normalize_ids_after_move(ids=ids, forced=0, REQUEST=REQUEST) # Copy objects. else: self._normalize_ids_after_copy(ids=ids, forced=0, REQUEST=REQUEST) # Keep links (ref_by) synchron. if self.getConfProperty('ZMS.InternalLinks.keepsynchron', 0) == 1: obs = _globals.objectTree(self) for ob in obs: self.synchronizeRefToObjs() self.synchronizeRefByObjs() # Sort order (II). self.normalizeSortIds() # Return with message. if RESPONSE is not None: message = self.getZMILangStr('MSG_PASTED') message += ' (in ' + str(int( (time.time() - t0) * 100.0) / 100.0) + ' secs.)' RESPONSE.redirect('manage_main?lang=%s&manage_tabs_message=%s' % (REQUEST['lang'], urllib.quote(message)))
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
def manage_pasteObjs(self, REQUEST, RESPONSE=None): """ CopySupport.manage_pasteObjs """ id_prefix = REQUEST.get('id_prefix', 'e') standard.writeBlock(self, "[CopySupport.manage_pasteObjs]") t0 = time.time() # Analyze request cb_copy_data = self._get_cb_copy_data(cb_copy_data=None, REQUEST=REQUEST) op = cb_copy_data[0] cp = (op, cb_copy_data[1]) cp = _cb_encode(cp) ids = [self._get_id(x.getId()) for x in self._get_obs(cp)] oblist = self._get_obs(cp) # Paste objects. action = ['Copy', 'Move'][op == OP_MOVE] standard.triggerEvent(self, 'before%sObjsEvt' % action) self.manage_pasteObjects(cb_copy_data=None, REQUEST=REQUEST) standard.triggerEvent(self, 'after%sObjsEvt' % action) # Sort order (I). self._set_sort_ids(ids=ids, op=op, REQUEST=REQUEST) # Move objects. if op == OP_MOVE: normalize_ids_after_move(self, id_prefix=id_prefix, ids=ids) # Copy objects. else: normalize_ids_after_copy(self, id_prefix=id_prefix, ids=ids) # Sort order (II). self.normalizeSortIds() # Return with message. if RESPONSE is not None: message = self.getZMILangStr('MSG_PASTED') message += ' (in ' + str(int( (time.time() - t0) * 100.0) / 100.0) + ' secs.)' RESPONSE.redirect('manage_main?lang=%s&manage_tabs_message=%s' % (REQUEST['lang'], urllib.parse.quote(message)))
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')
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())
def make_data(lenght): return _cb_encode( (1, ['qwertzuiopasdfghjklyxcvbnm' for x in range(lenght)]))
def cp_get_obs(self, REQUEST): cp = self._get_cb_copy_data(cb_copy_data=None, REQUEST=REQUEST) op = cp[0] cp = (0, cp[1]) cp = _cb_encode(cp) return self._get_obs(cp)
def make_data(lenght): return _cb_encode( (1, ['qwertzuiopasdfghjklyxcvbnm' for x in range(lenght)]))
def create_version(context, reindex=True): """ Create a new version of an object This is done by copy&pasting the object, then assigning, as versionId, the one from the original object. Additionally, we rename the object using a number based scheme and then clean it up to avoid various problems. """ logger.info("Started creating version of %s", context.absolute_url()) obj_id = context.getId() parent = utils.parent(context) # Adapt version parent (if case) if not IVersionEnhanced.providedBy(context): alsoProvides(context, IVersionEnhanced) # _ = IVersionControl(context).getVersionId() # Create version object # 1. copy object clipb = parent.manage_copyObjects(ids=[obj_id]) # 2. pregenerate new id for the copy new_id = generateNewId(parent, obj_id) # 3. alter the clipboard data and inject the desired new id clipb_decoded = _cb_decode(clipb) clipb = _cb_encode((clipb_decoded[0], clipb_decoded[1], [new_id])) # 4. call paste operation manage_pasteObjects_Version(parent, clipb) # 5. get the version object - no need for a rename anymore ver = parent[new_id] # #31440 apply related items from original object to the new version ver.setRelatedItems(context.getRelatedItems()) # Set effective date today ver.setCreationDate(DateTime()) ver.setEffectiveDate(None) ver.setExpirationDate(None) mtool = getToolByName(context, 'portal_membership') auth_user = mtool.getAuthenticatedMember() auth_username = auth_user.getUserName() auth_username_list = [auth_username] current_creators = ver.Creators() auth_username_list.extend(current_creators) username_list = [] for name in auth_username_list: if name == auth_username and name in username_list: continue else: username_list.append(name) new_creators = tuple(username_list) ver.setCreators(new_creators) # Remove comments if hasNewDiscussion: conversation = IConversation(ver) while conversation.keys(): conversation.__delitem__(conversation.keys()[0]) else: if hasattr(aq_base(ver), 'talkback'): tb = ver.talkback if tb is not None: for obj in tb.objectValues(): obj.__of__(tb).unindexObject() tb._container = PersistentMapping() notify(VersionCreatedEvent(ver, context)) if reindex: ver.reindexObject() # some catalogued values of the context may depend on versions _reindex(context) logger.info("Created version at %s", ver.absolute_url()) return ver
def create_version(context, reindex=True): """ Create a new version of an object This is done by copy&pasting the object, then assigning, as versionId, the one from the original object. Additionally, we rename the object using a number based scheme and then clean it up to avoid various problems. """ logger.info("Started creating version of %s", context.absolute_url()) obj_id = context.getId() parent = utils.parent(context) # Adapt version parent (if case) if not IVersionEnhanced.providedBy(context): alsoProvides(context, IVersionEnhanced) # _ = IVersionControl(context).getVersionId() # Create version object # 1. copy object clipb = parent.manage_copyObjects(ids=[obj_id]) # 2. pregenerate new id for the copy new_id = generateNewId(parent, obj_id) # 3. alter the clipboard data and inject the desired new id clipb_decoded = _cb_decode(clipb) clipb = _cb_encode((clipb_decoded[0], clipb_decoded[1], [new_id])) # 4. call paste operation manage_pasteObjects_Version(parent, clipb) # 5. get the version object - no need for a rename anymore ver = parent[new_id] # #31440 apply related items from original object to the new version ver.setRelatedItems(context.getRelatedItems()) # Set effective date today ver.setCreationDate(DateTime()) ver.setEffectiveDate(None) ver.setExpirationDate(None) mtool = getToolByName(context, 'portal_membership') auth_user = mtool.getAuthenticatedMember() auth_username = auth_user.getUserName() auth_username_list = [auth_username] current_creators = ver.Creators() auth_username_list.extend(current_creators) username_list = [] for name in auth_username_list: if name == auth_username and name in username_list: continue else: username_list.append(name) new_creators = tuple(username_list) ver.setCreators(new_creators) # Remove comments if hasNewDiscussion: conversation = IConversation(ver) while conversation.keys(): conversation.__delitem__(conversation.keys()[0]) else: if hasattr(aq_base(ver), 'talkback'): tb = ver.talkback if tb is not None: for obj in tb.objectValues(): obj.__of__(tb).unindexObject() tb._container = PersistentMapping() notify(VersionCreatedEvent(ver, context)) if reindex: ver.reindexObject() # some catalogued values of the context may depend on versions _reindex(context) logger.info("Created version at %s", ver.absolute_url()) return ver