def action(self): #precondition if not self.kind.providedBy(self.context): raise ValueError("can t join something that is not a group") group = self.get_group() portal_state = component.getMultiAdapter((self.context, self.request), name=u'plone_portal_state') member = portal_state.member() if member is None: raise ValueError("you must be authenticated") group_state = component.getMultiAdapter((group, self.request), name=u'plone_context_state') state = group_state.workflow_state() role = "Contributor" if state == "open": #just add the localrole group.manage_setLocalRoles(member.getId(), [role]) group.reindexObject() event.notify( UserRolesModifiedOnObjectEvent(member.getUserName(), group)) msg = _(u"You have joined this group") elif state == "moderated" or state == "private": #You are supposed to already have view context to be here manager = group.restrictedTraverse("@@request_manager") request = manager.create() request.role = role manager.add(request) msg = _(u"You have request access to this group. " u"Please wait for an administrator to validate it") self.request.response.redirect(self.context.absolute_url()) status = IStatusMessage(self.request) status.add(msg)
def recaptcha(event): if not pk or not pr: return url = event.request.getURL() if event.request.method == 'POST' and url.endswith('/sendto_form'): messages = IStatusMessage(event.request) cr = event.request.form.get('g-recaptcha-response') if cr: URIReCaptcha = 'https://www.google.com/recaptcha/api/siteverify' remote_ip = get_ip(event.request) params = urllib.urlencode({ 'secret': pr, 'response': cr, 'remote_ip': remote_ip, }) data = urllib.urlopen(URIReCaptcha, params).read() result = json.loads(data) success = result.get('success', None) logging.getLogger("recaptcha").info( "Google reCaptcha: %s" % int(bool(success)) ) if success: return messages.add(_(u"Recaptcha failed."), type=u"info") else: messages.add(_(u"Recaptcha missing."), type=u"warning") event.request.form.pop("form.submitted", None)
def auto_translate(self): self.render_reportdata() seen = set() all_translatables = (self.translatable_data + self.translatable_extra_data) for value in all_translatables: if not value: continue if not isinstance(value, basestring): continue if value not in seen: retrieve_translation(self.country_code, value) seen.add(value) messages = IStatusMessage(self.request) messages.add( u"Auto-translation initiated, please refresh " u"in a couple of minutes", type=u"info") url = self.context.absolute_url() + '/@@view-report-data-2018' return self.request.response.redirect(url)
def add(self): request = self.request view = request.get('view', '') super(FavoriteActions, self).add() statusmsg = IStatusMessage(request) statusmsg.add(_("The item has been added to your favorites")) request.response.redirect(self.context.absolute_url() + '/' + view)
def __call__(self): portal = api.portal.get() messages = IStatusMessage(self.request) msg = events.purge_cache(portal, None) messages.add(msg, type=u"info") cp_url = api.portal.get().absolute_url() + '/@@cloudfront-controlpanel' self.request.response.redirect(cp_url)
def __call__(self): manager = self.context.restrictedTraverse(VIEW_NAME) if not manager.isin(): manager.add() status = IStatusMessage(self.request) status.add(_(u"Added to favorite")) self.request.response.redirect(self.nextURL())
def order_added(order, event): """Every time a order is added - change title.""" if order.Title(): return product = order.getProduct() quantity = order.getQuantity().decode('utf8', 'ignore') title = product.title_or_id().decode('utf8', 'ignore') unit = order.getUnit().decode('utf8', 'ignore') order.setTitle(u'%s %s di %s' % (quantity, unit, title)) order.reindexObject() company = order.getCompany() if not company: return owner = order.getOwner() params = {'email_message': NEW_ORDER_MAIL % (owner.getProperty('fullname', 'Utente'), quantity, title, '%s/@@company_owner' % order.absolute_url(), owner.getProperty('fullname', 'Utente'), owner.getProperty('cellphone'), owner.getProperty('email'), ), 'email_subject': NEW_ORDER_SUBJECT, 'phone_message': NEW_ORDER_SMS % (owner.getProperty('fullname', 'Utente'), owner.getProperty('cellphone', ''))} company_notify(company, params) status = IStatusMessage(order.REQUEST) status.add(_(u'Your order has been registered!'), type=u'order')
def handleOk(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return merge_vars = [] blocks = [] for key in data.keys(): value = data[key] if hasattr(value, 'output'): value = value.output if key.startswith('block_'): block = key.replace('block_','') blocks.append({'name': block, 'content': value}) continue value = data[key] merge_vars.append({'name': key, 'content': data[key]}) self.context.send(data['send_to'], merge_vars, blocks) messages = IStatusMessage(self.request) messages.add("Email was sent to %s." % (data['send_to'])) return self.request.response.redirect(self.context.absolute_url())
def action_addfield(self, action): data, errors = self.extractData() self.submitted = True if not errors: field_class = getattr(registry_field, data['field_type'], None) if field_class is None: notify( ActionErrorOccurred( action, WidgetActionExecutionError('field_type', Invalid('Invalid Field')))) return if data['name'] in self.context: notify( ActionErrorOccurred( action, WidgetActionExecutionError('name', Invalid('Field name already in use')))) return new_field = field_class(title=data['title'], required=data['required']) new_record = Record(new_field) self.context.records[data['name']] = new_record messages = IStatusMessage(self.request) messages.add(u"Successfully added field %s" % data['name'], type=u"info") return self.request.response.redirect('{url}/edit/{field}'.format( url=self.context.absolute_url(), field=data['name']))
def sync(self): redirect_url = self.context.absolute_url() messages = IStatusMessage(self.request) # Get API settings from the controlpanel api_settings = get_api_settings() # Create the API connection api_connection = APIConnection(api_settings) # Create the settings for the sync # Initiate the sync manager sync_options = {"api": api_connection, 'core': SYNC_CORE} sync_manager = SyncManager(sync_options) dateFrom = get_datetime_today(as_string=True) dateUntil = get_datetime_future(as_string=True) try: logger("[Status] Start syncing performance list.") performance_list = sync_manager.update_performance_list_by_date( date_from=dateFrom, date_until=dateUntil, create_and_unpublish=True) logger("[Status] Syncing performance list finished.") messages.add(u"Performance list is now synced.", type=u"info") except Exception as err: logger( "[Error] Error while requesting the sync for the performance list.", err) messages.add( u"Performance list failed to sync with the api. Please contact the website administrator.", type=u"error") raise Redirect(redirect_url)
def __call__(self): context = self.context portal_catalog = getToolByName(context, 'portal_catalog') currentpath = '/'.join(context.getPhysicalPath()) folder_contents = portal_catalog(path=dict(query=currentpath, depth=1), sort_on='getObjPositionInParent') if folder_contents: first_item = folder_contents[0] if getSecurityManager().checkPermission( permissions.ModifyPortalContent, context): messages = IStatusMessage(self.request) msg = _(u'redirect_info', default=_(u'You have been forwarded from "${title_from}" '\ '(<a href="${content_from}">contents</a> | '\ '<a href="${changeview_from}">change view</a>) to '\ '"${title_to}". Use the menu "Manage redirect" to '\ 'change this.'), mapping={'title_from': safe_unicode(context.title), 'title_to': safe_unicode(first_item.Title), 'content_from': context.absolute_url() + '/folder_contents', 'changeview_from': context.absolute_url() + '/select_default_view', }) messages.add(msg, type="info") self.request.response.redirect(first_item.getURL()) else: return self.template()
def __call__(self): manager = self.context.restrictedTraverse(VIEW_NAME) if not manager.isin(): manager.add() status = IStatusMessage(self.request) status.add(_(u"Added to favorite")) self.request.response.redirect(self.context.absolute_url())
def update(self): fields = field.Fields(IEnhancedUserDataSchema) if self.omitAccept: fields = fields.omit('accept') self.add(fields) self.form.fields['fullname'].field.required = True if 'username' in self.form.fields: self.form.fields['username'].field.title = u'Login name (official e-mail address)' self.form.fields['username'].field.description = u'''Please choose a login name. Your login name should be an email address. If you are using the system as a part of a course in a school/university, use the official email address from your institution (e.g. your @hi.is address). When you login the system this email address is you login name''' self.form.fields['email'].field.title = u'Preferred email address' self.form.fields['email'].field.description = u'The email address we should use when sending you forgotten passwords, etc' self.form.buttons = self.form.buttons.omit('cancel') # If at beginning of editing process, and editing ourself, add nag. if not self.request.form.get('userid', None): mt = getToolByName(self.context, 'portal_membership') mb = mt.getAuthenticatedMember() if not mb.getProperty('accept', False): messages = IStatusMessage(self.request) messages.add(u"Make sure you accept the terms and conditions below", type=u"info")
class StatusMessageFormatter(object): def __init__(self, request): self.request = request self.statusmessage = IStatusMessage(self.request) def __call__(self, kind, message): self.statusmessage.add(message, type=kind)
def handle_save(self, action): data, errors = self.extractData() if errors: return props = dict( title=data['title'], description=data.get('description', ''), remoteUrl=data['remoteUrl'], fileCategories=tuple( tuple(x.values()) for x in data['fileCategories'] ) ) lfa = LandFileApi(self.context.landfiles) try: landfile = lfa.add_with_filesize(**props) except (KeyError, OSError) as err: raise ActionExecutionError(Invalid(err.message)) messages = IStatusMessage(self.request) messages.add(u'Added landfile: {}'.format(landfile.title)) self.redirect_to_listing()
def render(self): messages = IStatusMessage(self.request) portal = api.portal.get() try: testfolder = portal['ca']['testingfolder'] api.content.find(context=testfolder, depth=0)[0] except: return "You must create default content with /create_test_content" # Create a new user. try: api.user.create( username="******", roles=('Anonymous', ), email="*****@*****.**", ) except: pass # with api.env.adopt_user(username="******"): # import ipdb; ipdb.set_trace() # api.user.grant_roles(username="******", roles=['OG1-Secretari']) # portal.ca.testingfolder.obert.planificada.punt.public.restrictedTraverse('@@view')() # print portal.ca.testingfolder.obert.planificada.punt.public.restrictedTraverse('@@view')() # api.user.grant_roles(username="******", roles=['OG2-Editor']) # portal.ca.testingfolder.obert.planificada.punt.public.restrictedTraverse('@@view')() # print portal.ca.testingfolder.obert.planificada.punt.public.restrictedTraverse('@@view')() api.user.delete(username='******') return "End of tests..." messages.add('TESTED FILE PERMISSIONS.', type='warning')
def render(self): # http:/session_url/change_migrated_to?value=False messages = IStatusMessage(self.request) if self.context.portal_type == 'genweb.organs.sessio': if self.request['value'] == 'True': elements = api.content.find( path=self.context.absolute_url_path()) for item in elements: value = item.getObject() value.migrated = True transaction.commit() elif self.request['value'] == 'False': elements = api.content.find( path=self.context.absolute_url_path()) for item in elements: value = item.getObject() value.migrated = False transaction.commit() else: return messages.add('migrated property set to: ' + str(self.request['value']), type='warning') self.request.response.redirect(self.context.absolute_url()) else: pass
def forceUpdateProfile(principal, event): """ Redirect to edit profile if user has not completed info about thematic and institutional domains """ site = getSite() if site is not None: membership = getToolByName(site, 'portal_membership') authenticated_user = membership.getAuthenticatedMember() t_d = authenticated_user.getProperty('thematic_domain', '') i_d = authenticated_user.getProperty('institutional_domain', '') if t_d == '' or i_d == '': request = getRequest() messages = IStatusMessage(request) messages.add( u"Please complete your profile adding your Professional " + "thematic domain and Institutional domain.", type=u"info") if request.get('came_from', None): came_from = request.get("came_from") request['came_from'] = '' request.form['came_from'] = '' request.form['next'] = '' # our one, the best: used on save in personal information request.SESSION.set("go_next", came_from) url = "{0}{1}".format(site.portal_url(), '/@@personal-information') request.RESPONSE.redirect(url)
def add(self): request = self.request view = request.get('view', '') super(FavoriteActions, self).add() statusmsg = IStatusMessage(request) statusmsg.add(_("The item has been added to your favorites")) request.response.redirect(self.context.absolute_url() + '/' + view)
def request_translation(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return fieldname = data.get("field_to_translate") filepath = self._make_html_document_from_field(fieldname) result = self._translate(filepath, data.get("model"), data.get("tr_mode")) translation = pam.translate(self.context, target_language="en") translation.title = self.context.title translation.description = self.context.description translation.text = self.context.text if result is not None: annotated = IAnnotations(translation) annotated[KEY] = result messages = IStatusMessage(self.request) messages.add(_(u"TGATE translation requested correctly")) return self.request.response.redirect(translation.absolute_url()) else: messages = IStatusMessage(self.request) messages.add(_(u"Error when requesting translations"), "error") return self.request.response.redirect(self.context.absolute_url())
def __call__(self): form = self.request.form source_lang = form.get('language', '') url = form.get('redirect_url') text = form.get('text', '') if not source_lang: source_lang = ITranslationContext(self.context).language logger.info("Source lang %s", source_lang) if not text: return self.request.response.redirect(url) text = normalize(text) delete_translation(text, source_lang) targetLanguages = self.request.form.get('targetLanguages', ['EN']) retrieve_translation(source_lang, text, targetLanguages, force=True) deps = ['translation'] event.notify(InvalidateMemCacheEvent(raw=True, dependencies=deps)) logger.info('Invalidate cache for dependencies: %s', ', '.join(deps)) messages = IStatusMessage(self.request) messages.add( u"Auto-translation initiated, please refresh " u"in a couple of minutes", type=u"info") return self.request.response.redirect(url)
def __call__(self): # check that we can actually access this form, # aka the current user has an advice to add or edit form = self.request.form cancelled = form.get('form.button.Cancel', False) submitted = form.get('form.button.Migrate', False) # test = form.get('form.button.Test', False) if submitted: # proceed, call the migration methdd results = self.migrate() messages = IStatusMessage(self.request) for migration_result in results: res_type = migration_result.get('type') res_infos = migration_result.get('infos') if res_infos.get('errors'): messages.add(u'Error when migrating "%s" type. Check the ' u'log for other informations.' % res_type, type=u"error") else: msg = translate( 'Migration applied succesfully for %s "%s" items.' % (res_infos.get('counter'), res_type), domain='plone.app.contenttypes') messages.add(msg, type=u"info") elif cancelled: self.request.response.redirect(form.get('form.HTTP_REFERER')) return self.index()
def render(self): user_roles = [] if self.request.get('REQUEST_METHOD') == 'POST': user = self.user() data = self.request.get('subscription_data') adapted = INotificationUnsubscriptions(self.context) user_roles = self.user_roles(translated_roles=False) to_delete = {} for item in data: copied_item = dict(item) rolename = copied_item.get('name') del copied_item['name'] if rolename in user_roles: notifications = set(NOTIFICATIONS_PER_ROLE.get(rolename)) deleted = notifications.difference(set(copied_item.keys())) to_delete[rolename] = deleted adapted.unsubscribe(user.getId(), notifications=to_delete) status = IStatusMessage(self.request) status.add('Subscription preferences saved correctly', type='info') url = self.context.absolute_url() return self.request.response.redirect(url) status = IStatusMessage(self.request) status.add('There was an error', type='error') return self.request.response.redirect(self.context.absolute_url())
def auto_translate(self): data = self.get_report_data() translatables = self.TRANSLATABLES seen = set() for compoundrow in data: rows = compoundrow.rows for row in rows: sub_title, values = row if compoundrow.field.name in translatables: for indx, value in enumerate(values): if not value: continue if value not in seen: country_code = self.available_countries[indx][0] retrieve_translation(country_code, value) seen.add(value) messages = IStatusMessage(self.request) messages.add( u"Auto-translation initiated, please refresh " u"in a couple of minutes", type=u"info") url = self.context.absolute_url() + '/@@view-report-data-2018' return self.request.response.redirect(url)
def forceUpdateProfile(principal, event): """ Redirect to edit profile if user has not completed info about thematic and institutional domains """ site = getSite() if site is not None: membership = getToolByName(site, 'portal_membership') authenticated_user = membership.getAuthenticatedMember() t_d = authenticated_user.getProperty('thematic_domain', '') i_d = authenticated_user.getProperty('institutional_domain', '') if t_d == '' or i_d == '': request = getRequest() messages = IStatusMessage(request) messages.add( u"Please complete your profile adding your Professional " + "thematic domain and Institutional domain.", type=u"info") if request.get('came_from', None): request['came_from'] = '' request.form['came_from'] = '' request.form['next'] = '' edit_profile_url = site.portal_url() + '/@@personal-information' request.RESPONSE.redirect(edit_profile_url)
def handleApply(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return messages = IStatusMessage(self.request) messages.add(u"Obrigado. Seu comentário foi enviado para aprovação.", type=u"info") nome = data['nome'] email = data['email'] comentario = data['comentario'] title = '{0} - {1}'.format(nome, email) normalizer = getUtility(IIDNormalizer) objid = self.generateIdForContext(self.context, normalizer.normalize(title)) pt = api.portal.get_tool('portal_types') type_info = pt.getTypeInfo('Comentario') content = type_info._constructInstance(self.context, objid, title=title) content.setNome(nome) content.setEmail(email) content.setCreated(datetime.datetime.now()) content.setComentario(comentario) return self.request.response.redirect(self.context.absolute_url())
def __call__(self): manager = self.context.restrictedTraverse(VIEW_NAME) if manager.isin(): manager.rm() status = IStatusMessage(self.request) status.add(_(u"Removed from favorite")) self.request.response.redirect(self.nextURL())
def auto_translate(self, data=None): if not data: data = self.get_report_data() # report_def = REPORT_DEFS[self.year][self.article] # translatables = report_def.get_translatable_fields() translatables = self.TRANSLATABLES seen = set() for table in data: muid, table_data = table for row in table_data: field, cells = row if field.name in translatables: for value in cells: if value not in seen: retrieve_translation(self.country_code, value) seen.add(value) messages = IStatusMessage(self.request) messages.add( u"Auto-translation initiated, please refresh " u"in a couple of minutes", type=u"info") url = self.context.absolute_url() + '/@@view-report-data-2018' return self.request.response.redirect(url)
def __call__(self): manager = self.context.restrictedTraverse(VIEW_NAME) if manager.isin(): manager.rm() status = IStatusMessage(self.request) status.add(_(u"Removed from favorite")) self.request.response.redirect(self.context.absolute_url())
def __call__(self): # check that we can actually access this form, # aka the current user has an advice to add or edit form = self.request.form cancelled = form.get('form.button.Cancel', False) submitted = form.get('form.button.Migrate', False) # test = form.get('form.button.Test', False) if submitted: # proceed, call the migration methdd results = self.migrate() messages = IStatusMessage(self.request) for migration_result in results: res_type = migration_result.get('type') res_infos = migration_result.get('infos') if res_infos.get('errors'): messages.add( u'Error when migrating "%s" type. Check the ' u'log for other informations.' % res_type, type=u"error") else: msg = translate( 'Migration applied succesfully for %s "%s" items.' % (res_infos.get('counter'), res_type), domain='plone.app.contenttypes') messages.add(msg, type=u"info") elif cancelled: self.request.response.redirect(form.get('form.HTTP_REFERER')) return self.index()
def __call__(self): # setup national assessment data for country_id, country_name in self.available_countries: self.setup_descriptor_level_assessment_data(country_id) country_data = self.overall_scores NATIONAL_ASSESSMENT_DATA[country_id] = country_data # setup regional assessment data view = RegDescriptorLevelAssessments(self, self.request) view.setup_descriptor_level_assessment_data() REGIONAL_ASSESSMENT_DATA[self.region_code] = view.overall_scores if 'edit-data' in self.request.form: url = "{}/edit".format(self.context.absolute_url()) return self.request.response.redirect(url) report_html = self.render_reportdata() self.report_html = report_html if 'translate' in self.request.form: for value in self._translatable_values: retrieve_translation(self.country_code, value) messages = IStatusMessage(self.request) messages.add( u"Auto-translation initiated, please refresh " u"in a couple of minutes", type=u"info") @timeit def render_html(): return self.index() return render_html()
def handleApply(self, action): data, errors = self.extractData() messages = IStatusMessage(self.request) if errors: return False try: source = "*****@*****.**" recipients = [recipients_voc.getTerm(data["recipient"]).value, ] subject = "[Sito Viola] Nuova mail da %(name)s" % data # Custom message with a name filled in message = u"""Hai ricevuto una mail di contatto dal sito violareggiocalabria.it: Dati del richiedente: Nome: %(name)s Email: %(email)s Telefono: %(phone)s Testo: %(text)s """ % (data) encoding = 'utf-8' message = MIMEText(message, 'plain', encoding) message['Reply-To'] = Header(data.get("email", source), encoding) send_mail(source, recipients, subject, message) messages.add(u"""La tua email è stata inviata con successo. Ti risponderemo prima possibile.""", type=u"info") except: messages.add(u"""C'è stato un problema nell'invio della posta. Riprova o contattaci telefonicamente.""", type=u"error") return False
def update(self): super(FoundationDashboard, self).update() if self.empty() and self.can_edit(): status = IStatusMessage(self.request) msg = _p(u"info_empty_dashboard") msg = translate(msg, domain='plone', context=self.request) status.add(msg, "info")
def queue_sync(self): redirect_url = self.context.absolute_url() QUEUE_LIMIT = 1 QUEUE_VIEW = "sync_person" queue_view_path = self.context.getPhysicalPath() queue_size = len(getUtility(ITaskQueue, name='sync')) queue_view_path_url = "/".join(queue_view_path) queue_view_url = "%s/%s" % (queue_view_path_url, QUEUE_VIEW) print("URL: %s" % (queue_view_url)) print("Queue size: %s" % (queue_size)) messages = IStatusMessage(self.request) if queue_size < QUEUE_LIMIT: sync_id = taskqueue.add(url=queue_view_url, queue="sync") print("Run sync with ID: '%s'" % (sync_id)) messages.add(u"Sync ID '%s' is now triggered." % (sync_id), type=u"info") else: messages.add( u"There is one sync currently running. Try again later.", type=u"warning") raise Redirect(redirect_url)
def sync(self): redirect_url = self.context.absolute_url() messages = IStatusMessage(self.request) try: # Get API settings from the controlpanel api_settings = get_api_settings() # Create the API connection api_connection = APIConnectionOrganizations(api_settings) # Create the settings for the sync # Initiate the sync manager sync_options = { "api": api_connection, 'core': SYNC_CORE_ORGANIZATIONS } sync_manager = SyncManagerOrganizations(sync_options) # Trigger the sync to update one organization logger("[Status] Start update of all organization.") person_data = sync_manager.update_organizations( create_and_unpublish=True) logger("[Status] Finished update of all organization.") except Exception as err: logger( "[Error] Error while requesting the sync for all organizations", err) messages.add( u"Sync of all organizations ID failed. Please contact the website administrator.", type=u"error") # Redirect to the original page raise Redirect(redirect_url)
def handleCancel(self, action): messages = IStatusMessage(self.request) messages.add(_(u"Review submission canceled"), type=u"info") redirect = self.request.response.redirect redirect(self.context.absolute_url())
def set_blacklist_status(self, manager, group_status, content_type_status, context_status): """Stay on the same page rather then redirecting to the portlet management view. """ superclass = super(CustomManageContextualPortlets, self) superclass.set_blacklist_status( manager, group_status, content_type_status, context_status ) # Give some feedback to the user, otherwise he might miss the fact # that the form has been submitted. messages = IStatusMessage(self.request) messages.add(text=_(u'Settings have been saved.'), type=u'success') base_url = str( getMultiAdapter((self.context, self.request), name='absolute_url') ) if self.request.get('HTTP_REFERER', '').endswith('manage-footer'): # This is the part we need to override from the parent class. self.request.response.redirect(base_url + '/manage-footer') else: self.request.response.redirect(base_url + '/@@manage-portlets') return ''
def update(self): if self.portal_state is None: self.portal_state = component.getMultiAdapter( (self.context, self.request), name=u'plone_portal_state' ) if self.portal_registry is None: self.portal_registry = component.getUtility(IRegistry) if self.embed_settings is None: self.embed_settings = {} registry = self.portal_registry self.embed_settings = registry.forInterface(EtherpadEmbedSettings) if self.etherpad_settings is None: registry = self.portal_registry self.etherpad_settings = registry.forInterface(EtherpadSettings) if self.etherpad is None: self.etherpad = HTTPAPI(self.context, self.request) self.etherpad.update() try: self.etherpad.checkToken() except ValueError: status = IStatusMessage(self.request) msg = _(u"Etherpad connection error") status.add(msg) self.etherpad_iframe_url = "" return self._updateName() self._updateAuthor() self._updateId() self._updateSession() self._updateIframe()
def handleApply(self, action): data, errors = self.extractData() # get write access to the database portal_state = getMultiAdapter( (self.context, self.request), name=u'plone_portal_state' ) navigation_root = portal_state.navigation_root() writer = IEventDatabaseWriteProvider(navigation_root) if errors: self.status = self.formErrorsMessage return for key in EventOrgEditForm.context_attributes: value = data.get(key) setattr(self.context, key, value) org_data = {} for key in EventOrgEditForm.database_attributes: org_data[key] = data.get(key) if writer.db_org_id == 0: db_org_id = writer.insertOrg(**org_data) setattr(navigation_root, 'dbOrgId', db_org_id) else: writer.updateOrgData(**org_data) writer.updateOrgCats(data.get('org_categories', [])) messages = IStatusMessage(self.request) messages.add(u"Organization event settings updated", type=u"info") self.request.response.redirect("caledit")
def download_translation(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return registry = getUtility(IRegistry) base_url = registry.get("tgate.tgate_server_url") username = registry.get("tgate.tgate_server_username") password = registry.get("tgate.tgate_server_password") client = TGateClient(base_url, username, password) annotated = IAnnotations(self.context) document_id = annotated.get(KEY, None) if document_id: response = client.download_document(document_id) if response.get("status") == "success": text = response.get("data", {}).get("contents", "") self._make_field_from_html_document( text, data.get("field_to_translate") ) messages = IStatusMessage(self.request) messages.add(_(u"Translation downloaded correctly"), "info") return self.request.response.redirect(self.context.absolute_url()) messages = IStatusMessage(self.request) messages.add(_(u"Error when downloading the translation"), "error") return self.request.response.redirect(self.context.absolute_url())
def __call__(self): if 'edit-data' in self.request.form: url = "{}/edit".format(self._country_folder.absolute_url()) return self.request.response.redirect(url) if 'download_pdf' in self.request.form: self.render_header = False report_html = self.render_reportdata() self.report_html = report_html if 'download' in self.request.form: return self.download() if 'download_pdf' in self.request.form: return self.download_pdf() if 'translate' in self.request.form: for value in self._translatable_values: retrieve_translation(self.country_code, value) messages = IStatusMessage(self.request) messages.add( u"Auto-translation initiated, please refresh " u"in a couple of minutes", type=u"info") @timeit def render_html(): return self.index() return render_html()
def render(self): user_roles = [] if self.request.get('REQUEST_METHOD') == 'POST': user = self.user() data = self.request.get('subscription_data') adapted = INotificationUnsubscriptions(self.context) user_roles = self.user_roles(translated_roles=False) to_delete = {} for item in data: copied_item = dict(item) rolename = copied_item.get('name') del copied_item['name'] if rolename in user_roles: notifications = set(NOTIFICATIONS_PER_ROLE.get(rolename)) deleted = notifications.difference(set(copied_item.keys())) to_delete[rolename] = deleted adapted.unsubscribe(user.getId(), notifications=to_delete) status = IStatusMessage(self.request) status.add('Subscription preferences saved correctly', type='info') url = self.context.absolute_url() return self.request.response.redirect(url) status = IStatusMessage(self.request) status.add('There was an error', type='error') return self.request.response.redirect(self.context.absolute_url())
def action_addfield(self, action): data, errors = self.extractData() self.submitted = True if not errors: field_class = getattr(registry_field, data['field_type'], None) if field_class is None: notify( ActionErrorOccurred( action, WidgetActionExecutionError('field_type', Invalid('Invalid Field')))) return if data['name'] in self.context: notify( ActionErrorOccurred( action, WidgetActionExecutionError( 'name', Invalid('Field name already in use')))) return new_field = field_class(title=data['title'], required=data['required']) new_record = Record(new_field) self.context.records[data['name']] = new_record messages = IStatusMessage(self.request) messages.add(u"Successfully added field %s" % data['name'], type=u"info") return self.request.response.redirect('{url}/edit/{field}'.format( url=self.context.absolute_url(), field=data['name']))
def block_access(self, workspace): messages = IStatusMessage(workspace.REQUEST) messages.add( u"The content you tried to access is available only for \ approved participants. Please log in.", type=u"info") return workspace.REQUEST.response.redirect( workspace.aq_parent.absolute_url())
def _back_to_review_page(self, message=None): if message: messages = IStatusMessage(self.request) messages.add(message, type='info') portal_url = api.portal.get().absolute_url() target = '{0}/@@pratica-pendentes'.format(portal_url) return self.request.response.redirect(target)
def remove(self): super(FavoriteActions, self).remove() statusmsg = IStatusMessage(self.request) statusmsg.add(_("The item has been removed from your favorites")) site_properties = getToolByName(self.context, 'portal_properties').site_properties useView = self.context.portal_type in site_properties.typesUseViewActionInListings url = self.context.absolute_url() + (useView and "/view" or "") self.request.response.redirect(url)
def render(self): user = self.user() adapted = INotificationUnsubscriptions(self.context) adapted.unsubscribe(user.getId()) status = IStatusMessage(self.request) status.add('Local subscription preferences cleared', type='info') return self.request.response.redirect(self.context.absolute_url())
def remove(self): super(FavoriteActions, self).remove() statusmsg = IStatusMessage(self.request) statusmsg.add(_("The item has been removed from your favorites")) site_properties = getToolByName(self.context, 'portal_properties').site_properties useView = self.context.portal_type in site_properties.typesUseViewActionInListings url = self.context.absolute_url() + (useView and "/view" or "") self.request.response.redirect(url)
def render(self): user = self.user() adapted = INotificationUnsubscriptions(self.context) adapted.unsubscribe(user.getId()) status = IStatusMessage(self.request) status.add('Local subscription preferences cleared', type='info') return self.request.response.redirect(self.context.absolute_url())
class StatusMessageFormatter(object): def __init__(self, request): self.request = request self.statusmessage = IStatusMessage(self.request) def __call__(self, kind, message): self.statusmessage.add(message, type=kind)
def free_reference_prefix(self, prefix_num): refs = ReferenceNumberPrefixAdpater(self.context) refs.free_number(prefix_num) notify(RepositoryPrefixUnlocked(self.context, prefix_num)) messages = IStatusMessage(self.request) messages.add(_("statmsg_prefix_unlocked", default=u"Reference prefix has been unlocked."), type=u"info")
def render(self): session = Session() r = self.request content = session.query(db.PessoaOrigem).get((r.protocolo_id, r.pessoa_id)) session.delete(content) session.flush() status = IStatusMessage(self.request) status.add(_(u'Registro removido.'), 'info') go('show-protocolo', id=r.protocolo_id)
def updateSelectedVCards(self): status = IStatusMessage(self.request) widget = self.widgets.get('users') if widget.extract() == NO_VALUE: status.add(_(u"You first need to choose the users"), "error") return self.updateVCards(member_ids=self.getChosenMembers()) return status.add(_(u"The selected users' vCards are being updated in " u"the background."), "info")
def _back_to(self, message=None): observatorio = self.context.absolute_url() if message: messages = IStatusMessage(self.request) messages.add(message, type='info') return self.request.response.redirect(observatorio)
def render(self): session = Session() content = session.query(db.Transicao).get(self.request.id) fluxo_id = content.fluxo_id session.delete(content) session.flush() status = IStatusMessage(self.request) status.add(_(u"Registro removido."), "info") go("list-transicao", fluxo_id=fluxo_id)
def render(self): session = Session() r = self.request content = session.query(db.PessoaDestino).get((r.protocolo_id, r.pessoa_id)) session.delete(content) session.flush() status = IStatusMessage(self.request) status.add(_(u"Registro removido."), "info") go("show-protocolo", id=r.protocolo_id)
def _back_to_admin(self, message=None): portal_url = api.portal.get().absolute_url() fale_conosco = '{0}/@@fale-conosco-admin/'.format(portal_url) if message: messages = IStatusMessage(self.request) messages.add(message, type='info') return self.request.response.redirect(fale_conosco)
def render(self): session = Session() r = self.request content = session.query(db.Referencia).get((r.protocolo_id, r.referencia_id)) session.delete(content) session.flush() status = IStatusMessage(self.request) status.add(_(u"Registro removido."), "info") go("list-referencia", protocolo_id=r.protocolo_id)
def render(self): session = Session() api = getUtility(ISPDOAPI) pessoa_id = api.getAuthPessoa().id content = session.query(db.Notificacao).get((pessoa_id, self.request.protocolo_id)) session.delete(content) session.flush() status = IStatusMessage(self.request) status.add(_(u"Registro removido."), "info") go("list-notificacao")