def saveUpload(self, source='file', file='', url='', lang=None, REQUEST=None): """ """ if not self.checkPermissionEditObject(): raise EXCEPTION_NOTAUTHORIZED(EXCEPTION_NOTAUTHORIZED_MSG) if self.wl_isLocked(): raise ResourceLockedError("File is locked via WebDAV") if lang is None: lang = self.gl_get_selected_language() context = self ext_file = self.get_data(as_string=False) zope_event.notify( ObjectWillBeRemovedEvent(ext_file, self, ext_file.getId())) context.handleUpload(source, file, url) self.recatalogNyObject(self) if REQUEST: self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES, date=self.utGetTodayDate()) REQUEST.RESPONSE.redirect('%s/edit_html?lang=%s' % (self.absolute_url(), lang))
def __call__(self): # Delete tile from template tile_data = self.annotations.get( '%s.%s' % (ANNOTATIONS_KEY_PREFIX, self.tileId), None) if tile_data and tile_data.get('column'): column = tile_data['column'] element = html.fromstring(getattr(self.context, column)) for tile_div in element: tile_url = tile_div.attrib['data-tile'] if self.tileId in tile_url: element.remove(tile_div) break setattr(self.context, column, html.tostring(element)) tile_url = tile_url.replace('./', '') tile = self.context.restrictedTraverse(tile_url) notify(ObjectWillBeRemovedEvent(tile, self.context, self.tileId)) index = super(DeleteTile, self).__call__() notify(ObjectRemovedEvent(tile, self.context, self.tileId)) notify(ObjectModifiedEvent(self.context)) return index
def _delObject(self, id, dp=1, suppress_events=False): """Delete an object from this container. Also sends IObjectWillBeRemovedEvent and IObjectRemovedEvent. """ ob = self._getOb(id) compatibilityCall('manage_beforeDelete', ob, ob, self) if not suppress_events: notify(ObjectWillBeRemovedEvent(ob, self, id)) self._objects = tuple([i for i in self._objects if i['id'] != id]) self._delOb(id) # Indicate to the object that it has been deleted. This is # necessary for object DB mount points. Note that we have to # tolerate failure here because the object being deleted could # be a Broken object, and it is not possible to set attributes # on Broken objects. try: ob._v__object_deleted__ = 1 except Exception: pass if not suppress_events: notify(ObjectRemovedEvent(ob, self, id)) notifyContainerModified(self)
def _delObject(self, id): object = self._getOb(id) notify(ObjectWillBeRemovedEvent(object, self, id)) if hasattr(aq_base(object), 'manage_beforeDelete'): object.manage_beforeDelete(object, self) self._delOb(id) notify(ObjectRemovedEvent(object, self, id)) notifyContainerModified(self)
def _delete_element(self, element, event=True): uid = element.UID() if event is True: notify(ObjectWillBeRemovedEvent(element, self, uid)) del self._tree[uid] if event is True: notify(ObjectRemovedEvent(element, self, uid)) notify(ContainerModifiedEvent(self))
def __delitem__(self, key, suppress_container_modified=False): element = self[key].__of__(self) notify(ObjectWillBeRemovedEvent(element, self, key)) # Remove the element from _tree self._tree.pop(key) notify(ObjectRemovedEvent(element, self, key)) if not suppress_container_modified: notify(ContainerModifiedEvent(self))
def test_create_destroy_link_translations(self): a_ca = createContentInContainer(self.portal['ca'], 'Document', title=u"Test document") ITranslationManager(a_ca).add_translation('es') a_es = ITranslationManager(a_ca).get_translation('es') # Create duplicate content another_es = createContentInContainer(self.portal['es'], 'Document', title=u"Test another") ITranslationManager(another_es).add_translation('ca') another_ca = ITranslationManager(another_es).get_translation('ca') # Delete original content notify(ObjectWillBeRemovedEvent(a_es)) self.portal.es.manage_delObjects(a_es.id) notify(ObjectWillBeRemovedEvent(another_ca)) self.portal.ca.manage_delObjects(another_ca.id) # Check canonical values are still different id_a_ca = ITranslationManager(a_ca).query_canonical() id_another_es = ITranslationManager(another_es).query_canonical() self.assertNotEquals(id_another_es, id_a_ca) self.assertTrue(isinstance(id_another_es, str)) self.assertTrue(isinstance(id_a_ca, str)) # Make documents translations of each other ITranslationManager(a_ca).register_translation('es', another_es) # Check that canonical values are now the same id_a_ca = ITranslationManager(a_ca).query_canonical() id_another_es = ITranslationManager(another_es).query_canonical() self.assertEqual(id_another_es, id_a_ca)
def _delObject(self, id, dp=1, suppress_events=False): ob = self._getOb(id) OFS.subscribers.compatibilityCall('manage_beforeDelete', ob, ob, self) if not suppress_events: notify(ObjectWillBeRemovedEvent(ob, self, id)) self._delOb(id) if not suppress_events: notify(ObjectRemovedEvent(ob, self, id)) notifyContainerModified(self)
def saveUpload(self, source='file', file='', url='', version=True, lang=None, REQUEST=None): """ """ if REQUEST: username = REQUEST.AUTHENTICATED_USER.getUserName() else: username = self.REQUEST.AUTHENTICATED_USER.getUserName() if not self.checkPermissionEditObject(): raise EXCEPTION_NOTAUTHORIZED, EXCEPTION_NOTAUTHORIZED_MSG if self.wl_isLocked(): raise ResourceLockedError, "File is locked via WebDAV" if lang is None: lang = self.gl_get_selected_language() if not self.hasVersion(): context = self else: version_ob = self._getOb('version') #this object has been checked out; save changes into the version object if self.checkout_user != username: raise EXCEPTION_NOTAUTHORIZED, EXCEPTION_NOTAUTHORIZED_MSG context = version_ob # Create version if version: newdata = self.getFileItem(lang)._get_upload_file( source, file, url, self)[0] context.createversion(newdata, lang, username=username, modification_time=self.utGetTodayDate()) else: fileitem = self.getFileItem(lang) ext_file = fileitem.get_data(as_string=False) zope_event.notify( ObjectWillBeRemovedEvent(ext_file, fileitem, ext_file.getId())) context.handleUpload(source, file, url, lang) self.recatalogNyObject(self) if REQUEST: self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES, date=self.utGetTodayDate()) REQUEST.RESPONSE.redirect('%s/edit_html?lang=%s' % (self.absolute_url(), lang))
def deleter(self): to_delete = [] container_ids = set(self.context.objectIds()) try: protected = self.context._reserved_names except: protected = () content = yield while content is not None: try: content.is_deletable() except ContentError as error: result = error else: content_id = content.getId() if (content_id in container_ids and content_id not in protected and aq_base(self.context) is aq_base(aq_parent(content))): to_delete.append((content_id, content)) result = content else: result = ContentError(_("Cannot delete content."), content) content = yield result # Event for identifier, content in to_delete: compatibilityCall('manage_beforeDelete', content, content, self.context) notify(ObjectWillBeRemovedEvent(content, self.context, identifier)) # Delete for identifier, content in to_delete: self.context._objects = tuple( [i for i in self.context._objects if i['id'] != identifier]) self.context._delOb(identifier) try: content._v__object_deleted__ = 1 except: pass # Event for identifier, content in to_delete: notify(ObjectRemovedEvent(content, self.context, identifier)) if to_delete: notifyContainerModified(self.context)
def test_shared_content_indexing(self): # Create shared document createContentInContainer( self.portal.en.assets, 'Document', title=u"Test document") # Check that shared document is indexed in all LRFs elements = self.portal.portal_catalog.searchResults(id='test-document') self.assertEqual(len(elements), 3) # Remove shared document notify(ObjectWillBeRemovedEvent(self.portal.en.assets['test-document'])) self.portal.en.assets.manage_delObjects('test-document') # Check that shared document is unindexed elements = self.portal.portal_catalog.searchResults(id='test-document') self.assertEqual(len(elements), 0)
def manage_delObjects(self, ids=[], REQUEST=None): """Delete reflected files or directories The objects specified in 'ids' get deleted. This emulates the ObjectManager interface enough to support deletion in Plone only. When file removal fails, errors are communicated through the return of the successful ids and the IStatusMessage utility """ if type(ids) is StringType: ids = [ids] if not ids: raise ValueError('No items specified') # To avoid inconsistencies, first test file availability for id in ids: if not self.has_key(id): raise KeyError(id) notify(ObjectWillBeRemovedEvent(self[id], self, id)) problem_ids = [] path = self.getFilesystemPath() for id in ids: subpath = os.path.join(path, id) ob = self[id] try: if os.path.isdir(subpath): shutil.rmtree(subpath) else: os.unlink(subpath) notify(ObjectRemovedEvent(ob, self, id)) except OSError: problem_ids.append(id) if problem_ids: sm = IStatusMessage(getattr(self, 'REQUEST', None), None) if sm is not None: sm.addStatusMessage( 'Failed to remove some files: %s' % problem_ids, 'stop') if set(ids) - set(problem_ids): indexview = self.unrestrictedTraverse('@@index') indexview.index() notifyContainerModified(self) return problem_ids or None # None expected by webdav on success
def test_shared_content(self): # Create shared document createContentInContainer( self.portal.en.assets, 'Document', title=u"Test document") # Check shared document is there self.assertEqual(self.portal.en.assets['test-document'], self.portal.ca.assets['test-document']) self.assertEqual(self.portal.en.assets['test-document'], self.portal.es.recursos['test-document']) # Delete shared document notify(ObjectWillBeRemovedEvent(self.portal.en.assets['test-document'])) self.portal.en.assets.manage_delObjects('test-document') # Check that it is not available in LRFs self.assertNotIn('test-document', self.portal.ca.assets.objectIds()) self.assertNotIn('test-document', self.portal.es.recursos.objectIds())
def manage_delObjects(self, ids=[], REQUEST=None): """Delete objects. """ if isinstance(ids, str): ids = [ids] try: protected = self._reserved_names except: protected = () deleted_objects = [] for identifier in ids: if identifier in protected: continue ob = self._getOb(identifier, None) if ob is None: continue deleted_objects.append((identifier, ob)) for identifier, ob in deleted_objects: compatibilityCall('manage_beforeDelete', ob, ob, self) notify(ObjectWillBeRemovedEvent(ob, self, identifier)) for identifier, ob in deleted_objects: self._objects = tuple( [i for i in self._objects if i['id'] != identifier]) self._delOb(identifier) try: ob._v__object_deleted__ = 1 except: pass for identifier, ob in deleted_objects: notify(ObjectRemovedEvent(ob, self, identifier)) if deleted_objects: notifyContainerModified(self) if REQUEST is not None: # For ZMI REQUEST.RESPONSE.redirect( absoluteURL(self, REQUEST) + '/manage_main')
def _remove(self, obj=None, suppress_events=False): """remove object from our side of a relationship""" if obj: objs = [obj] else: objs = self.objectValuesAll() if not suppress_events: for robj in objs: notify(ObjectWillBeRemovedEvent(robj, self, robj.getId())) if obj: id = obj.id if not self._objects.has_key(id): raise ObjectNotFound("object %s not found on %s" % (obj.getPrimaryId(), self.getPrimaryId())) del self._objects[id] else: self._objects = OOBTree() self.__primary_parent__._p_changed = True if not suppress_events: for robj in objs: notify(ObjectRemovedEvent(robj, self, robj.getId()))
def __delitem__(self, key, suppress_container_modified=False): """Delete an item by its long key """ key = long(key) comment = self[key].__of__(self) commentator = comment.author_username notify(ObjectWillBeRemovedEvent(comment, self, key)) # Remove all children for child_id in self._children.get(key, []): # avoid sending ContainerModifiedEvent multiple times self.__delitem__(child_id, suppress_container_modified=True) # Remove the comment from _comments self._comments.pop(key) # Remove this comment as a child of its parent if not suppress_container_modified: parent = comment.in_reply_to if parent is not None: parent_children = self._children.get(parent, None) if parent_children is not None and key in parent_children: parent_children.remove(key) # Remove commentators if commentator and commentator in self._commentators: if self._commentators[commentator] <= 1: del self._commentators[commentator] else: self._commentators[commentator] -= 1 notify(ObjectRemovedEvent(comment, self, key)) if not suppress_container_modified: notify(ContainerModifiedEvent(self))
def CopyToClient(survey, preview=False): """Copy the survey to the online client part of the site. :param survey: the survey to copy :param bool preview: indicates if this is a preview or a normal publication :rtype: :py:class:`euphorie.content.survey.Survey` The public area is hardcoded to be a container with id ``client`` within the site root. The ''id'' and ''title'' of the survey group will be used for the published survey. If another object with the same ''id'' already exists it will be removed first. Any missing country and sector folders are created if needed. If this is a preview (as indicated by the ``preview`` parameter) the id of the survey will be set to ``preview``, guaranteeing that an existing published survey will not be replaced. This also means only a sector can only have one preview online. This method assumes the current user has permissions to create content in the online client. This is normally done by using the :py:func:`PublishToClient` function which switches the current user for the copy operation. Returns the new public survey instance. """ # This is based on OFS.CopyContainer.manage_clone, modified to # use the sector id and title, skip security checks and remove # an existing object with the same id. client = getPortal(survey).client source = aq_inner(survey) surveygroup = aq_parent(source) sector = aq_parent(surveygroup) country = aq_parent(sector) from euphorie.content.sector import ISector assert ISector.providedBy(sector) if country.id not in client: client.invokeFactory("euphorie.clientcountry", country.id, title=country.title, country_type=country.country_type) cl_country = client[country.id] if sector.id not in cl_country: cl_country.invokeFactory("euphorie.clientsector", sector.id) target = cl_country[sector.id] target.title = sector.title target.logo = sector.logo # Clear any scaled logos AnnotationStorage(target).storage.clear() target.main_background_colour = getattr(sector, "main_colour", None) if target.main_background_colour: target.main_foreground_colour = utils.MatchColour( target.main_background_colour, 0.0, 0.6, 0.3) target.main_background_bright = \ utils.IsBright(target.main_background_colour) target.support_background_colour = getattr(sector, "support_colour", None) if target.support_background_colour: target.support_foreground_colour = \ utils.MatchColour(target.support_background_colour) target.support_background_bright = \ utils.IsBright(target.support_background_colour) copy = source._getCopy(target) if preview: copy.id = "preview" else: copy.id = surveygroup.id copy.title = surveygroup.title copy.obsolete = surveygroup.obsolete copy.evaluation_algorithm = surveygroup.evaluation_algorithm copy.version = source.id copy.published = datetime.datetime.now() copy.preview = preview if copy.id in target: # We must suppress events to prevent the can-not-delete-published- # content check from blocking us. # XXX: We need however the ObjectWillBeRemovedEvent event to be called # otherwise the removed objects are not uncatalogged. to_delete = target._getOb(copy.id) notify(ObjectWillBeRemovedEvent(to_delete, target, copy.id)) target._delObject(copy.id, suppress_events=True) target._setObject(copy.id, copy, suppress_events=True) copy = target[copy.id] copy._postCopy(target, op=0) notify(ObjectPublishedEvent(source)) return copy