def object_cut(self, ajax=False): self.protect() context = aq_inner(self.context) title = self.objectTitle() plone_utils = getToolByName(context, 'plone_utils') lock_info = getMultiAdapter((context, self.request), name='plone_lock_info') if lock_info is not None and lock_info.is_locked(): message = _(u'${title} is locked and cannot be cut.', mapping={u'title': title}) plone_utils.addPortalMessage(message, 'error') else: parent = aq_parent(context) try: parent.manage_cutObjects(context.getId(), self.request) message = _(u'${title} cut.', mapping={u'title': title}) utils.transaction_note('Cut object %s' % ( context.absolute_url())) plone_utils.addPortalMessage(message) except CopyError: message = _(u'${title} is not moveable.', mapping={u'title': title}) plone_utils.addPortalMessage(message, 'error') if ajax: pass else: return self.redirectReferer()
def create(self, fields): # create a member in portal factory # i don't think this is really necessary any more. -egj pf = self._membertool.portal_factory #00 pythonscript call, move to fs code id_ = self.context.generateUniqueId('OpenMember') mem_folder = pf._getTempFolder('OpenMember') mem = mem_folder.restrictedTraverse('%s' % id_) # now we have mem, a temp member. create him for real. mem_id = fields.get('id') mem = pf.doCreate(mem, mem_id) transaction_note('Created %s with id %s in %s' % \ (mem.getTypeInfo().getId(), mem_id, self.context.absolute_url())) # post-creation setup result = mem.processForm(values=fields) # what does result look like? what do we do with it? # and shouldn't we process form BEFORE we finalize creation? notify(ObjectCreatedEvent(mem)) mem.setUserConfirmationCode() return mem
def __call__(self): title = safe_unicode(self.context.title_or_id()) mtool = getToolByName(self.context, 'portal_membership') self.request.response.setHeader("Content-type","application/json") if not mtool.checkPermission('Copy or Move', self.context): message = PLMF(u'Permission denied to copy ${title}.', mapping={u'title' : title}) status = 'error' raise json.dumps({'status':status, 'message':self.context.translate(message)}) parent = aq_parent(aq_inner(self.context)) try: cp = parent.manage_copyObjects(self.context.getId()) status = 'copied' except CopyError: status = 'error' message = PLMF(u'${title} is not copyable.', mapping={u'title' : title}) return json.dumps({'status':status, 'message':parent.translate(message)}) message = PLMF(u'${title} copied.', mapping={u'title' : title}) transaction_note('Copied object %s' % self.context.absolute_url()) contextId = 'UID_' + get_uid(self.context) return json.dumps({'status':status, 'message':self.context.translate(message), 'cp':cp, 'id':contextId})
def __call__(self): context = self.context title = safe_unicode(context.title_or_id()) if not has_permission('Copy or Move', context): msg = _(u'Permission denied to cut ${title}.', mapping={u'title': title}) msg = self.context.translate(msg) raise Unauthorized, msg try: lock_info = context.restrictedTraverse('plone_lock_info') except AttributeError: lock_info = None if lock_info is not None and lock_info.is_locked(): msg = _(u'${title} is locked and cannot be cut.', mapping={u'title': title}) msg = self.context.translate(msg) raise Exception, msg parent = aq_parent(aq_inner(context)) try: parent.manage_cutObjects(context.getId(), self.request) except CopyError: msg = _(u'${title} is not moveable.', mapping={u'title': title}) msg = self.context.translate(msg) raise Exception, msg self.request.response.setCookie('__fct', self.context.UID(), path='/') msg = _(u'${title} cut.', mapping={u'title': title}) msg = self.context.translate(msg) transaction_note('Cut object %s' % context.absolute_url()) return msg, None
def __call__(self): msg=plMF(u'Copy or cut one or more items to paste.') status='failure' if self.context.cb_dataValid: try: baseObject = self.portal.restrictedTraverse(self.copyDict['url']) baseId = 'UID_'+baseObject.UID() intervalle = baseObject.endDate-baseObject.startDate cb_copy_data = self.request['__cp'] pasteList = self.context.manage_pasteObjects(cb_copy_data=cb_copy_data) newObject = getattr(self.context, pasteList[0]['new_id']) startDate = self.startDate if self.EventAllDay: startDate = DateTime(self.startDate).strftime('%Y-%m-%d ')+baseObject.startDate.strftime('%H:%M') newObject.setStartDate( DateTime(startDate) ) newObject.setEndDate(newObject.startDate + intervalle) newObject.reindexObject() transaction_note('Pasted content to %s' % (self.context.absolute_url())) return json.dumps({'status':'pasted', 'event':self.createJsonEvent(newObject), 'url':newObject.absolute_url(), 'op':self.copyDict['op'], 'id':baseId}) except ConflictError: raise except ValueError: msg=plMF(u'Disallowed to paste item(s).') except (Unauthorized, 'Unauthorized'): msg=plMF(u'Unauthorized to paste item(s).') except: # fallback msg=plMF(u'Paste could not find clipboard content.') return json.dumps({'status':'failure', 'message':self.context.translate(msg)})
def __call__(self): payload = self.request.get('data', None) if not payload: raise BadRequest('No data given') # TODO validate payload contains blocks and confirmed flag. self.link_integrity = ILinkIntegrityInfo(self.request) data = json.loads(payload) self.block = uuidToObject(data['block']) if self.request.get('form.submitted', False): if self.link_integrity: # Always allow deletion of block, regardless of the integrity # check. self.request.environ[self.link_integrity.marker] = 'all' self.context.manage_delObjects([self.block.id]) transaction_note('Deleted %s' % self.block.absolute_url()) return json_response(self.request, proceed=True) else: return json_response(self.request, content=self.confirm_template(), proceed=False)
def __call__(self): method = self.request.get('REQUEST_METHOD', 'GET') if (method != 'POST') or not int(self.request.form.get('form.submitted', 0)): return self.index() if self.request.form.get('form.button.Cancel') == 'Cancel': #User canceled deletion... message = _(u'The deletion of ${title} has been canceled.', mapping={u'title' : self.context.Title()}) self.context.plone_utils.addPortalMessage(message) self.request.response.redirect(self.context.absolute_url()) return parent = self.context.aq_inner.aq_parent self.processChilds() parent.manage_delObjects(self.context.getId()) title = self.context.Title() message = _(u'${title} has been deleted.', mapping={u'title': self.context.Title()}) transaction_note('Deleted %s' % self.context.absolute_url()) self.context.plone_utils.addPortalMessage(message) self.request.response.redirect(parent.absolute_url())
def deleteObjectsByPaths(self, paths, handle_errors=True, REQUEST=None): log_deprecated("deleteObjectsByPaths is deprecated, you should use. " "plone.api.content.delete. This method no longer does link integrity checks") # noqa failure = {} success = [] # use the portal for traversal in case we have relative paths portal = getToolByName(self, 'portal_url').getPortalObject() traverse = portal.restrictedTraverse for path in paths: # Skip and note any errors if handle_errors: sp = transaction.savepoint(optimistic=True) try: obj = traverse(path) obj_parent = aq_parent(aq_inner(obj)) obj_parent.manage_delObjects([obj.getId()]) success.append('%s (%s)' % (obj.getId(), path)) except ConflictError: raise except Exception as e: if handle_errors: sp.rollback() failure[path] = e log_exc() else: raise transaction_note('Deleted %s' % (', '.join(success))) return success, failure
def _makeTransactionNote(self, obj, msg=u''): # TODO Why not aq_parent()? relative_path = '/'.join( getToolByName(self, 'portal_url').getRelativeContentPath(obj)[:-1] ) if not msg: msg = relative_path + '/' + obj.title_or_id() \ + ' has been modified.' if not transaction.get().description: transaction_note(safe_unicode(msg))
def __call__(self, subject, body_text, text_format="plain", username=None, password=None): """This method is lifted almost directly from CMFPlone's discussion_reply.cpy skin script. Modifications start at the point where we try to adapt to IWeblogEntry. """ req = self.request if username or password: # The user username/password inputs on on the comment form were used, # which might happen when anonymous commenting is enabled. If they typed # something in to either of the inputs, we send them to 'logged_in'. # 'logged_in' will redirect them back to this script if authentication # succeeds with a query string which will post the message appropriately # and show them the result. if 'logged_in' fails, the user will be # presented with the stock login failure page. This all depends # heavily on cookiecrumbler, but I believe that is a Plone requirement. came_from = "%s?subject=%s&body_text=%s" % (req["URL"], subject, body_text) came_from = url_quote_plus(came_from) portal_url = self.context.portal_url() return req.RESPONSE.redirect( "%s/logged_in?__ac_name=%s" "&__ac_password=%s" "&came_from=%s" % (portal_url, url_quote_plus(username), url_quote_plus(password), came_from) ) # if (the user is already logged in) or (if anonymous commenting is enabled and # they posted without typing a username or password into the form), we do # the following mtool = getToolByName(self.context, "portal_membership") creator = mtool.getAuthenticatedMember().getId() dtool = getToolByName(self.context, "portal_discussion") tb = dtool.getDiscussionFor(self.context) id = tb.createReply(title=subject, text=body_text, Creator=creator) reply = tb.getReply(id) # TODO THIS NEEDS TO GO AWAY! if hasattr(dtool.aq_explicit, "cookReply"): dtool.cookReply(reply, text_format="plain") parent = tb.aq_parent # return to the discussable object. obj = self.context.plone_utils.getDiscussionThread(tb)[0] try: entry = IWeblogEntry(obj).__of__(self.context.aq_inner.aq_parent) # Check for the existence of a parent weblog to see if `obj' should # be treated as having an archive url. if IWeblog.providedBy(entry.getWeblog()): weview = getMultiAdapter((obj, self.request), name=u"weblogentry_view") base = weview.getArchiveURLFor(entry) except TypeError: base = obj.getTypeInfo().getActionInfo("object/view", obj)["url"] anchor = reply.getId() from Products.CMFPlone.utils import transaction_note transaction_note("Added comment to %s at %s" % (parent.title_or_id(), reply.absolute_url())) self.context.plone_utils.addPortalMessage(_(u"Comment added.")) target = "%s#%s" % (base, anchor) return req.RESPONSE.redirect(target)
def _makeTransactionNote(self, obj, msg=""): # TODO Why not aq_parent()? relative_path = "/".join(getToolByName(self, "portal_url").getRelativeContentPath(obj)[:-1]) if not msg: msg = relative_path + "/" + obj.title_or_id() + " has been modified." if isinstance(msg, UnicodeType): # Convert unicode to a regular string for the backend write IO. # UTF-8 is the only reasonable choice, as using unicode means # that Latin-1 is probably not enough. msg = msg.encode("utf-8") if not transaction.get().description: transaction_note(msg)
def _create_content(self, title, type_name): assert title, 'Must have a title to create content' id_=self.context.generateUniqueId(type_name) new_content = self.context.restrictedTraverse('portal_factory/%s/%s' % (type_name, id_)) transaction_note('Initiated creation of %s with id %s in %s' % \ (new_content.getTypeInfo().getId(), id_, self.context.absolute_url())) new_content.setTitle(title) newcontentid = normalize(title) new_content.setId(newcontentid) return new_content
def __call__(self): mt = getToolByName(self.context, 'portal_membership') mt.logoutUser(self.request) transaction_note('Logged out') # Handle external logout requests from other portals next_ = self.request.get('next', None) portal_url = getToolByName(self.context, 'portal_url') if next_ is not None and portal_url.isURLInPortal(next_): target_url = next_ else: target_url = self.request.URL1 + '/logged-out' registry = queryUtility(IRegistry) external_logout_url = registry['plone.external_logout_url'] if external_logout_url: target_url = external_logout_url self.request.response.redirect(target_url)
def __call__(self): msg=PLMF(u'Copy or cut one or more items to paste.') self.request.response.setHeader("Content-type","application/json") if self.context.cb_dataValid(): try: baseObject = self.portal.restrictedTraverse(self.copyDict['url']) baseId = 'UID_' + get_uid(baseObject) intervalle = ends(baseObject) - starts(baseObject) cb_copy_data = self.request['__cp'] pasteList = self.context.manage_pasteObjects(cb_copy_data=cb_copy_data) newObject = getattr(self.context, pasteList[0]['new_id']) startDate = self.startDate if self.EventAllDay: startDate = DateTime(self.startDate).strftime('%Y-%m-%d ')+starts(baseObject).strftime('%H:%M') if HAS_PAE and not hasattr(newObject, 'setStartDate'): # non-Archetypes duck type: use properties for start/end, # along with UTC-normalized datetime.datetime values from plone.event.utils import pydt import pytz local_start = DateTime(startDate) _utc = lambda dt: pytz.UTC.normalize(dt) newObject.start = _utc(pydt(local_start)) newObject.end = _utc(pydt(local_start + intervalle)) newObject.whole_day = self.EventAllDay else: newObject.setStartDate(DateTime(startDate)) newObject.setEndDate(newObject.getField('startDate').get(newObject) + intervalle) newObject.reindexObject() transaction_note('Pasted content to %s' % (self.context.absolute_url())) return json.dumps({'status':'pasted', 'event':self.createJsonEvent(newObject), 'url':newObject.absolute_url(), 'op':self.copyDict['op'], 'id':baseId}) except ConflictError: raise except ValueError: msg=PLMF(u'Disallowed to paste item(s).') except (Unauthorized, 'Unauthorized'): msg=PLMF(u'Unauthorized to paste item(s).') except CopyError: # fallback msg=PLMF(u'Paste could not find clipboard content.') return json.dumps({'status':'failure', 'message':self.context.translate(msg)})
def __call__(self): context = self.context request = context.REQUEST # copied from delete_confirmation controller script if isLinked(context): parent = context.aq_inner.aq_parent title = safe_unicode(context.title_or_id()) try: lock_info = context.restrictedTraverse('@@plone_lock_info') except AttributeError: lock_info = None if lock_info is not None and lock_info.is_locked(): message = _pl_(u'${title} is locked and cannot be deleted.', mapping={u'title': title}) else: parent.manage_delObjects(context.getId()) message = _pl_(u'${title} has been deleted.', mapping={u'title': title}) transaction_note('Deleted %s' % context.absolute_url()) context.plone_utils.addPortalMessage(message) return context.REQUEST.RESPONSE.redirect( object.aq_inner.aq_parent.absolute_url()) else: #check for lock info try: lock_info = context.restrictedTraverse('@@plone_lock_info') except AttributeError: lock_info = None if lock_info is not None and lock_info.is_locked(): lock_view = getMultiAdapter((context, request), name="plone_lock_info") self.info = lock_view self.lock_is_stealable = self.info.lock_is_stealable() self.lock_info = self.info.lock_info() return self.locked_template() return self.template()
def renameObjectsByPaths(self, paths, new_ids, new_titles, handle_errors=True, REQUEST=None): failure = {} success = {} # use the portal for traversal in case we have relative paths portal = getToolByName(self, 'portal_url').getPortalObject() traverse = portal.restrictedTraverse for i, path in enumerate(paths): new_id = new_ids[i] new_title = new_titles[i] if handle_errors: sp = transaction.savepoint(optimistic=True) try: obj = traverse(path, None) obid = obj.getId() title = obj.Title() change_title = new_title and title != new_title changed = False if change_title: getSecurityManager().validate( obj, obj, 'setTitle', obj.setTitle ) obj.setTitle(new_title) notify(ObjectModifiedEvent(obj)) changed = True if new_id and obid != new_id: parent = aq_parent(aq_inner(obj)) parent.manage_renameObjects((obid,), (new_id,)) changed = True elif change_title: # the rename will have already triggered a reindex obj.reindexObject() if changed: success[path] = (new_id, new_title) except ConflictError: raise except Exception as e: if handle_errors: # skip this object but continue with sub-objects. sp.rollback() failure[path] = e else: raise transaction_note('Renamed %s' % str(success.keys())) return success, failure
def __call__(self): context = self.context msg = _(u'Copy or cut one or more items to paste.') msg = self.context.translate(msg) if context.cb_dataValid: try: context.manage_pasteObjects(self.request['__cp']) transaction_note( 'Pasted content to %s' % (context.absolute_url())) self.request.response.expireCookie('__fct', path='/') msg = _(u'Item(s) pasted.') msg = self.context.translate(msg) return msg, context.objectValues()[-1].UID() except ConflictError, e: raise e except ValueError: msg = _(u'Disallowed to paste item(s).') msg = self.context.translate(msg) raise Exception(msg)
def __call__(self): context = self.context parent = context.aq_inner.aq_parent title = safe_unicode(context.title_or_id()) try: lock_info = context.restrictedTraverse('@@plone_lock_info') except AttributeError: lock_info = None if lock_info is not None and lock_info.is_locked(): msg = _(u'${title} is locked and cannot be deleted.', mapping={u'title': title}) msg = self.context.translate(msg) raise Exception(msg) else: parent.manage_delObjects(context.getId()) msg = _(u'${title} has been deleted.', mapping={u'title': title}) msg = self.context.translate(msg) transaction_note('Deleted %s' % context.absolute_url()) return msg, None
def duplicate(self): context = aq_inner(self.context) plone_utils = context.plone_utils title = safe_unicode(context.title_or_id()) if not self.allowed(): msg = _(u'Permission denied to duplicate ${title}.', mapping={u'title' : title}) plone_utils.addPortalMessage(msg, 'error') raise Unauthorized, msg parent = aq_parent(context) try: parent.manage_copyObjects(context.getId(), self.request) except CopyError: message = _(u'${title} is not duplicable.', mapping={u'title' : title}) plone_utils.addPortalMessage(message, 'error') transaction_note('Copied object %s' % context.absolute_url()) msg=_(u'Duplicate failed to copy item.') redirect = self.request.RESPONSE.redirect if parent.cb_dataValid(): try: paste = parent.manage_pasteObjects(parent.REQUEST['__cp']) transaction_note('Pasted item to %s' % (parent.absolute_url())) plone_utils.addPortalMessage(_(u'Item duplicated.')) return redirect(parent.absolute_url() + '/' + paste[0]['new_id']) except ConflictError: raise except ValueError: msg=_(u'Disallowed to duplicate item.') except Unauthorized: msg=_(u'Unauthorized to duplicate item.') except: # fallback transaction.abort() # in case of error in redirecting to new duplicated item msg=_(u'Duplicate failed to paste item.') plone_utils.addPortalMessage(msg, 'error') return redirect(context.absolute_url())
def object_copy(self, ajax=False): self.protect() context = aq_inner(self.context) plone_utils = getToolByName(context, 'plone_utils') title = self.objectTitle() parent = aq_parent(context) try: parent.manage_copyObjects(context.getId(), self.request) message = _(u'${title} copied.', mapping={u'title': title}) utils.transaction_note('Copied object %s' % context.absolute_url()) plone_utils.addPortalMessage(message) except CopyError: message = _(u'${title} is not copyable.', mapping={u'title': title}) plone_utils.addPortalMessage(message, 'error') if ajax: pass else: return self.redirectReferer()
def __call__(self): mt = getToolByName(self.context, 'portal_membership') mt.logoutUser(self.request) transaction_note('Logged out') # Handle external logout requests from other portals next = self.request.get('next', None) portal_url = getToolByName(self.context, 'portal_url') if next is not None and portal_url.isURLInPortal(next): target_url = next else: target_url = self.request.URL1 + '/logged-out' pprops = getToolByName(self.context, 'portal_properties') site_properties = pprops.site_properties external_logout_url = site_properties.getProperty( 'external_logout_url') if external_logout_url: target_url = '{0:s}?next={1:s}'.format( external_logout_url, target_url) self.request.response.redirect(target_url)
def __call__(self): context = self.context title = safe_unicode(context.title_or_id()) if not has_permission('Copy or Move', context): msg = _(u'Permission denied to copy ${title}.', mapping={u'title': title}) msg = self.context.translate(msg) raise Unauthorized, msg parent = aq_parent(aq_inner(context)) try: parent.manage_copyObjects(context.getId(), self.request) except CopyError: msg = _(u'${title} is not copyable.', mapping={u'title': title}) msg = self.context.translate(msg) raise Exception, msg msg = _(u'${title} copied.', mapping={u'title': title}) msg = self.context.translate(msg) transaction_note('Copied object %s' % context.absolute_url()) return msg, None
def __call__(self): oblist = [] op = 0 context = Acquisition.aq_inner(self.context) paths = self.request["paths"] for path in paths: obj = context.restrictedTraverse(path) container = Acquisition.aq_parent(Acquisition.aq_inner(obj)) cp = getattr(container, self.method)([obj.getId()]) op, mdatas = CopySupport._cb_decode(cp) oblist.extend(mdatas) cp = CopySupport._cb_encode((op, oblist)) resp = self.request.response resp.setCookie("__cp", cp, path="%s" % CopySupport.cookie_path(self.request)) self.request["__cp"] = cp transaction_note(self.transaction_note % paths) message = _(self.message, mapping={u"count": len(paths)}) context.plone_utils.addPortalMessage(message) resp.redirect(context.absolute_url()) return ""
def __call__(self): eventid = 'UID_'+self.context.UID() parent = self.context.aq_inner.aq_parent title = safe_unicode(self.context.title_or_id()) try: lock_info = self.context.restrictedTraverse('@@plone_lock_info') except AttributeError: lock_info = None if lock_info is not None and lock_info.is_locked(): status = 'locked' message = plMF(u'${title} is locked and cannot be deleted.', mapping={u'title' : title}) else: parent.manage_delObjects(self.context.getId()) status = 'ok' message = plMF(u'${title} has been deleted.', mapping={u'title' : title}) transaction_note('Deleted %s' % self.context.absolute_url()) return json.dumps({'status':status, 'message':parent.translate(message), 'id':eventid})
def object_delete(self): self.protect() context = aq_inner(self.context) request = self.request parent = aq_parent(context) title = self.objectTitle() plone_utils = getToolByName(context, 'plone_utils') lock_info = getMultiAdapter((context, request), name='plone_lock_info') if lock_info is not None and lock_info.is_locked(): message = _(u'${title} is locked and cannot be deleted.', mapping={u'title': title}) plone_utils.addPortalMessage(message, type='error') return request.response.redirect(context.absolute_url()) else: parent.manage_delObjects(context.getId()) message = _(u'${title} has been deleted.', mapping={u'title': title}) utils.transaction_note('Deleted %s' % context.absolute_url()) plone_utils.addPortalMessage(message) return request.response.redirect(parent.absolute_url())
def __call__(self): title = safe_unicode(self.context.title_or_id()) mtool = getToolByName(self.context, 'portal_membership') if not mtool.checkPermission('Copy or Move', self.context): message = PLMF(u'Permission denied to copy ${title}.', mapping={u'title' : title}) status = 'error' raise json.dumps({'status':status, 'message':self.context.translate(message)}) try: lock_info = self.context.restrictedTraverse('@@plone_lock_info') except AttributeError: lock_info = None parent = aq_parent(aq_inner(self.context)) if lock_info is not None and lock_info.is_locked(): status = 'error' message = PLMF(u'${title} is locked and cannot be cut.', mapping={u'title' : title}) return json.dumps({'status': status, 'message': parent.translate(message)}) try: cp = parent.manage_cutObjects(self.context.getId()) status = 'copied' except CopyError: status = 'error' message = PLMF(u'${title} is not copyable.', mapping={u'title' : title}) return json.dumps({'status':status, 'message':parent.translate(message)}) message = PLMF(u'${title} copied.', mapping={u'title' : title}) transaction_note('Copied object %s' % self.context.absolute_url()) contextId = 'UID_'+self.context.UID() return json.dumps({'status':status, 'message':self.context.translate(message), 'cp':cp, 'id':contextId})
def __delete(self): context = self.context parent = context.aq_inner.aq_parent pp = "/".join(parent.getPhysicalPath())+"/" title = safe_unicode(context.title_or_id()) try: lock_info = context.restrictedTraverse('@@plone_lock_info') except AttributeError: lock_info = None if lock_info is not None and lock_info.is_locked(): message = _(u'${title} is locked and cannot be deleted.', mapping={u'title' : title}) messages.add(message, type=u"info") else: parent.manage_delObjects(context.getId()) message = _(u'${title} has been deleted.', mapping={u'title' : title}) transaction_note('Deleted %s' % context.absolute_url()) IStatusMessage(self.request).addStatusMessage(message, type='info') # There is a bug in Plone that will actually cause the message to be lost, sorry self.response.redirect(pp)
def object_paste(self): self.protect() context = aq_inner(self.context) plone_utils = getToolByName(context, 'plone_utils') msg = _(u'Copy or cut one or more items to paste.') if context.cb_dataValid(): try: context.manage_pasteObjects(context.REQUEST['__cp']) utils.transaction_note('Pasted content to %s' % ( context.absolute_url())) plone_utils.addPortalMessage(_(u'Item(s) pasted.')) return self.redirectReferer() except ConflictError: raise except ValueError: msg = _(u'Disallowed to paste item(s).') except Unauthorized: msg = _(u'Unauthorized to paste item(s).') except: # fallback msg = _(u'Paste could not find clipboard content.') plone_utils.addPortalMessage(msg, 'error') return self.redirectReferer()
#if not path.startswith(portal.absolute_url_path()): if not path.startswith("/".join(portal.getPhysicalPath())): msg = ( 'Path {} does not start ' 'with path to portal'.format(path) ) raise ValueError(msg) obj = traverse(path) if list(obj.getPhysicalPath()) != path.split('/'): msg = ( 'Path {} does not match ' 'traversed object physical path. ' 'This is likely an acquisition issue.'.format(path) ) raise ValueError(msg) obj_parent = aq_parent(aq_inner(obj)) obj_parent.manage_delObjects([obj.getId()]) success.append('%s (%s)' % (obj.getId(), path)) except ConflictError: raise except LinkIntegrityNotificationException: raise except Exception, e: if handle_errors: sp.rollback() failure[path] = e else: raise transaction_note('Deleted %s' % (', '.join(success))) return success, failure
sp = transaction.savepoint(optimistic=True) try: obj = traverse(path) obj_parent = aq_parent(aq_inner(obj)) obj_parent.manage_delObjects([obj.getId()]) success.append('%s (%s)' % (obj.getId(), path)) except ConflictError: raise except Exception, e: if handle_errors: sp.rollback() failure[path] = e log_exc() else: raise transaction_note('Deleted %s' % (', '.join(success))) return success, failure deleteObjectsByPaths = postonly(deleteObjectsByPaths) @security.public def transitionObjectsByPaths(self, workflow_action, paths, comment='', expiration_date=None, effective_date=None, include_children=False, handle_errors=True, REQUEST=None): log_deprecated("transitionObjectsByPaths is deprecated") failure = {} # use the portal for traversal in case we have relative paths portal = getToolByName(self, 'portal_url').getPortalObject() traverse = portal.restrictedTraverse for path in paths: if handle_errors:
##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters=state_change ##title=Delete the booking and redirect to booked object ## from Products.CMFPlone.utils import transaction_note from DateTime import DateTime # get the object booking = state_change.object booking_id = booking.getId() booking_center = booking.getBookingCenter() booked_object = booking.getBookableObject() transaction_note('Deleted %s from %s' % (booking_id, booking.absolute_url())) from Products.CMFCore.utils import getToolByName booking_tool = getToolByName(booking, 'portal_booking') booking_tool.cancelBooking(booking) # raise the object deleted method and pass # the folder you want to return to raiseError = context.REQUEST.get_header("raiseError", True) if raiseError == True: raise state_change.ObjectDeleted(booked_object) request = context.REQUEST response = request.RESPONSE
def __call__(self): request = self.context.REQUEST event_path = self.request.get('event_path', None) portal = getToolByName(self.context, 'portal_url').getPortalObject() url_list = event_path.split('/content_status_modify?workflow_action=') item_path = url_list[0] workflow_action = url_list[1] copyDict = getCopyObjectsUID(self.request) portal_url = portal.absolute_url() event_url = item_path.replace(portal_url, '') event = portal.restrictedTraverse(portal.id + event_url) eventPhysicalPath = '/'.join(event.getPhysicalPath()) plone_utils = getToolByName(event, 'plone_utils') contentEditSuccess = 0 plone_log = event.plone_log portal_workflow = event.portal_workflow transitions = portal_workflow.getTransitionsFor(event) transition_ids = [t['id'] for t in transitions] comment = self.request.get('comment', None) effective_date = self.request.get('effective_date', None) expiration_date = self.request.get('expiration_date', None) if workflow_action in transition_ids and not effective_date and event.EffectiveDate( ) == 'None': effective_date = DateTime() def editContent(obj, effective, expiry): kwargs = {} if effective and (isinstance(effective, DateTime) or len(effective) > 5): # may contain the year kwargs['effective_date'] = effective if expiry and (isinstance(expiry, DateTime) or len(expiry) > 5): # may contain the year kwargs['expiration_date'] = expiry event.plone_utils.contentEdit(obj, **kwargs) #You can transition content but not have the permission to ModifyPortalContent try: editContent(event, effective_date, expiration_date) contentEditSuccess = 1 except (Unauthorized, 'Unauthorized'): pass wfcontext = event # Create the note while we still have access to wfcontext note = 'Changed status of %s at %s' % (wfcontext.id, wfcontext.absolute_url()) if workflow_action in transition_ids: wfcontext = event.portal_workflow.doActionFor(event, workflow_action, comment=comment) if not wfcontext: wfcontext = event #The object post-transition could now have ModifyPortalContent permission. if not contentEditSuccess: try: editContent(wfcontext, effective_date, expiration_date) except (Unauthorized, 'Unauthorized'): pass transaction_note(note) eventDict = getMultiAdapter((event, self.request), ISolgemaFullcalendarEventDict)() return json.dumps(eventDict, sort_keys=True)
if not mt.testCurrentPassword(current): failMessage = _('Does not match current password.') context.plone_utils.addPortalMessage(failMessage, 'error') return context.password_form(context, REQUEST, error=failMessage) failMessage = context.portal_registration.testPasswordValidity( password, password_confirm) if failMessage: context.plone_utils.addPortalMessage(failMessage, 'error') return context.password_form(context, REQUEST, error=failMessage) member = mt.getAuthenticatedMember() try: mt.setPassword(password, domains, REQUEST=context.REQUEST) except AttributeError: failMessage = _( 'While changing your password an AttributeError occurred. This is usually caused by your user being defined outside the portal.' ) context.plone_utils.addPortalMessage(failMessage, 'error') return context.password_form(context, REQUEST, error=failMessage) from Products.CMFPlone.utils import transaction_note transaction_note('Changed password for %s' % (member.getUserName())) # added for ITIS context.credentials_updated(member.getUserName()) context.plone_utils.addPortalMessage(_('Password changed.')) return context.REQUEST.RESPONSE.redirect('%s/plone_memberprefs_panel' % context.absolute_url())