def post(self): context = self._prepare() try: data_dict = logic.clean_dict( dictization_functions.unflatten( logic.tuplize_dict(logic.parse_params(request.form)))) data_dict.update(logic.clean_dict( dictization_functions.unflatten( logic.tuplize_dict(logic.parse_params(request.files))) )) except dictization_functions.DataError: base.abort(400, _(u'Integrity Error')) context[u'message'] = data_dict.get(u'log_message', u'') try: captcha.check_recaptcha(request) except captcha.CaptchaError: error_msg = _(u'Bad Captcha. Please try again.') h.flash_error(error_msg) return self.get(data_dict) try: error_summary = {} if not data_dict.get('image_upload'): error_summary[u'image_url'] = u'Do not leave it blank' if not data_dict.get('password1'): error_summary[u'password1'] = u'Vui l\xf2ng nh\u1eadp m\u1eadt kh\u1ea9u' if not data_dict.get('password2'): error_summary[u'password2'] = u'Vui l\xf2ng nh\u1eadp m\u1eadt kh\u1ea9u' if not error_summary: logic.get_action(u'user_create')(context, data_dict) else: return self.get(data_dict, [], error_summary) except logic.NotAuthorized: base.abort(403, _(u'Unauthorized to create user %s') % u'') except logic.NotFound: base.abort(404, _(u'User not found')) except logic.ValidationError as e: errors = e.error_dict error_summary = e.error_summary return self.get(data_dict, errors, error_summary) if g.user: # #1799 User has managed to register whilst logged in - warn user # they are not re-logged in as new user. h.flash_success( _(u'User "%s" is now registered but you are still ' u'logged in as "%s" from before') % (data_dict[u'name'], g.user)) if authz.is_sysadmin(g.user): # the sysadmin created a new user. We redirect him to the # activity page for the newly created user return h.redirect_to(u'user.activity', id=data_dict[u'name']) else: return base.render(u'user/logout_first.html') # log the user in programatically resp = h.redirect_to(u'user.me') set_repoze_user(data_dict[u'name'], resp) return resp
def post(self) -> Union[Response, str]: context = self._prepare() try: data_dict = logic.clean_dict( dictization_functions.unflatten( logic.tuplize_dict(logic.parse_params(request.form)))) data_dict.update( logic.clean_dict( dictization_functions.unflatten( logic.tuplize_dict(logic.parse_params( request.files))))) except dictization_functions.DataError: base.abort(400, _(u'Integrity Error')) try: captcha.check_recaptcha(request) except captcha.CaptchaError: error_msg = _(u'Bad Captcha. Please try again.') h.flash_error(error_msg) return self.get(data_dict) try: user_dict = logic.get_action(u'user_create')(context, data_dict) except logic.NotAuthorized: base.abort(403, _(u'Unauthorized to create user %s') % u'') except logic.NotFound: base.abort(404, _(u'User not found')) except logic.ValidationError as e: errors = e.error_dict error_summary = e.error_summary return self.get(data_dict, errors, error_summary) user = current_user.name if user: # #1799 User has managed to register whilst logged in - warn user # they are not re-logged in as new user. h.flash_success( _(u'User "%s" is now registered but you are still ' u'logged in as "%s" from before') % (data_dict[u'name'], user)) if authz.is_sysadmin(user): # the sysadmin created a new user. We redirect him to the # activity page for the newly created user if "activity" in g.plugins: return h.redirect_to(u'activity.user_activity', id=data_dict[u'name']) return h.redirect_to(u'user.read', id=data_dict[u'name']) else: return base.render(u'user/logout_first.html') # log the user in programatically userobj = model.User.get(user_dict["id"]) if userobj: login_user(userobj) resp = h.redirect_to(u'user.me') return resp
def _clean_request_form(self): form_data = logic.clean_dict( dict_fns.unflatten( logic.tuplize_dict( logic.parse_params(toolkit.request.form, ignore_keys=CACHE_PARAMETERS)))) form_data.update( logic.clean_dict( dict_fns.unflatten( logic.tuplize_dict( logic.parse_params(toolkit.request.files))))) return form_data
def edit(self, id): """ Allows a user to edit an existing feed, potentially changing the URL and in doing so re-triggering validation of the feed. """ self._check_auth("feed_update") data, errors, error_summary = {}, {}, {} c.feed = feedlogic.get_feed(id) if not c.feed: base.abort(404, _("Feed {name} does not exist".format(name=id))) if base.request.method == "POST": try: data = logic.clean_dict( df.unflatten( logic.tuplize_dict( logic.parse_params(base.request.params) ))) feed = feedlogic.edit_feed(c.feed, data) h.redirect_to(controller=self.controller_path, action='read', id=feed.name) except feedmodels.FeedException: error = {'url': [u'Failed to load feed']} error_summary = {u'URL': u'Failed to load feed'} data = c.feed.as_dict() except df.DataError: base.abort(400, _(u'Integrity Error')) except logic.ValidationError, e: errors = e.error_dict error_summary = e.error_summary
def new(self): """ Allows the user to create a new feed and performs an initial fetch of the feed during validation. """ self._check_auth("feed_create") data, errors, error_summary = {}, {}, {} if base.request.method == "POST": try: dd = logic.clean_dict( df.unflatten( logic.tuplize_dict( logic.parse_params(base.request.params) ) ) ) feed = feedlogic.create_feed(dd) h.redirect_to( controller=self.controller_path, action='read', id=feed.name) except feedmodels.FeedException: error = {'url': [u'Failed to load feed']} error_summary = {u'URL': u'Failed to load feed'} data = dd except df.DataError: base.abort(400, _(u'Integrity Error')) except logic.ValidationError, e: errors = e.error_dict error_summary = e.error_summary
def _save_new(self, context): try: data_dict = clean_dict( dict_fns.unflatten(tuplize_dict(parse_params(request.params)))) data_dict['group'] = data_dict['organization'] member = toolkit.get_action('member_request_create')(context, data_dict) redirect_to_src_page = asbool( config.get('ytp.requests.redirect_to_src_page', 'true')) if redirect_to_src_page: helpers.flash_success( _('Thank you for your request. The organisation admins were notified.' )) redirect_to(request.referer) else: helpers.redirect_to('member_request_show', member_id=member['id']) except NotAuthorized: abort(401, self.not_auth_message) except NotFound: abort(404, _('Item not found')) except dict_fns.DataError: abort(400, _(u'Integrity Error')) except ValidationError, e: errors = e.error_dict error_summary = e.error_summary helpers.flash_error( _('There was an error saving your request. Please try again.')) return self.new(data_dict, errors, error_summary)
def updatePackagePublishedStatus(self): if request.method != 'POST' or not request.is_xhr: return { 'success': False, 'message': toolkit._("Bad request - JSON Error: No request body data") } context = { 'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj } data = clean_dict(unflatten(tuplize_dict(parse_params( request.params)))) package_id = data.get("package_id", None) status = data.get("status", None) try: result = toolkit.get_action( 'geoserver_update_package_published_status')(context, { 'package_id': package_id, 'status': status }) except: return { 'success': False, 'message': toolkit. _("An error occured while processing your request, please contact your administrator." ) }
def new_resource(self, id, data=None, errors=None, error_summary=None): ''' Before creating a resource into CKAN, we request WSO2 ESB to add a subscription to the related Topic. ''' if request.method == 'POST' and not data: # Recogniced new resource form POST, extract variables. postdata = data or clean_dict(unflatten(tuplize_dict(parse_params(request.POST)))) if 'save' in postdata and 'url' in postdata: package_data = get_action('package_show')({'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj}, {'id': id}) topic = getTopicFromPackageData(package_data) # Add a new subscription for the topic named after the dataset, pointing to the URL given. brokerclient = getBrokerClient() try: result = brokerclient.subscribe(topic, postdata['url']) except Py4JJavaError, e: # Errors are propagated to the CKAN controller below to prevent new resource creation. error_message = str(e) if 'Error While Subscribing :Cannot initialize URI with empty parameters.' in error_message: error_message = _('Error While Subscribing: Cannot initialize URI with empty parameters.') if 'org.apache.axis2.AxisFault: Connection refused' in error_message: error_message = _('Error While Subscribing: Cannot connect to WSO2 ESB.') if errors and isinstance(errors, dict): errors.update({ 'error': error_message }) else: errors = { 'error': error_message } data = postdata error_summary = { _('WSO2 ESB'): error_message }
def config(self): items = self._get_config_form_items() data = request.POST if 'save' in data: try: # really? data_dict = logic.clean_dict( dict_fns.unflatten( logic.tuplize_dict( logic.parse_params( request.POST, ignore_keys=CACHE_PARAMETERS)))) del data_dict['save'] data = logic.get_action('config_option_update')( {'user': c.user}, data_dict) except logic.ValidationError, e: errors = e.error_dict error_summary = e.error_summary vars = {'data': data, 'errors': errors, 'error_summary': error_summary, 'form_items': items} return base.render('admin/config.html', extra_vars=vars) h.redirect_to(controller='admin', action='config')
def image_uploaded(): '''View function to handle uploading arbitrary images for the home page. Passes `'image_url': 'submitted-image-path'` to template/view function. ''' data_dict = {} try: # Cleanup the data_dict for the uploader. req = request.form.copy() req.update(request.files.to_dict()) data_dict = logic.clean_dict( dict_fns.unflatten( logic.tuplize_dict( logic.parse_params(req, ignore_keys=CACHE_PARAMETERS)))) # Upload the image. upload = uploader.get_uploader('home') upload.update_data_dict(data_dict, 'image_url', 'image_upload', 'clear_upload') upload.upload(uploader.get_max_image_size()) image_url = '' # Build and return the image url. for key, value in data_dict.iteritems(): if key == 'image_url' and value and not value.startswith('http')\ and not value.startswith('/'): image_path = 'uploads/home/' value = h.url_for_static('{0}{1}'.format(image_path, value)) image_url = value except Exception as e: log.error(e) return h.redirect_to(u'ontario_theme.image_uploader', image_url=image_url)
def resource_edit(self, id, resource_id, data=None, errors=None, error_summary=None): if request.method == 'POST' and not data: data = data or clean_dict(unflatten(tuplize_dict(parse_params( request.POST)))) # we don't want to include save as it is part of the form del data['save'] context = {'model': model, 'session': model.Session, 'api_version': 3, 'for_edit': True, 'user': c.user or c.author, 'auth_user_obj': c.userobj} data['package_id'] = id try: if resource_id: data['id'] = resource_id get_action('resource_update')(context, data) else: get_action('resource_create')(context, data) except ValidationError, e: errors = e.error_dict error_summary = e.error_summary return self.resource_edit(id, resource_id, data, errors, error_summary) except NotAuthorized: abort(401, _('Unauthorized to edit this resource'))
def handle_submit(self, id): data = clean_dict( dict_fns.unflatten(tuplize_dict(parse_params(request.params)))) data['dataset_url'] = toolkit.url_for(controller='package', action='read', id=id, qualified=True) package = get_action('package_show')(None, {'id': id}) self.fail_if_private(package, data['dataset_url']) # Comma separated config var to_addrs = config['ckanext.ands.support_emails'].split(',') subject = 'DataPortal Support: Request to publish dataset' body = base.render('package/doi_email.text', extra_vars=data) for email in to_addrs: mail_recipient('Dataportal support', email, subject, body) data['package_id'] = package['id'] data['user_id'] = c.userobj.id doi_request = DoiRequest(**data) Session.add(doi_request) Session.commit() h.flash_success("DOI Request sent") return toolkit.redirect_to(data['dataset_url'])
def post(self, id): context = {u'model': model} data_dict = logic.clean_dict( dictization_functions.unflatten( logic.tuplize_dict(logic.parse_params(request.form)))) data_dict[u'user'] = id try: token = logic.get_action(u'api_token_create')(context, data_dict)[u'token'] except logic.NotAuthorized: base.abort(403, _(u'Unauthorized to create API tokens.')) except logic.ValidationError as e: errors = e.error_dict error_summary = e.error_summary return self.get(id, data_dict, errors, error_summary) copy_btn = dom_tags.button( dom_tags.i(u'', {u'class': u'fa fa-copy'}), { u'type': u'button', u'class': u'btn btn-default btn-xs', u'data-module': u'copy-into-buffer', u'data-module-copy-value': ensure_str(token) }) h.flash_success( _(u"API Token created: <code style=\"word-break:break-all;\">" u"{token}</code> {copy}<br>" u"Make sure to copy it now, " u"you won't be able to see it again!").format( token=ensure_str(token), copy=copy_btn), True) return h.redirect_to(u'user.api_tokens', id=id)
def _save_edit(self, id, context): try: data_dict = logic.clean_dict( unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') data_dict['id'] = id if data_dict['password1'] and data_dict['password2']: identity = { 'login': c.user, 'password': data_dict['old_password'] } auth = authenticator.UsernamePasswordAuthenticator() if auth.authenticate(request.environ, identity) != c.user: raise UsernamePasswordError # MOAN: Do I really have to do this here? if 'activity_streams_email_notifications' not in data_dict: data_dict['activity_streams_email_notifications'] = False user = get_action('user_update')(context, data_dict) h.flash_success(_('Profile updated')) h.redirect_to(controller='user', action='read', id=user['name']) except NotAuthorized: abort(401, _('Unauthorized to edit user %s') % id) except NotFound, e: abort(404, _('User not found'))
def _add_or_reply(self, dataset_name): """ Allows the user to add a comment to an existing dataset """ context = {'model': model, 'user': c.user} # Auth check to make sure the user can see this package ctx = context ctx['id'] = dataset_name check_access('package_show', ctx, {'id': dataset_name}) try: c.pkg_dict = get_action('package_show')(context, {'id': dataset_name}) c.pkg = context['package'] except: abort(401, _('Unauthorized')) if not c.user: abort(401, _('Unauthorized')) errors = {} if request.method == 'POST': data_dict = clean_dict(unflatten( tuplize_dict(parse_params(request.POST)))) data_dict['parent_id'] = c.parent.id if c.parent else None data_dict['url'] = '/dataset/%s' % c.pkg.name data_dict['comment'] = data_dict['comment'][:5000] success = False try: res = get_action('comment_create')(context, data_dict) success = True except ValidationError, ve: errors = ve.error_dict except Exception, e: abort(401, _('Unauthorized'))
def _save_new(self, context): try: data_dict = logic.clean_dict(df.unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') captcha.check_recaptcha(request) # Extra: Create username from email email = data_dict.get('email', '') email_user = email.split('@')[0] name = re.sub('[^a-z0-9_\-]', '_', email_user) # Append num so it becames unique (search inside deleted as well) session = context['session'] user_names = model.User.search(name, session.query(model.User)).all() user_names = map(lambda u: u.name, user_names) while name in user_names: m = re.match('^(.*?)(\d+)$', name) if m: name = m.group(1) + str(int(m.group(2)) + 1) else: name = name + '2' data_dict['name'] = name user = get_action('user_create')(context, data_dict) except NotAuthorized: abort(401, _('Unauthorized to create user %s') % '') except NotFound, e: abort(404, _('User not found'))
def follow_details(self, data=None, errors=None, error_summary=None): ''' Step 4: user follows key entities :param data: :param errors: :param error_summary: :return: ''' data_dict = logic.clean_dict( unflatten(logic.tuplize_dict(logic.parse_params(request.params)))) name = c.user or data_dict['id'] user_obj = model.User.get(name) user_id = user_obj.id context = { 'model': model, 'session': model.Session, 'user': user_obj.name, 'auth_user_obj': c.userobj } try: ue_dict = self._get_ue_dict(user_id, user_model.HDX_ONBOARDING_FOLLOWS) get_action('user_extra_update')(context, ue_dict) except NotAuthorized: return OnbNotAuth except NotFound, e: return OnbUserNotFound
def member_new(self, id): context = { 'model': model, 'session': model.Session, 'user': c.user or c.author } #self._check_access('group_delete', context, {'id': id}) try: if request.method == 'POST': data_dict = clean_dict( unflatten(tuplize_dict(parse_params(request.params)))) data_dict['id'] = id c.group_dict = self._action('group_member_create')(context, data_dict) self._redirect_to(controller='group', action='members', id=id) else: user = request.params.get('user') if user: c.user_dict = get_action('user_show')(context, { 'id': user }) c.user_role = ckan.new_authz.users_role_for_group_or_org( id, user) or 'member' else: c.user_role = 'member' c.group_dict = self._action('group_show')(context, {'id': id}) c.roles = self._action('member_roles_list')(context, {}) except NotAuthorized: abort(401, _('Unauthorized to add member to group %s') % '') except NotFound: abort(404, _('Group not found')) return self._render_template('group/member_new.html')
def _send_suggestion(self, context): try: data_dict = logic.clean_dict( unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') c.form = data_dict['name'] captcha.check_recaptcha(request) #return base.render('suggest/form.html') except logic.NotAuthorized: base.abort(401, _('Not authorized to see this page')) except captcha.CaptchaError: error_msg = _(u'Bad Captcha. Please try again.') h.flash_error(error_msg) return self.suggest_form(data_dict) errors = {} error_summary = {} if (data_dict["email"] == ''): errors['email'] = [u'Missing Value'] error_summary['email'] = u'Missing value' if (data_dict["name"] == ''): errors['name'] = [u'Missing Value'] error_summary['name'] = u'Missing value' if (data_dict["suggestion"] == ''): errors['suggestion'] = [u'Missing Value'] error_summary['suggestion'] = u'Missing value' if len(errors) > 0: return self.suggest_form(data_dict, errors, error_summary) else: # #1799 User has managed to register whilst logged in - warn user # they are not re-logged in as new user. mail_to = config.get('email_to') recipient_name = 'CKAN Surrey' subject = 'CKAN - Dataset suggestion' body = 'Submitted by %s (%s)\n' % (data_dict["name"], data_dict["email"]) if (data_dict["category"] != ''): body += 'Category: %s' % data_dict["category"] body += 'Request: %s' % data_dict["suggestion"] try: mailer.mail_recipient(recipient_name, mail_to, subject, body) except mailer.MailerException: raise return base.render('suggest/suggest_success.html')
def dataportal_admin(): # items = self._get_config_form_items() if request.method == "POST": data = request.form try: data_dict = logic.clean_dict( dict_fns.unflatten(logic.tuplize_dict(logic.parse_params(request.form, ignore_keys=CACHE_PARAMETERS))) ) del data_dict["save"] data = logic.get_action("config_option_update")({"user": g.user}, data_dict) except logic.ValidationError as e: errors = e.error_dict error_summary = e.error_summary extra_vars = {"data": data, "errors": errors, "error_summary": error_summary} return toolkit.render("admin/dataportal.html", extra_vars=extra_vars) return toolkit.redirect_to("dataportaltheme_blueprint.dataportal_admin") else: admin_schema = schema.update_configuration_schema() data = {} for key in admin_schema: data[key] = config.get(key) extra_vars = {"data": data, "errors": {}} return toolkit.render("admin/dataportal.html", extra_vars=extra_vars)
def post(self): context = self._prepare() try: data_dict = logic.clean_dict( dictization_functions.unflatten( logic.tuplize_dict(logic.parse_params(request.form)))) except dictization_functions.DataError: base.abort(400, _(u'Integrity Error')) try: sub_theme = logic.get_action(u'sub_theme_create')(context, data_dict) except logic.NotAuthorized: base.abort(403, _(u'Unauthorized to create a sub-theme')) except logic.ValidationError as e: errors = e.error_dict error_summary = e.error_summary return self.get(data_dict, errors, error_summary) try: kwh_data = { 'type': 'sub-theme', 'content': sub_theme.get('title'), 'sub_theme': sub_theme.get('id') } logic.get_action(u'kwh_data_create')(context, kwh_data) except Exception as e: log.debug('Error while storing KWH data: %s' % str(e)) return h.redirect_to(u'sub_theme.read', name=sub_theme.get(u'name'))
def post(self): try: req = request.form.copy() req.update(request.files.to_dict()) data_dict = logic.clean_dict( dict_fns.unflatten( logic.tuplize_dict( logic.parse_params(req, ignore_keys=CACHE_PARAMETERS)))) del data_dict['save'] data = logic.get_action(u'config_option_update')({ u'user': g.user }, data_dict) except logic.ValidationError as e: items = _get_config_options() data = request.form errors = e.error_dict error_summary = e.error_summary vars = dict(data=data, errors=errors, error_summary=error_summary, form_items=items, **items) return base.render(u'admin/config.html', extra_vars=vars) return h.redirect_to(u'admin.config')
def new(self, data=None, errors=None, error_summary=None): """ This overrides the PackageController method to redirect to the show dataset view without having to go to the add data view. The difference is the inclusion of what the dataset type is. If the save param finish is included or any exceptions happen it will either abort or call the super new method. """ log.info('ckanext-bcgov.controllers.package:EDCPackageController.new overriding ckan\'s method') save_action = toolkit.request.params.get('save') data_dict = logic.clean_dict( dict_fns.unflatten( logic.tuplize_dict( logic.parse_params(toolkit.request.POST, ignore_keys=CACHE_PARAMETERS)))) log.debug('EDCPackageController data from toolkit.request.POST %s' % data_dict) is_an_update = data_dict.get('pkg_name', False) if data and 'type' in data and data['type']: package_type = data['type'] else: package_type = self._guess_package_type(True) if save_action == 'finish' and not is_an_update and package_type == 'Geographic': return self._new_dataset_only(package_type, data_dict, errors, error_summary) elif save_action == 'add_data' and not is_an_update and package_type == 'Geographic': return self._new_dataset_only(package_type, data_dict, errors, error_summary, 'resources') else: return super(EDCPackageController, self).new(data, errors, error_summary)
def _add_or_reply(self, dataset_id): """ Allows the user to add a comment to an existing dataset """ context = {'model': model, 'user': c.user} # Auth check to make sure the user can see this package data_dict = {'id': dataset_id} check_access('package_show', context, data_dict) try: c.pkg_dict = get_action('package_show')(context, {'id': dataset_id}) c.pkg = context['package'] except: abort(403) if request.method == 'POST': data_dict = clean_dict(unflatten( tuplize_dict(parse_params(request.POST)))) data_dict['parent_id'] = c.parent.id if c.parent else None data_dict['url'] = '/dataset/%s' % c.pkg.name success = False try: res = get_action('comment_create')(context, data_dict) success = True except ValidationError, ve: log.debug(ve) except Exception, e: log.debug(e) abort(403)
def _save_edit(self, id, context): try: data_dict = clean_dict(unflatten( tuplize_dict(parse_params(request.POST)))) self._check_data_dict(data_dict) context['message'] = data_dict.get('log_message', '') if not context['moderated']: context['pending'] = False data_dict['id'] = id pkg = get_action('package_update')(context, data_dict) if request.params.get('save', '') == 'Approve': update.make_latest_pending_package_active(context, data_dict) c.pkg = context['package'] c.pkg_dict = pkg if context['preview']: c.is_preview = True PackageSaver().render_package(pkg, context) c.preview = render('package/read_core.html') return self.edit(id, data_dict) self._form_save_redirect(pkg['name'], 'edit') except NotAuthorized: abort(401, _('Unauthorized to read package %s') % id) except NotFound, e: abort(404, _('Package not found'))
def member_new(self, id): context = {'model': model, 'session': model.Session, 'user': c.user or c.author} #self._check_access('group_delete', context, {'id': id}) try: if request.method == 'POST': data_dict = clean_dict(unflatten( tuplize_dict(parse_params(request.params)))) data_dict['id'] = id c.group_dict = self._action('group_member_create')(context, data_dict) self._redirect_to(controller='group', action='members', id=id) else: user = request.params.get('user') if user: c.user_dict = get_action('user_show')(context, {'id': user}) c.user_role = ckan.new_authz.users_role_for_group_or_org(id, user) or 'member' else: c.user_role = 'member' c.group_dict = self._action('group_show')(context, {'id': id}) c.roles = self._action('member_roles_list')(context, {}) except NotAuthorized: abort(401, _('Unauthorized to add member to group %s') % '') except NotFound: abort(404, _('Group not found')) return self._render_template('group/member_new.html')
def new(self, data=None, errors=None, error_summary=None): package_type = self._guess_package_type(True) context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'extras_as_string': True, 'save': 'save' in request.params,} # Package needs to have a organization group in the call to check_access # and also to save it try: check_access('package_create',context) except NotAuthorized: abort(401, _('Unauthorized to create a package')) if context['save'] and not data: return self._save_new(context) data = data or clean_dict(unflatten(tuplize_dict(parse_params( request.params, ignore_keys=[CACHE_PARAMETER])))) c.resources_json = json.dumps(data.get('resources',[])) errors = errors or {} error_summary = error_summary or {} vars = {'data': data, 'errors': errors, 'error_summary': error_summary} c.errors_json = json.dumps(errors) self._setup_template_variables(context, {'id': id}) # TODO: This check is to maintain backwards compatibility with the old way of creating # custom forms. This behaviour is now deprecated. if hasattr(self, 'package_form'): c.form = render(self.package_form, extra_vars=vars) else: c.form = render(self._package_form(package_type=package_type), extra_vars=vars) return render( self._new_template(package_type))
def handle_submit(self, id): data = clean_dict(dict_fns.unflatten(tuplize_dict(parse_params( request.params)))) data['dataset_url'] = toolkit.url_for( controller='package', action='read', id=id, qualified=True ) package = get_action('package_show')(None, {'id': id}) self.fail_if_private(package, data['dataset_url']) # Comma separated config var to_addrs = config['ckanext.ands.support_emails'].split(',') subject = 'DataPortal Support: Request to publish dataset' body = base.render( 'package/doi_email.text', extra_vars=data) for email in to_addrs: mail_recipient('Dataportal support', email, subject, body) data['package_id'] = package['id'] data['user_id'] = c.userobj.id doi_request = DoiRequest(**data) Session.add(doi_request) Session.commit() h.flash_success("DOI Request sent") return toolkit.redirect_to(data['dataset_url'])
def form(self): context = {'model': model, 'user': c.user} if not ckan.new_authz.is_authorized('sysadmin', context, {})['success']: base.abort(401, _('Need to be system administrator')) # get one and only one entry from our extlink table entry = model.Session.query(extlinkmodel.ExtLink).first() if not entry: # create the empty entry for the first time entry = extlinkmodel.ExtLink() entry.save() if base.request.method == "POST": data = logic.clean_dict( df.unflatten( logic.tuplize_dict(logic.parse_params( base.request.params)))) entry.domains = data.get('white-list') entry.message = data.get('message') entry.save() h.flash_success(_('External link changes saved.')) h.redirect_to(controller=self.controller_path, action='form') c.extlinkdata = { 'white-list': entry.domains, 'message': entry.message, 'placeholder': msg_default, } return p.toolkit.render("form.html")
def form(self): context = {'model': model, 'user': c.user} if not ckan.new_authz.is_authorized('sysadmin', context, {})['success']: base.abort(401, _('Need to be system administrator')) # get one and only one entry from our extlink table entry = model.Session.query(extlinkmodel.ExtLink).first() if not entry: # create the empty entry for the first time entry = extlinkmodel.ExtLink() entry.save() if base.request.method == "POST": data = logic.clean_dict( df.unflatten( logic.tuplize_dict( logic.parse_params(base.request.params) ))) entry.domains = data.get('white-list') entry.message = data.get('message') entry.save() h.flash_success(_('External link changes saved.')) h.redirect_to(controller=self.controller_path, action='form') c.extlinkdata = { 'white-list': entry.domains, 'message': entry.message, 'placeholder': msg_default, } return p.toolkit.render("form.html")
def _add_users( self, group, parameters ): if not group: h.flash_error(_("There was a problem with your submission, " "please correct it and try again")) errors = {"reason": ["No reason was supplied"]} return self.apply(group.id, errors=errors, error_summary=action.error_summary(errors)) data_dict = logic.clean_dict(dict_func.unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) data_dict['id'] = group.id # Temporary fix for strange caching during dev l = data_dict['users'] for d in l: d['capacity'] = d.get('capacity','editor') context = { "group" : group, "schema": schema.default_group_schema(), "model": model, "session": model.Session } # Temporary cleanup of a capacity being sent without a name users = [d for d in data_dict['users'] if len(d) == 2] data_dict['users'] = users model.repo.new_revision() model_save.group_member_save(context, data_dict, 'users') model.Session.commit() h.redirect_to( controller='group', action='edit', id=group.name)
def post(self, name=None): context = self._prepare(name) sub_theme = context['sub_theme'] try: data_dict = logic.clean_dict( dictization_functions.unflatten( logic.tuplize_dict(logic.parse_params(request.form)))) data_dict.pop('save', '') except dictization_functions.DataError: base.abort(400, _(u'Integrity Error')) data_dict['id'] = sub_theme.get('id') try: st = logic.get_action(u'sub_theme_update')(context, data_dict) h.flash_notice(_(u'Sub-Theme has been updated.')) except logic.NotAuthorized: base.abort(403, _(u'Unauthorized to update the sub-theme')) except logic.ValidationError as e: errors = e.error_dict error_summary = e.error_summary return self.get(name, data_dict, errors, error_summary) try: kwh_data = { 'type': 'sub-theme', 'old_content': sub_theme.get('title'), 'new_content': st.get('title') } logic.get_action(u'kwh_data_update')(context, kwh_data) except Exception as e: log.debug('Error while storing KWH data: %s' % str(e)) return h.redirect_to(u'sub_theme.read', name=sub_theme.get(u'name'))
def post(self): try: req = request.form.copy() req.update(request.files.to_dict()) data_dict = logic.clean_dict( dict_fns.unflatten( logic.tuplize_dict( logic.parse_params( req, ignore_keys=CACHE_PARAMETERS)))) del data_dict['save'] data = logic.get_action(u'config_option_update')({ u'user': g.user }, data_dict) except logic.ValidationError as e: items = _get_config_options() data = request.form errors = e.error_dict error_summary = e.error_summary vars = dict( data=data, errors=errors, error_summary=error_summary, form_items=items, **items) return base.render(u'admin/config.html', extra_vars=vars) return h.redirect_to(u'admin.config')
def dataportalAdmin(self): # items = self._get_config_form_items() data = request.POST if 'save' in data: try: # really? data_dict = logic.clean_dict( dict_fns.unflatten( logic.tuplize_dict( logic.parse_params( request.POST, ignore_keys=CACHE_PARAMETERS)))) del data_dict['save'] data = logic.get_action('config_option_update')( {'user': c.user}, data_dict) except logic.ValidationError as e: errors = e.error_dict error_summary = e.error_summary vars = {'data': data, 'errors': errors, 'error_summary': error_summary} return base.render('admin/dataportal.html', extra_vars=vars) h.redirect_to(controller='ckanext.dataportaltheme.plugin:PortalController', action='dataportalAdmin') schema = logic.schema.update_configuration_schema() data = {} for key in schema: data[key] = config.get(key) vars = {'data': data, 'errors': {}} return base.render('admin/dataportal.html', extra_vars=vars)
def importpackagedata(self,bulk_upload_id,file_path=None,resource_dir=None,ckanclient=None): """ This is an entry point for bulk upload of one record(bulk uploaded template). Loads the package details as dict from xls file and loads them into CKAN. Each successfully loaded pacakges are referenced against bulk upload record for tracking. """ from ckan.lib.navl.dictization_functions import unflatten from ckan.logic import (tuplize_dict,clean_dict ) from ckanext.ngds.importer.loader import ResourceLoader if ckanclient is None: ckanclient = self._get_ckanclient() loader = ResourceLoader(ckanclient,field_keys_to_find_pkg_by=['name'],resource_dir=resource_dir) package_import = NGDSPackageImporter(filepath=file_path) pkg_dicts = [pkg_dict for pkg_dict in package_import.pkg_dict()] for pkg_dict in pkg_dicts: try: returned_package = loader.load_package(clean_dict(unflatten(tuplize_dict(pkg_dict)))) # Upload bulk upload to package relationship. self._create_bulk_upload_package(bulk_upload_id,returned_package['name'],returned_package['title']) except Exception , e: log.info(e) log.info("Skipping this record and proceeding with next one....") raise
def _save_new(self, context): model = context['model'] context['ignore_auth'] = True try: data_dict = logic.clean_dict(unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') captcha.check_recaptcha(request) organization = get_action('inventory_organization_by_inventory_id')( context, {'id': data_dict['inventory_organization_id']}) password = str(random.SystemRandom().random()) data_dict['password1'] = password data_dict['password2'] = password data_dict['state'] = model.State.PENDING user = get_action('user_create')(context, data_dict) data_dict = { 'id': organization['id'], 'role': 'editor', 'username': user['name'] } logic.get_action('organization_member_create')(context, data_dict) except NotAuthorized: abort(401, _('Unauthorized to create user %s') % '') except NotFound, e: abort(404, _('User or organization not found'))
def post(self): context = self._prepare() # a.s. data = request.form if 'save' in data: try: data_dict = logic.clean_dict( dictization_functions.unflatten( logic.tuplize_dict(logic.parse_params(request.form)))) except dictization_functions.DataError: base.abort(400, toolkit._(u'Integrity Error')) context[u'message'] = data_dict.get(u'log_message', u'') try: logic.get_action(u'reqaccess_create')(context, data_dict) except logic.ValidationError as e: errors = e.error_dict error_summary = e.error_summary return self.get(data_dict, errors, error_summary) toolkit.h.flash_success( toolkit._(u'Request for dataset access has been sent. Data ' u'maintainer will respond to the following ' u'email: "%s" ') % (data_dict[u'user_email'])) return base.render(u'home/index.html')
def edit(self, dataset_id, comment_id): context = {'model': model, 'user': c.user} # Auth check to make sure the user can see this package data_dict = {'id': dataset_id} check_access('package_show', context, data_dict) try: c.pkg_dict = get_action('package_show')(context, {'id': dataset_id}) c.pkg = context['package'] except: abort(403) if request.method == 'POST': data_dict = clean_dict(unflatten( tuplize_dict(parse_params(request.POST)))) data_dict['id'] = comment_id success = False try: res = get_action('comment_update')(context, data_dict) success = True except ValidationError, ve: log.debug(ve) except Exception, e: log.debug(e) abort(403)
def post(self, package_type, id): context = {u'model': model, u'user': g.user} try: form_dict = logic.clean_dict( dict_fns.unflatten( logic.tuplize_dict(logic.parse_params(request.form)))) user = get_action(u'user_show')(context, { u'id': form_dict[u'username'] }) data_dict = { u'id': id, u'user_id': user[u'id'], u'capacity': form_dict[u'capacity'] } get_action(u'package_collaborator_create')(context, data_dict) except dict_fns.DataError: return base.abort(400, _(u'Integrity Error')) except NotAuthorized: message = _(u'Unauthorized to edit collaborators {}').format(id) return base.abort(401, _(message)) except NotFound: return base.abort(404, _(u'Resource not found')) except ValidationError as e: h.flash_error(e.error_summary) else: h.flash_success(_(u'User added to collaborators')) return h.redirect_to(u'dataset.collaborators_read', id=id)
def resource_edit(self, id, resource_id, data=None, errors=None, error_summary=None): if request.method == 'POST' and not data: data = data or clean_dict(dict_fns.unflatten(tuplize_dict(parse_params( request.POST)))) # we don't want to include save as it is part of the form del data['save'] context = {'model': model, 'session': model.Session, 'api_version': 3, 'for_edit': True, 'user': c.user or c.author, 'auth_user_obj': c.userobj} data['package_id'] = id try: if resource_id: data['id'] = resource_id get_action('resource_update')(context, data) else: get_action('resource_create')(context, data) except ValidationError, e: errors = e.error_dict error_summary = e.error_summary return self.resource_edit(id, resource_id, data, errors, error_summary) except NotAuthorized: abort(401, _('Unauthorized to edit this resource'))
def publish(self, dataset_id, comment_id): context = {'model': model, 'user': c.user} # Verifica que el usuario autenticado pueda ver el paquete # Se comenta para evitar que solo usuarios conectados puedan realizar comentarios data_dict = {'id': dataset_id} #check_access('package_show', context, data_dict) try: c.pkg_dict = get_action('package_show')(context, { 'id': dataset_id }) c.pkg = context['package'] except: abort(403) if request.method == 'POST': data_dict = clean_dict( unflatten(tuplize_dict(parse_params(request.POST)))) data_dict['id'] = comment_id try: get_action('comment_publish')(context, data_dict) except ValidationError, ve: log.debug(ve) except Exception, e: log.debug(e) abort(403)
def _save_permissions(self, id, context): try: data_dict = clean_dict( dict_fns.unflatten( tuplize_dict(parse_params(tk.request.params)))) data_dict['role_id'] = id context['message'] = data_dict.get('log_message', '') context['defer_commit'] = True selected_permission_ids = [ permission_id[11:] for permission_id in data_dict.iterkeys() if permission_id.startswith('permission:') ] current_permissions = tk.c.permissions for permission in current_permissions: data_dict['content_type'] = permission['content_type'] data_dict['operation'] = permission['operation'] if permission[ 'id'] in selected_permission_ids and not permission[ 'granted']: tk.get_action('role_permission_grant')(context, data_dict) elif permission['granted'] and permission[ 'id'] not in selected_permission_ids: tk.get_action('role_permission_revoke')(context, data_dict) model.repo.commit() tk.h.redirect_to('role_read', id=id) except tk.ObjectNotFound: tk.abort(404, tk._('Role not found')) except tk.NotAuthorized, e: tk.abort(403, e.message)
def post(self, id, resource_id): u'''Data dictionary view: edit field labels and descriptions''' data_dict = self._prepare(id, resource_id) fields = data_dict[u'fields'] data = dict_fns.unflatten(tuplize_dict(parse_params(request.form))) info = data.get(u'info') if not isinstance(info, list): info = [] info = info[:len(fields)] get_action(u'datastore_create')( None, { u'resource_id': resource_id, u'force': True, u'fields': [{ u'id': f[u'id'], u'type': f[u'type'], u'info': fi if isinstance(fi, dict) else {} } for f, fi in zip_longest(fields, info)] } ) h.flash_success( _( u'Data Dictionary saved. Any type overrides will ' u'take effect when the resource is next uploaded ' u'to DataStore' ) ) return h.redirect_to( u'datastore.dictionary', id=id, resource_id=resource_id )
def _save_edit(self, id, context): try: data_dict = logic.clean_dict(unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') data_dict['id'] = id if data_dict['password1'] and data_dict['password2']: identity = {'login': c.user, 'password': data_dict['old_password']} auth = authenticator.UsernamePasswordAuthenticator() if auth.authenticate(request.environ, identity) != c.user: raise UsernamePasswordError # MOAN: Do I really have to do this here? if 'activity_streams_email_notifications' not in data_dict: data_dict['activity_streams_email_notifications'] = False user = get_action('user_update')(context, data_dict) h.flash_success(_('Profile updated')) h.redirect_to(controller='user', action='read', id=user['name']) except NotAuthorized: abort(401, _('Unauthorized to edit user %s') % id) except NotFound, e: abort(404, _('User not found'))
def config(self): items = self._get_config_form_items() data = request.POST if 'save' in data: try: # really? data_dict = logic.clean_dict( dict_fns.unflatten( logic.tuplize_dict( logic.parse_params(request.POST, ignore_keys=CACHE_PARAMETERS)))) del data_dict['save'] data = logic.get_action('config_option_update')({ 'user': c.user }, data_dict) except logic.ValidationError, e: errors = e.error_dict error_summary = e.error_summary vars = { 'data': data, 'errors': errors, 'error_summary': error_summary, 'form_items': items } return base.render('admin/config.html', extra_vars=vars) h.redirect_to(controller='admin', action='config')
def _edit_or_new(self, id, related_id, is_edit): """ Edit and New were too similar and so I've put the code together and try and do as much up front as possible. """ context = {"model": model, "session": model.Session, "user": c.user or c.author, "for_view": True} data_dict = {} if is_edit: tpl = "related/edit.html" auth_name = "related_update" auth_dict = {"id": related_id} action_name = "related_update" try: related = logic.get_action("related_show")(context, {"id": related_id}) except logic.NotFound: base.abort(404, _("Related item not found")) else: tpl = "related/new.html" auth_name = "related_create" auth_dict = {} action_name = "related_create" try: logic.check_access(auth_name, context, auth_dict) except logic.NotAuthorized: base.abort(401, base._("Not authorized")) try: c.pkg_dict = logic.get_action("package_show")(context, {"id": id}) except logic.NotFound: base.abort(404, _("Package not found")) data, errors, error_summary = {}, {}, {} if base.request.method == "POST": try: data = logic.clean_dict(df.unflatten(logic.tuplize_dict(logic.parse_params(base.request.params)))) if is_edit: data["id"] = related_id else: data["dataset_id"] = id data["owner_id"] = c.userobj.id related = logic.get_action(action_name)(context, data) if not is_edit: h.flash_success(_("Related item was successfully created")) else: h.flash_success(_("Related item was successfully updated")) h.redirect_to(controller="related", action="list", id=c.pkg_dict["name"]) except df.DataError: base.abort(400, _(u"Integrity Error")) except logic.ValidationError, e: errors = e.error_dict error_summary = e.error_summary
def _send_request(self, context): try: data_dict = logic.clean_dict( unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) captcha.check_recaptcha(request) except logic.NotAuthorized: toolkit.abort(401, _('Not authorized to see this page')) except captcha.CaptchaError: error_msg = _('Bad Captcha. Please try again.') h.flash_error(error_msg) return self.restricted_request_access_form( package_id=data_dict.get('package_name'), resource_id=data_dict.get('resource'), data=data_dict) try: pkg = toolkit.get_action('package_show')( context, { 'id': data_dict.get('package_name') }) data_dict['pkg_dict'] = pkg # log.info('data_dict: ') # log.info(data_dict) # log.info('package: ') # log.info(pkg) except toolkit.ObjectNotFound: toolkit.abort(404, _('Dataset not found')) except Exception: toolkit.abort(404, _('Exception retrieving dataset to send mail')) # Validation errors = {} error_summary = {} if (data_dict['message'] == ''): msg = _('Missing Value') errors['message'] = [msg] error_summary['message'] = msg if len(errors) > 0: return self.restricted_request_access_form( data=data_dict, errors=errors, error_summary=error_summary, package_id=data_dict.get('package-name'), resource_id=data_dict.get('resource')) success = self._send_request_mail(data_dict) return render('restricted/restricted_request_access_result.html', extra_vars={ 'data': data_dict, 'pkg_dict': pkg, 'success': success })
def getOGCServices(self): data = clean_dict(unflatten(tuplize_dict(parse_params(request.params)))) url = data.get('url', None) workspace = data.get('workspace', None) #USGIN MODEL WFS Validator add ? if workspace: workspace = workspace.replace('?', '') request_ogc = data.get('request', None) obj = None try: if not request_ogc or (request_ogc and request_ogc == "GetCapabilities"): if url and workspace: oResponse = requests.get(urllib.unquote_plus(url)) obj = oResponse.text #Replace the (#name_workspace) from NamespaceURI #obj = oResponse.text.replace('#'+workspace, '') #Add API URL in all links in order to make system go through it instead of hitting geoserver direclty to remove (#name_workspace) from all ogc services XML #siteUrl = config.get('ckan.site_url', None) #if siteUrl: # newServiceUrl = siteUrl+"/geoserver/get-ogc-services?url=" # match = re.compile('xlink:href=[\'|"](.*?)[\'"]') # matches = match.findall(obj) #loop through all occurrences and replace one by one to add the link API Ckan-Geoserver # for item in matches: # obj = obj.replace(item, newServiceUrl+urllib.quote_plus(item)+"&workspace="+workspace, 1) else: msg = 'An error ocurred: [Bad Request - Missing parameters]' abort(400, msg) elif request_ogc and request_ogc == "GetFeature": service = data.get('service', None) typename = data.get('typename', None) version = data.get('version', None) maxfeatures = data.get('maxfeatures', None) getFeatureURL = urllib.unquote_plus(url)+"?service=%s&request=%s&typename=%s&version=%s" % (service, request_ogc, typename, version) if maxfeatures: getFeatureURL = getFeatureURL+"&maxfeatures=%s" % maxfeatures oResponse = requests.get(getFeatureURL) onj = oResponse.text #Replace the (#name_workspace) from NamespaceURI #obj = oResponse.text.replace('#'+workspace, '') response.content_type = 'application/xml; charset=utf-8' response.headers['Content-Length'] = len(obj) return obj.encode('utf-8') except Exception, e: msg = 'An error ocurred: [%s]' % str(e) abort(500, msg)
def validate_resource(self): """ Validate a resource to ensure that it conforms to NGDS standards. For ex: if a resource specifies that it conforms to a content model, that validation occurs here. """ data = clean_dict(unflatten(tuplize_dict(parse_params( request.params)))) return toolkit.get_action("validate_resource")(None, data)
def _hdx_edit(self, id, related_id, is_edit): #Taken from ckan/controller/related.py, paired down to just edits """ Edit and New were too similar and so I've put the code together and try and do as much up front as possible. """ context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj, 'for_view': True} data_dict = {} tpl = 'related/edit.html' auth_name = 'related_update' auth_dict = {'id': related_id} action_name = 'related_update' try: related = logic.get_action('related_show')( context, {'id': related_id}) except logic.NotFound: base.abort(404, _('Related item not found')) try: logic.check_access(auth_name, context, auth_dict) except logic.NotAuthorized: #If user can edit package, user can edit related item try: logic.check_access('package_update', {'model': model, 'session': model.Session, 'user': c.user or c.author, 'for_view': True, 'auth_user_obj': c.userobj}, {'id': id}) except logic.NotAuthorized: base.abort(401, base._('Not authorized')) try: c.pkg_dict = logic.get_action('package_show')(context, {'id': id}) except logic.NotFound: base.abort(404, _('Package not found')) data, errors, error_summary = {}, {}, {} if base.request.method == "POST": try: data = logic.clean_dict( df.unflatten( logic.tuplize_dict( logic.parse_params(base.request.params)))) data['id'] = related_id related = self.related_update(context, data) h.flash_success(_("Related item was successfully updated")) h.redirect_to( controller='ckanext.hdx_package.controllers.dataset_controller:DatasetController', action='read', id=c.pkg_dict['name']) except df.DataError: base.abort(400, _(u'Integrity Error')) except logic.ValidationError, e: errors = e.error_dict error_summary = e.error_summary
def post(self, id=None): context, id = self._prepare(id) if not context[u'save']: return self.get(id) if id in (g.userobj.id, g.userobj.name): current_user = True else: current_user = False old_username = g.userobj.name try: data_dict = logic.clean_dict( dictization_functions.unflatten( logic.tuplize_dict(logic.parse_params(request.form)))) except dictization_functions.DataError: base.abort(400, _(u'Integrity Error')) data_dict.setdefault(u'activity_streams_email_notifications', False) context[u'message'] = data_dict.get(u'log_message', u'') data_dict[u'id'] = id email_changed = data_dict[u'email'] != g.userobj.email if (data_dict[u'password1'] and data_dict[u'password2']) or email_changed: identity = { u'login': g.user, u'password': data_dict[u'old_password'] } auth = authenticator.UsernamePasswordAuthenticator() if auth.authenticate(request.environ, identity) != g.user: errors = { u'oldpassword': [_(u'Password entered was incorrect')] } error_summary = {_(u'Old Password'): _(u'incorrect password')} return self.get(id, data_dict, errors, error_summary) try: user = logic.get_action(u'user_update')(context, data_dict) except logic.NotAuthorized: base.abort(403, _(u'Unauthorized to edit user %s') % id) except logic.NotFound: base.abort(404, _(u'User not found')) except logic.ValidationError as e: errors = e.error_dict error_summary = e.error_summary return self.get(id, data_dict, errors, error_summary) h.flash_success(_(u'Profile updated')) resp = h.redirect_to(u'user.read', id=user[u'name']) if current_user and data_dict[u'name'] != old_username: # Changing currently logged in user's name. # Update repoze.who cookie to match set_repoze_user(data_dict[u'name'], resp) return resp
def _send_suggestion(self, context): try: data_dict = logic.clean_dict(unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') c.form = data_dict['name'] captcha.check_recaptcha(request) # return base.render('suggest/form.html') except logic.NotAuthorized: base.abort(401, _('Not authorized to see this page')) except captcha.CaptchaError: error_msg = _(u'Bad Captcha. Please try again.') h.flash_error(error_msg) return self.suggest_form(data_dict) errors = {} error_summary = {} if (data_dict["email"] == ''): errors['email'] = [u'Missing Value'] error_summary['email'] = u'Missing value' if (data_dict["name"] == ''): errors['name'] = [u'Missing Value'] error_summary['name'] = u'Missing value' if (data_dict["suggestion"] == ''): errors['suggestion'] = [u'Missing Value'] error_summary['suggestion'] = u'Missing value' if len(errors) > 0: return self.suggest_form(data_dict, errors, error_summary) else: # #1799 User has managed to register whilst logged in - warn user # they are not re-logged in as new user. mail_to = config.get('email_to') recipient_name = 'CKAN Surrey' subject = 'CKAN - Dataset suggestion' body = 'Submitted by %s (%s)\n' % (data_dict["name"], data_dict["email"]) if (data_dict["category"] != ''): body += 'Category: %s' % data_dict["category"] body += 'Request: %s' % data_dict["suggestion"] try: mailer.mail_recipient(recipient_name, mail_to, subject, body) except mailer.MailerException: raise return base.render('suggest/suggest_success.html')
def render_map(self): """ This function is responsible for rendering the Map Search page. """ data = clean_dict(unflatten(tuplize_dict(parse_params(request.params)))) if data.get('query'): c.query = data['query'] return render('map/map.html')
def _save_new(self, context): try: data_dict = clean_dict(unflatten(tuplize_dict(parse_params(request.params)))) context["message"] = data_dict.get("log_message", "") group = get_action("group_create")(context, data_dict) h.redirect_to(controller="group", action="read", id=group["name"]) except NotAuthorized: abort(401, _("Unauthorized to read group %s") % "") except NotFound, e: abort(404, _("Package not found"))
def _save_new(self, context): try: data_dict = logic.clean_dict(unflatten(logic.tuplize_dict(logic.parse_params(request.params)))) context["message"] = data_dict.get("log_message", "") captcha.check_recaptcha(request) user = get_action("user_create")(context, data_dict) except NotAuthorized: abort(401, _("Unauthorized to create user %s") % "") except NotFound, e: abort(404, _("User not found"))
def _send_contact(self, context): try: data_dict = logic.clean_dict(unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') c.form = data_dict['name'] captcha.check_recaptcha(request) #return base.render('suggest/form.html') except logic.NotAuthorized: base.abort(401, _('Not authorized to see this page')) except captcha.CaptchaError: error_msg = _(u'Bad Captcha. Please try again.') h.flash_error(error_msg) return self.contact_form(data_dict) errors = {} error_summary = {} if (data_dict["email"] == ''): errors['email'] = [u'Missing Value'] error_summary['email'] = u'Missing value' if (data_dict["name"] == ''): errors['name'] = [u'Missing Value'] error_summary['name'] = u'Missing value' if (data_dict["content"] == ''): errors['content'] = [u'Missing Value'] error_summary['content'] = u'Missing value' if len(errors) > 0: return self.suggest_form(data_dict, errors, error_summary) else: mail_to = config.get('email_to') recipient_name = 'CKAN' subject = 'CKAN - Contact/Question from visitor' body = 'Submitted by %s (%s)\n' % (data_dict["name"], data_dict["email"]) body += 'Request: %s' % data_dict["content"] try: mailer.mail_recipient(recipient_name, mail_to, subject, body) except mailer.MailerException: raise return base.render('contact/success.html')