def formList(request, username): """ This is where ODK Collect gets its download list. """ formlist_user = get_object_or_404(User, username__iexact=username) profile, created = UserProfile.objects.get_or_create(user=formlist_user) if profile.require_auth: authenticator = HttpDigestAuthenticator() if not authenticator.authenticate(request): return authenticator.build_challenge_response() # unauthorized if user in auth request does not match user in path # unauthorized if user not active if not request.user.is_active: return HttpResponseNotAuthorized() # filter private forms (where require_auth=False) # for users who are non-owner if request.user.username == profile.user.username: xforms = XForm.objects.filter(downloadable=True, user__username__iexact=username) else: xforms = XForm.objects.filter(downloadable=True, user__username__iexact=username, require_auth=False) audit = {} audit_log(Actions.USER_FORMLIST_REQUESTED, request.user, formlist_user, _("Requested forms list."), audit, request) data = {"host": request.build_absolute_uri().replace(request.get_full_path(), ""), "xforms": xforms} response = render(request, "xformsList.xml", data, content_type="text/xml; charset=utf-8") response["X-OpenRosa-Version"] = "1.0" tz = pytz.timezone(settings.TIME_ZONE) dt = datetime.now(tz).strftime("%a, %d %b %Y %H:%M:%S %Z") response["Date"] = dt return response
def set_form(): form = QuickConverter(request.POST, request.FILES) survey = form.publish(request.user).survey audit = {} audit_log( Actions.FORM_PUBLISHED, request.user, content_user, _("Published form '%(id_string)s'.") % { 'id_string': survey.id_string, }, audit, request) enketo_webform_url = reverse( enter_data, kwargs={'username': username, 'id_string': survey.id_string} ) return { 'type': 'alert-success', 'preview_url': reverse(enketo_preview, kwargs={ 'username': username, 'id_string': survey.id_string }), 'text': _(u'Successfully published %(form_id)s.' u' <a href="%(form_url)s">Enter Web Form</a>' u' or <a href="#preview-modal" data-toggle="modal">' u'Preview Web Form</a>') % {'form_id': survey.id_string, 'form_url': enketo_webform_url}, 'form_o': survey }
def profile_settings(request, username): context = RequestContext(request) content_user = check_and_set_user(request, username) context.content_user = content_user profile, created = UserProfile.objects.get_or_create(user=content_user) if request.method == 'POST': form = UserProfileForm(request.POST, instance=profile) if form.is_valid(): # get user # user.email = cleaned_email form.instance.user.email = form.cleaned_data['email'] form.instance.user.save() form.save() # todo: add string rep. of settings to see what changed audit = {} audit_log( Actions.PROFILE_SETTINGS_UPDATED, request.user, content_user, _("Profile settings updated."), audit, request) return HttpResponseRedirect(reverse( public_profile, kwargs={'username': request.user.username} )) else: form = UserProfileForm( instance=profile, initial={"email": content_user.email}) return render_to_response("settings.html", {'form': form}, context_instance=context)
def formList(request, username): """ This is where ODK Collect gets its download list. """ formlist_user = get_object_or_404(User, username=username) profile, created = UserProfile.objects.get_or_create(user=formlist_user) if profile.require_auth: authenticator = HttpDigestAuthenticator() if not authenticator.authenticate(request): return authenticator.build_challenge_response() # unauthorized if user in auth request does not match user in path # unauthorized if user not active if not request.user.is_active: return HttpResponseNotAuthorized() xforms = XForm.objects.filter(downloadable=True, user__username=username) audit = {} audit_log(Actions.USER_FORMLIST_REQUESTED, request.user, formlist_user, _("Requested forms list."), audit, request) response = render_to_response("xformsList.xml", { 'host': request.build_absolute_uri().replace( request.get_full_path(), ''), 'xforms': xforms }, mimetype="text/xml; charset=utf-8") response['X-OpenRosa-Version'] = '1.0' tz = pytz.timezone(settings.TIME_ZONE) dt = datetime.now(tz).strftime('%a, %d %b %Y %H:%M:%S %Z') response['Date'] = dt return response
def delete_data(request, username=None, id_string=None): xform, owner = check_and_set_user_and_form(username, id_string, request) response_text = u"" if not xform: return HttpResponseForbidden(_(u"Not shared.")) data_id = request.POST.get("id") if not data_id: return HttpResponseBadRequest(_(u"id must be specified")) Instance.set_deleted_at(data_id) audit = {"xform": xform.id_string} audit_log( Actions.SUBMISSION_DELETED, request.user, owner, _("Deleted submission with id '%(record_id)s' " "on '%(id_string)s'.") % {"id_string": xform.id_string, "record_id": data_id}, audit, request, ) response_text = json.dumps({"success": "Deleted data %s" % data_id}) if "callback" in request.GET and request.GET.get("callback") != "": callback = request.GET.get("callback") response_text = "%s(%s)" % (callback, response_text) return HttpResponse(response_text, mimetype="application/json")
def download_xlsform(request, username, id_string): xform = get_object_or_404(XForm, user__username=username, id_string=id_string) owner = User.objects.get(username=username) helper_auth_helper(request) if not has_permission(xform, owner, request, xform.shared): return HttpResponseForbidden('Not shared.') file_path = xform.xls.name default_storage = get_storage_class()() if default_storage.exists(file_path): audit = { "xform": xform.id_string } audit_log( Actions.FORM_XLS_DOWNLOADED, request.user, xform.user, _("Downloaded XLS file for form '%(id_string)s'.") % { "id_string": xform.id_string }, audit, request) split_path = file_path.split(os.extsep) extension = 'xls' if len(split_path) > 1: extension = split_path[len(split_path) - 1] response = response_with_mimetype_and_name( 'vnd.ms-excel', id_string, show_date=False, extension=extension, file_path=file_path) return response else: messages.add_message(request, messages.WARNING, _(u'No XLS file for your form ' u'<strong>%(id)s</strong>') % {'id': id_string}) return HttpResponseRedirect("/%s" % username)
def zip_export(request, username, id_string): owner = get_object_or_404(User, username=username) xform = get_object_or_404(XForm, id_string=id_string, user=owner) helper_auth_helper(request) if not has_permission(xform, owner, request): return HttpResponseForbidden(_(u'Not shared.')) if request.GET.get('raw'): id_string = None attachments = Attachment.objects.filter(instance__xform=xform) zip_file = create_attachments_zipfile(attachments) audit = { "xform": xform.id_string, "export_type": Export.ZIP_EXPORT } audit_log( Actions.EXPORT_CREATED, request.user, owner, _("Created ZIP export on '%(id_string)s'.") % { 'id_string': xform.id_string, }, audit, request) # log download as well audit_log( Actions.EXPORT_DOWNLOADED, request.user, owner, _("Downloaded ZIP export on '%(id_string)s'.") % { 'id_string': xform.id_string, }, audit, request) if request.GET.get('raw'): id_string = None response = response_with_mimetype_and_name('zip', id_string, file_path=zip_file, use_local_filesystem=True) return response
def instance(request, username, id_string): """ Data view for browsing submissions one at a time. """ # pylint: disable=W0612 xform, is_owner, can_edit, can_view = get_xform_and_perms( username, id_string, request) # no access if not (xform.shared_data or can_view or request.session.get('public_link') == xform.uuid): return HttpResponseForbidden(_(u'Not shared.')) audit = { "xform": xform.id_string, } audit_log(Actions.FORM_DATA_VIEWED, request.user, xform.user, _("Requested instance view for '%(id_string)s'.") % { 'id_string': xform.id_string, }, audit, request) return render(request, 'instance.html', { 'username': username, 'id_string': id_string, 'xform': xform, 'can_edit': can_edit })
def set_form(): form = QuickConverter(request.POST, request.FILES) survey = form.publish(request.user).survey audit = {} audit_log( Actions.FORM_PUBLISHED, request.user, content_user, _("Published form '%(id_string)s'.") % {"id_string": survey.id_string}, audit, request, ) enketo_webform_url = reverse(enter_data, kwargs={"username": username, "id_string": survey.id_string}) return { "type": "alert-success", "preview_url": reverse(enketo_preview, kwargs={"username": username, "id_string": survey.id_string}), "text": _( u"Successfully published %(form_id)s." u' <a href="%(form_url)s">Enter Web Form</a>' u' or <a href="#preview-modal" data-toggle="modal">' u"Preview Web Form</a>" ) % {"form_id": survey.id_string, "form_url": enketo_webform_url}, "form_o": survey, }
def download_metadata(request, username, id_string, data_id): xform = get_object_or_404(XForm, user__username=username, id_string=id_string) owner = xform.user if username == request.user.username or xform.shared: data = get_object_or_404(MetaData, pk=data_id) file_path = data.data_file.name filename, extension = os.path.splitext(file_path.split('/')[-1]) extension = extension.strip('.') dfs = get_storage_class()() if dfs.exists(file_path): audit = { 'xform': xform.id_string } audit_log( Actions.FORM_UPDATED, request.user, owner, _("Document '%(filename)s' for '%(id_string)s' downloaded.") % { 'id_string': xform.id_string, 'filename': "%s.%s" % (filename, extension) }, audit, request) response = response_with_mimetype_and_name( data.data_file_type, filename, extension=extension, show_date=False, file_path=file_path) return response else: return HttpResponseNotFound() return HttpResponseForbidden(_(u'Permission denied.'))
def set_form(): form_owner = request.POST.get("username") id_string = request.POST.get("id_string") xform = XForm.objects.get(user__username=form_owner, id_string=id_string) if len(id_string) > 0 and id_string[0].isdigit(): id_string = "_" + id_string path = xform.xls.name if default_storage.exists(path): xls_file = upload_to(None, "%s%s.xls" % (id_string, XForm.CLONED_SUFFIX), to_username) xls_data = default_storage.open(path) xls_file = default_storage.save(xls_file, xls_data) context.message = u"%s-%s" % (form_owner, xls_file) survey = DataDictionary.objects.create(user=request.user, xls=xls_file).survey # log to cloner's account audit = {} audit_log( Actions.FORM_CLONED, request.user, request.user, _("Cloned form '%(id_string)s'.") % {"id_string": survey.id_string}, audit, request, ) clone_form_url = reverse( show, kwargs={"username": to_username, "id_string": xform.id_string + XForm.CLONED_SUFFIX} ) return { "type": "alert-success", "text": _(u"Successfully cloned to %(form_url)s into your " u"%(profile_url)s") % { "form_url": u'<a href="%(url)s">%(id_string)s</a> ' % {"id_string": survey.id_string, "url": clone_form_url}, "profile_url": u'<a href="%s">profile</a>.' % reverse(profile, kwargs={"username": to_username}), }, }
def delete_export(request, username, id_string, export_type): owner = get_object_or_404(User, username__iexact=username) xform = get_object_or_404(XForm, id_string__exact=id_string, user=owner) if not has_permission(xform, owner, request): return HttpResponseForbidden(_(u'Not shared.')) export_id = request.POST.get('export_id') # find the export entry in the db export = get_object_or_404(Export, id=export_id) export.delete() audit = { "xform": xform.id_string, "export_type": export.export_type } audit_log( Actions.EXPORT_DOWNLOADED, request.user, owner, _("Deleted %(export_type)s export '%(filename)s'" " on '%(id_string)s'.") % { 'export_type': export.export_type.upper(), 'filename': export.filename, 'id_string': xform.id_string, }, audit, request) return HttpResponseRedirect(reverse( export_list, kwargs={ "username": username, "id_string": id_string, "export_type": export_type }))
def kml_export(request, username, id_string): # read the locations from the database owner = get_object_or_404(User, username__iexact=username) xform = get_object_or_404(XForm, id_string__exact=id_string, user=owner) helper_auth_helper(request) if not has_permission(xform, owner, request): return HttpResponseForbidden(_(u'Not shared.')) data = {'data': kml_export_data(id_string, user=owner)} response = \ render(request, "survey.kml", data, content_type="application/vnd.google-earth.kml+xml") response['Content-Disposition'] = \ disposition_ext_and_date(id_string, 'kml') audit = { "xform": xform.id_string, "export_type": Export.KML_EXPORT } audit_log( Actions.EXPORT_CREATED, request.user, owner, _("Created KML export on '%(id_string)s'.") % { 'id_string': xform.id_string, }, audit, request) # log download as well audit_log( Actions.EXPORT_DOWNLOADED, request.user, owner, _("Downloaded KML export on '%(id_string)s'.") % { 'id_string': xform.id_string, }, audit, request) return response
def delete_data(request, username=None, id_string=None): xform, owner = check_and_set_user_and_form(username, id_string, request) response_text = u'' if not xform: return HttpResponseForbidden(_(u'Not shared.')) data_id = request.POST.get('id') if not data_id: return HttpResponseBadRequest(_(u"id must be specified")) Instance.set_deleted_at(data_id) audit = { 'xform': xform.id_string } audit_log( Actions.SUBMISSION_DELETED, request.user, owner, _("Deleted submission with id '%(record_id)s' " "on '%(id_string)s'.") % { 'id_string': xform.id_string, 'record_id': data_id }, audit, request) response_text = json.dumps({"success": "Deleted data %s" % data_id}) if 'callback' in request.GET and request.GET.get('callback') != '': callback = request.GET.get('callback') response_text = ("%s(%s)" % (callback, response_text)) return HttpResponse(response_text, mimetype='application/json')
def _generate_new_export(request, xform, query, export_type): query = _set_start_end_params(request, query) extension = _get_extension_from_export_type(export_type) try: if export_type == Export.EXTERNAL_EXPORT: export = generate_external_export( export_type, xform.user.username, xform.id_string, None, request.GET.get('token'), query, request.GET.get('meta') ) else: export = generate_export( export_type, extension, xform.user.username, xform.id_string, None, query ) audit = { "xform": xform.id_string, "export_type": export_type } log.audit_log( log.Actions.EXPORT_CREATED, request.user, xform.user, _("Created %(export_type)s export on '%(id_string)s'.") % { 'id_string': xform.id_string, 'export_type': export_type.upper() }, audit, request) except NoRecordsFoundError: raise Http404(_("No records found to export")) except J2XException as e: # j2x exception return {'error': str(e)} else: return export
def set_form(): form = QuickConverter(request.POST, request.FILES) survey = form.publish(request.user, id_string).survey enketo_webform_url = reverse( enter_data, kwargs={'username': username, 'id_string': survey.id_string} ) audit = { 'xform': xform.id_string } audit_log( Actions.FORM_XLS_UPDATED, request.user, owner, _("XLS for '%(id_string)s' updated.") % { 'id_string': xform.id_string, }, audit, request) return { 'type': 'alert-success', 'text': _(u'Successfully published %(form_id)s.' u' <a href="%(form_url)s">Enter Web Form</a>' u' or <a href="#preview-modal" data-toggle="modal">' u'Preview Web Form</a>') % {'form_id': survey.id_string, 'form_url': enketo_webform_url} }
def download_media_data(request, username, id_string, data_id): xform = get_object_or_404( XForm, user__username=username, id_string=id_string) owner = xform.user data = get_object_or_404(MetaData, id=data_id) dfs = get_storage_class()() if request.GET.get('del', False): if username == request.user.username: try: # ensure filename is not an empty string if data.data_file.name != '': dfs.delete(data.data_file.name) data.delete() audit = { 'xform': xform.id_string } audit_log( Actions.FORM_UPDATED, request.user, owner, _("Media download '%(filename)s' deleted from " "'%(id_string)s'.") % { 'id_string': xform.id_string, 'filename': os.path.basename(data.data_file.name) }, audit, request) return HttpResponseRedirect(reverse(show, kwargs={ 'username': username, 'id_string': id_string })) except Exception as e: return HttpResponseServerError(e) else: if username: # == request.user.username or xform.shared: if data.data_file.name == '' and data.data_value is not None: return HttpResponseRedirect(data.data_value) file_path = data.data_file.name filename, extension = os.path.splitext(file_path.split('/')[-1]) extension = extension.strip('.') if dfs.exists(file_path): audit = { 'xform': xform.id_string } audit_log( Actions.FORM_UPDATED, request.user, owner, _("Media '%(filename)s' downloaded from " "'%(id_string)s'.") % { 'id_string': xform.id_string, 'filename': os.path.basename(file_path) }, audit, request) response = response_with_mimetype_and_name( data.data_file_type, filename, extension=extension, show_date=False, file_path=file_path) return response else: return HttpResponseNotFound() return HttpResponseForbidden(_(u'Permission denied.'))
def retrieve(self, request, *args, **kwargs): lookup_field = self.lookup_field lookup = self.kwargs.get(lookup_field) if lookup == self.public_forms_endpoint: self.object_list = self._get_public_forms_queryset() page = self.paginate_queryset(self.object_list) if page is not None: serializer = self.get_pagination_serializer(page) else: serializer = self.get_serializer(self.object_list, many=True) return Response(serializer.data) xform = self.get_object() query = request.GET.get("query", {}) export_type = kwargs.get('format') if export_type is None or export_type in ['json']: # perform default viewset retrieve, no data export return super(XFormViewSet, self).retrieve(request, *args, **kwargs) export_type = _get_export_type(export_type) # check if we need to re-generate, # we always re-generate if a filter is specified if should_regenerate_export(xform, export_type, request): export = _generate_new_export(request, xform, query, export_type) else: export = newset_export_for(xform, export_type) # log download as well audit = { "xform": xform.id_string, "export_type": export_type } log.audit_log( log.Actions.EXPORT_DOWNLOADED, request.user, xform.user, _("Downloaded %(export_type)s export on '%(id_string)s'.") % { 'id_string': xform.id_string, 'export_type': export_type.upper() }, audit, request) if not export.filename: # tends to happen when using newset_export_for. raise Http404("File does not exist!") # get extension from file_path, exporter could modify to # xlsx if it exceeds limits path, ext = os.path.splitext(export.filename) ext = ext[1:] id_string = None if request.GET.get('raw') else xform.id_string response = response_with_mimetype_and_name( Export.EXPORT_MIMES[ext], id_string, extension=ext, file_path=export.filepath) return response
def generate_instance(username, xml_file, media_files, uuid=None): ''' Process an XForm submission as if done via HTTP :param IO xml_file: file-like object containing XML XForm :param string username: username of the Form's owner :param list media_files: a list of UploadedFile objects :param string uuid: an optionnal uuid for the instance. :returns a (status, message) tuple. ''' try: instance = create_instance( username, xml_file, media_files, uuid=uuid ) except InstanceInvalidUserError: return {'code': SMS_SUBMISSION_REFUSED, 'text': _(u"Username or ID required.")} except InstanceEmptyError: return {'code': SMS_INTERNAL_ERROR, 'text': _(u"Received empty submission. " u"No instance was created")} except FormInactiveError: return {'code': SMS_SUBMISSION_REFUSED, 'text': _(u"Form is not active")} except XForm.DoesNotExist: return {'code': SMS_SUBMISSION_REFUSED, 'text': _(u"Form does not exist on this account")} except ExpatError: return {'code': SMS_INTERNAL_ERROR, 'text': _(u"Improperly formatted XML.")} except DuplicateInstance: return {'code': SMS_SUBMISSION_REFUSED, 'text': _(u"Duplicate submission")} if instance is None: return {'code': SMS_INTERNAL_ERROR, 'text': _(u"Unable to create submission.")} user = User.objects.get(username=username) audit = { "xform": instance.xform.id_string } audit_log(Actions.SUBMISSION_CREATED, user, instance.xform.user, _("Created submission on form %(id_string)s.") % {"id_string": instance.xform.id_string}, audit, HttpRequest()) xml_file.close() if len(media_files): [_file.close() for _file in media_files] return {'code': SMS_SUBMISSION_ACCEPTED, 'text': _(u"[SUCCESS] Your submission has been accepted."), 'id': get_sms_instance_id(instance)}
def bulksubmission(request, username): """ Bulk submission view. """ # puts it in a temp directory. # runs "import_tools(temp_directory)" # deletes posting_user = get_object_or_404(User, username__iexact=username) # request.FILES is a django.utils.datastructures.MultiValueDict # for each key we have a list of values try: temp_postfile = request.FILES.pop("zip_submission_file", []) except IOError: return HttpResponseBadRequest( _(u"There was a problem receiving your " u"ODK submission. [Error: IO Error " u"reading data]")) if len(temp_postfile) != 1: return HttpResponseBadRequest( _(u"There was a problem receiving your" u" ODK submission. [Error: multiple " u"submission files (?)]")) postfile = temp_postfile[0] tempdir = tempfile.gettempdir() our_tfpath = os.path.join(tempdir, postfile.name) with open(our_tfpath, 'wb') as f: f.write(postfile.read()) with open(our_tfpath, 'rb') as f: total_count, success_count, errors = import_instances_from_zip( f, posting_user) # chose the try approach as suggested by the link below # http://stackoverflow.com/questions/82831 try: os.remove(our_tfpath) except IOError: pass json_msg = { 'message': _(u"Submission complete. Out of %(total)d " u"survey instances, %(success)d were imported, " u"(%(rejected)d were rejected as duplicates, " u"missing forms, etc.)") % { 'total': total_count, 'success': success_count, 'rejected': total_count - success_count }, 'errors': u"%d %s" % (len(errors), errors) } audit = {"bulk_submission_log": json_msg} audit_log(Actions.USER_BULK_SUBMISSION, request.user, posting_user, _("Made bulk submissions."), audit, request) response = HttpResponse(json.dumps(json_msg)) response.status_code = 200 response['Location'] = request.build_absolute_uri(request.path) return response
def create_export(request, username, id_string, export_type): owner = get_object_or_404(User, username=username) xform = get_object_or_404(XForm, id_string=id_string, user=owner) if not has_permission(xform, owner, request): return HttpResponseForbidden(_(u'Not shared.')) query = request.POST.get("query") force_xlsx = request.POST.get('xls') != 'true' # export options group_delimiter = request.POST.get("options[group_delimiter]", '/') if group_delimiter not in ['.', '/']: return HttpResponseBadRequest( _("%s is not a valid delimiter" % group_delimiter)) # default is True, so when dont_.. is yes # split_select_multiples becomes False split_select_multiples = request.POST.get( "options[dont_split_select_multiples]", "no") == "no" binary_select_multiples = getattr(settings, 'BINARY_SELECT_MULTIPLES', False) options = { 'group_delimiter': group_delimiter, 'split_select_multiples': split_select_multiples, 'binary_select_multiples': binary_select_multiples } try: create_async_export(xform, export_type, query, force_xlsx, options) except Export.ExportTypeError: return HttpResponseBadRequest( _("%s is not a valid export type" % export_type)) else: audit = { "xform": xform.id_string, "export_type": export_type } audit_log( Actions.EXPORT_CREATED, request.user, owner, _("Created %(export_type)s export on '%(id_string)s'.") % { 'export_type': export_type.upper(), 'id_string': xform.id_string, }, audit, request) return HttpResponseRedirect(reverse( export_list, kwargs={ "username": username, "id_string": id_string, "export_type": export_type }) )
def public_profile(request, username): content_user = check_and_set_user(request, username) if isinstance(content_user, HttpResponseRedirect): return content_user context = RequestContext(request) set_profile_data(context, content_user) context.is_owner = request.user == content_user audit = {} audit_log( Actions.PUBLIC_PROFILE_ACCESSED, request.user, content_user, _("Public profile accessed."), audit, request) return render_to_response("profile.html", context_instance=context)
def download_xlsform(request, username, id_string): xform = get_object_or_404(XForm, user__username__iexact=username, id_string__exact=id_string) owner = User.objects.get(username__iexact=username) helper_auth_helper(request) if not has_permission(xform, owner, request, xform.shared): return HttpResponseForbidden('Not shared.') file_path = xform.xls.name default_storage = get_storage_class()() if file_path != '' and default_storage.exists(file_path): audit = { "xform": xform.id_string } audit_log( Actions.FORM_XLS_DOWNLOADED, request.user, xform.user, _("Downloaded XLS file for form '%(id_string)s'.") % { "id_string": xform.id_string }, audit, request) if file_path.endswith('.csv'): with default_storage.open(file_path) as ff: xls_io = convert_csv_to_xls(ff.read()) response = StreamingHttpResponse( xls_io, content_type='application/vnd.ms-excel; charset=utf-8') response[ 'Content-Disposition'] = 'attachment; filename=%s.xls' % xform.id_string return response split_path = file_path.split(os.extsep) extension = 'xls' if len(split_path) > 1: extension = split_path[len(split_path) - 1] response = response_with_mimetype_and_name( 'vnd.ms-excel', id_string, show_date=False, extension=extension, file_path=file_path) return response else: messages.add_message(request, messages.WARNING, _(u'No XLS file for your form ' u'<strong>%(id)s</strong>') % {'id': id_string}) return HttpResponseRedirect("/%s" % username)
def log_export(request, xform, export_type): # log download as well audit = { "xform": xform.id_string, "export_type": export_type } log.audit_log( log.Actions.EXPORT_DOWNLOADED, request.user, xform.user, _("Downloaded %(export_type)s export on '%(id_string)s'.") % { 'id_string': xform.id_string, 'export_type': export_type.upper() }, audit, request)
def public_profile(request, username): content_user = check_and_set_user(request, username) if isinstance(content_user, HttpResponseRedirect): return content_user data = {} set_profile_data(data, content_user) data['is_owner'] = request.user == content_user audit = {} audit_log( Actions.PUBLIC_PROFILE_ACCESSED, request.user, content_user, _("Public profile accessed."), audit, request) return render(request, "profile.html", data)
def download_xlsform(request, username, id_string): xform = get_object_or_404(XForm, user__username__iexact=username, id_string__exact=id_string) owner = User.objects.get(username__iexact=username) helper_auth_helper(request) if not has_permission(xform, owner, request, xform.shared): return HttpResponseForbidden('Not shared.') file_path = xform.xls.name default_storage = get_storage_class()() if file_path != '' and default_storage.exists(file_path): audit = {"xform": xform.id_string} audit_log( Actions.FORM_XLS_DOWNLOADED, request.user, xform.user, _("Downloaded XLS file for form '%(id_string)s'.") % {"id_string": xform.id_string}, audit, request) if file_path.endswith('.csv'): with default_storage.open(file_path) as ff: xls_io = convert_csv_to_xls(ff.read()) response = StreamingHttpResponse( xls_io, content_type='application/vnd.ms-excel; charset=utf-8') response[ 'Content-Disposition'] = 'attachment; filename=%s.xls' % xform.id_string return response split_path = file_path.split(os.extsep) extension = 'xls' if len(split_path) > 1: extension = split_path[len(split_path) - 1] response = response_with_mimetype_and_name('vnd.ms-excel', id_string, show_date=False, extension=extension, file_path=file_path) return response else: messages.add_message( request, messages.WARNING, _(u'No XLS file for your form ' u'<strong>%(id)s</strong>') % {'id': id_string}) return HttpResponseRedirect("/%s" % username)
def formList(request, username): # pylint: disable=C0103 """ formList view, /formList OpenRosa Form Discovery API 1.0. """ formlist_user = get_object_or_404(User, username__iexact=username) profile = cache.get(f'{USER_PROFILE_PREFIX}{formlist_user.username}') if not profile: profile, __ = UserProfile.objects.get_or_create( user__username=formlist_user.username) if profile.require_auth: authenticator = HttpDigestAuthenticator() if not authenticator.authenticate(request): return authenticator.build_challenge_response() # unauthorized if user in auth request does not match user in path # unauthorized if user not active if not request.user.is_active: return HttpResponseNotAuthorized() # filter private forms (where require_auth=False) # for users who are non-owner if request.user.username == profile.user.username: xforms = XForm.objects.filter(downloadable=True, deleted_at__isnull=True, user__username__iexact=username) else: xforms = XForm.objects.filter(downloadable=True, deleted_at__isnull=True, user__username__iexact=username, require_auth=False) audit = {} audit_log(Actions.USER_FORMLIST_REQUESTED, request.user, formlist_user, _("Requested forms list."), audit, request) data = { 'host': request.build_absolute_uri().replace(request.get_full_path(), ''), 'xforms': xforms } response = render(request, "xformsList.xml", data, content_type="text/xml; charset=utf-8") response['X-OpenRosa-Version'] = '1.0' response['Date'] = datetime.now(pytz.timezone(settings.TIME_ZONE))\ .strftime('%a, %d %b %Y %H:%M:%S %Z') return response
def formList(request, username): # pylint: disable=C0103 """ formList view, /formList OpenRosa Form Discovery API 1.0. """ formlist_user = get_object_or_404(User, username__iexact=username) profile, __ = UserProfile.objects.get_or_create(user=formlist_user) if profile.require_auth: authenticator = HttpDigestAuthenticator() if not authenticator.authenticate(request): return authenticator.build_challenge_response() # unauthorized if user in auth request does not match user in path # unauthorized if user not active if not request.user.is_active: return HttpResponseNotAuthorized() # filter private forms (where require_auth=False) # for users who are non-owner if request.user.username == profile.user.username: xforms = XForm.objects.filter( downloadable=True, deleted_at__isnull=True, user__username__iexact=username) else: xforms = XForm.objects.filter( downloadable=True, deleted_at__isnull=True, user__username__iexact=username, require_auth=False) audit = {} audit_log(Actions.USER_FORMLIST_REQUESTED, request.user, formlist_user, _("Requested forms list."), audit, request) data = { 'host': request.build_absolute_uri().replace(request.get_full_path(), ''), 'xforms': xforms } response = render( request, "xformsList.xml", data, content_type="text/xml; charset=utf-8") response['X-OpenRosa-Version'] = '1.0' response['Date'] = datetime.now(pytz.timezone(settings.TIME_ZONE))\ .strftime('%a, %d %b %Y %H:%M:%S %Z') return response
def map_view(request, username, id_string, template='map.html'): owner = get_object_or_404(User, username__iexact=username) xform = get_object_or_404(XForm, id_string__exact=id_string, user=owner) if not has_permission(xform, owner, request): return HttpResponseForbidden(_(u'Not shared.')) data = {'content_user': owner, 'xform': xform} data['profile'], created = UserProfile.objects.get_or_create(user=owner) # Follow the example of onadata.apps.main.views.show data['can_edit'] = has_edit_permission(xform, owner, request) data['form_view'] = True data['jsonform_url'] = reverse(download_jsonform, kwargs={ "username": username, "id_string": id_string }) data['enketo_edit_url'] = reverse('edit_data', kwargs={ "username": username, "id_string": id_string, "data_id": 0 }) data['enketo_add_url'] = reverse('enter_data', kwargs={ "username": username, "id_string": id_string }) data['enketo_add_with_url'] = reverse('add_submission_with', kwargs={ "username": username, "id_string": id_string }) data['mongo_api_url'] = reverse('mongo_view_api', kwargs={ "username": username, "id_string": id_string }) data['delete_data_url'] = reverse('delete_data', kwargs={ "username": username, "id_string": id_string }) data['mapbox_layer'] = MetaData.mapbox_layer_upload(xform) audit = {"xform": xform.id_string} audit_log( Actions.FORM_MAP_VIEWED, request.user, owner, _("Requested map on '%(id_string)s'.") % {'id_string': xform.id_string}, audit, request) return render(request, template, data)
def toggle_downloadable(request, username, id_string): xform = XForm.objects.get(user__username=username, id_string=id_string) xform.downloadable = not xform.downloadable xform.save() audit = {} audit_log( Actions.FORM_UPDATED, request.user, xform.user, _("Made form '%(id_string)s' %(downloadable)s.") % { 'id_string': xform.id_string, 'downloadable': _("downloadable") if xform.downloadable else _("un-downloadable") }, audit, request) return HttpResponseRedirect("/%s" % username)
def map_view(request, username, id_string, template='map.html'): owner = get_object_or_404(User, username=username) xform = get_object_or_404(XForm, id_string=id_string, user=owner) if not has_permission(xform, owner, request): return HttpResponseForbidden(_(u'Not shared.')) context = RequestContext(request) context.content_user = owner context.xform = xform context.profile, created = UserProfile.objects.get_or_create(user=owner) context.form_view = True context.jsonform_url = reverse(download_jsonform, kwargs={ "username": username, "id_string": id_string }) context.enketo_edit_url = reverse('edit_data', kwargs={ "username": username, "id_string": id_string, "data_id": 0 }) context.enketo_add_url = reverse('enter_data', kwargs={ "username": username, "id_string": id_string }) context.enketo_add_with_url = reverse('add_submission_with', kwargs={ "username": username, "id_string": id_string }) context.mongo_api_url = reverse('mongo_view_api', kwargs={ "username": username, "id_string": id_string }) context.delete_data_url = reverse('delete_data', kwargs={ "username": username, "id_string": id_string }) context.mapbox_layer = MetaData.mapbox_layer_upload(xform) audit = {"xform": xform.id_string} audit_log( Actions.FORM_MAP_VIEWED, request.user, owner, _("Requested map on '%(id_string)s'.") % {'id_string': xform.id_string}, audit, request) return render_to_response(template, context_instance=context)
def google_xls_export(request, username, id_string): """ Google export view, uploads an excel export to google drive and then redirects to the uploaded google sheet. """ token = None if request.user.is_authenticated: try: token_storage = TokenStorageModel.objects.get(id=request.user) except TokenStorageModel.DoesNotExist: pass else: token = token_storage.token elif request.session.get('access_token'): token = request.session.get('access_token') if token is None: request.session["google_redirect_url"] = reverse( google_xls_export, kwargs={'username': username, 'id_string': id_string}) return HttpResponseRedirect(google_flow.step1_get_authorize_url()) owner = get_object_or_404(User, username__iexact=username) xform = get_form({'user': owner, 'id_string__iexact': id_string}) if not has_permission(xform, owner, request): return HttpResponseForbidden(_(u'Not shared.')) is_valid, data_dictionary = set_instances_for_export( id_string, owner, request) if not is_valid: return data_dictionary xls_writer = XlsWriter() tmp = NamedTemporaryFile(delete=False) xls_writer.set_file(tmp) xls_writer.set_data_dictionary(data_dictionary) temp_file = xls_writer.save_workbook_to_file() temp_file.close() url = None os.unlink(tmp.name) audit = {"xform": xform.id_string, "export_type": "google"} audit_log(Actions.EXPORT_CREATED, request.user, owner, _("Created Google Docs export on '%(id_string)s'.") % { 'id_string': xform.id_string, }, audit, request) return HttpResponseRedirect(url)
def pending_instance(request, username, id_string): print('(apps/viewer/views.py) Action: data view from instance controller') xform_owner = get_object_or_404(XForm, id_string__exact=id_string) xform, is_owner, can_edit, can_view = get_xform_and_perms( xform_owner.user.username, id_string, request) if request.user.username is not None: username = request.user.username print('\n\n username : '******'\n form_id: ' + id_string + '\n' + '\n submission_id: ' + request.GET.get('s_id', '') + '\n') # no access if not (xform.shared_data or can_view or request.session.get('public_link') == xform.uuid): return HttpResponseForbidden(_(u'Not shared.')) audit = { "xform": xform.id_string, } audit_log( Actions.FORM_DATA_VIEWED, request.user, xform.user, _("Requested instance view for '%(id_string)s'.") % { 'id_string': xform.id_string, }, audit, request) _id_string = request.GET.get('s_id', '') _instance = get_object_or_404(Instance, id__exact=_id_string) note_list = Note.objects.filter(instance=_instance).distinct() approvals = ApprovalList.objects.filter(userid=username, formid=id_string, subbmissionid=_id_string).first() is_approved_or_reject = 'true' if approvals is not None: is_approved_or_reject = 'false' if approvals.status == 'Approved' or approvals.status == 'Reject': is_approved_or_reject = 'true' elif approvals.status == 'Upcoming' or approvals.status == 'Notify': is_approved_or_reject = 'true' return render( request, 'pending_instance.html', { 'username': xform.user.username, 'id_string': id_string, 'xform': xform, 'can_edit': can_edit, 'note_list': note_list, 'is_approved_or_reject': is_approved_or_reject })
def create_export(request, username, id_string, export_type): owner = get_object_or_404(User, username=username) xform = get_object_or_404(XForm, id_string=id_string, user=owner) if not has_permission(xform, owner, request): return HttpResponseForbidden(_(u'Not shared.')) query = request.POST.get("query") force_xlsx = request.POST.get('xls') != 'true' # export options group_delimiter = request.POST.get("options[group_delimiter]", '/') if group_delimiter not in ['.', '/']: return HttpResponseBadRequest( _("%s is not a valid delimiter" % group_delimiter)) # default is True, so when dont_.. is yes # split_select_multiples becomes False split_select_multiples = request.POST.get( "options[dont_split_select_multiples]", "no") == "no" binary_select_multiples = getattr(settings, 'BINARY_SELECT_MULTIPLES', False) options = { 'group_delimiter': group_delimiter, 'split_select_multiples': split_select_multiples, 'binary_select_multiples': binary_select_multiples } try: create_async_export(xform, export_type, query, force_xlsx, options) except Export.ExportTypeError: return HttpResponseBadRequest( _("%s is not a valid export type" % export_type)) else: audit = {"xform": xform.id_string, "export_type": export_type} audit_log( Actions.EXPORT_CREATED, request.user, owner, _("Created %(export_type)s export on '%(id_string)s'.") % { 'export_type': export_type.upper(), 'id_string': xform.id_string, }, audit, request) return HttpResponseRedirect( reverse(export_list, kwargs={ "username": username, "id_string": id_string, "export_type": export_type }))
def _generate_new_export(request, xform, query, export_type): query = _set_start_end_params(request, query) extension = _get_extension_from_export_type(export_type) try: if export_type == Export.EXTERNAL_EXPORT: export = generate_external_export( export_type, xform.user.username, xform.id_string, None, request.GET.get('token'), query, request.GET.get('meta'), request.GET.get('data_id') ) elif export_type == Export.OSM_EXPORT: export = generate_osm_export( export_type, extension, xform.user.username, xform.id_string, export_id=None, filter_query=None) elif export_type == Export.KML_EXPORT: export = generate_kml_export( export_type, extension, xform.user.username, xform.id_string, export_id=None, filter_query=None) else: remove_group_name = False if "remove_group_name" in request.QUERY_PARAMS: remove_group_name = \ str_to_bool(request.QUERY_PARAMS["remove_group_name"]) export = generate_export( export_type, extension, xform.user.username, xform.id_string, None, query, remove_group_name=remove_group_name ) audit = { "xform": xform.id_string, "export_type": export_type } log.audit_log( log.Actions.EXPORT_CREATED, request.user, xform.user, _("Created %(export_type)s export on '%(id_string)s'.") % { 'id_string': xform.id_string, 'export_type': export_type.upper() }, audit, request) except NoRecordsFoundError: raise Http404(_("No records found to export")) except J2XException as e: # j2x exception return {'error': str(e)} else: return export
def google_xls_export(request, username, id_string): """ Google export view, uploads an excel export to google drive and then redirects to the uploaded google sheet. """ token = None if request.user.is_authenticated(): try: token_storage = TokenStorageModel.objects.get(id=request.user) except TokenStorageModel.DoesNotExist: pass else: token = token_storage.token elif request.session.get('access_token'): token = request.session.get('access_token') if token is None: request.session["google_redirect_url"] = reverse( google_xls_export, kwargs={'username': username, 'id_string': id_string}) return HttpResponseRedirect(google_flow.step1_get_authorize_url()) owner = get_object_or_404(User, username__iexact=username) xform = get_form({'user': owner, 'id_string__iexact': id_string}) if not has_permission(xform, owner, request): return HttpResponseForbidden(_(u'Not shared.')) is_valid, data_dictionary = set_instances_for_export( id_string, owner, request) if not is_valid: return data_dictionary xls_writer = XlsWriter() tmp = NamedTemporaryFile(delete=False) xls_writer.set_file(tmp) xls_writer.set_data_dictionary(data_dictionary) temp_file = xls_writer.save_workbook_to_file() temp_file.close() url = None os.unlink(tmp.name) audit = {"xform": xform.id_string, "export_type": "google"} audit_log(Actions.EXPORT_CREATED, request.user, owner, _("Created Google Docs export on '%(id_string)s'.") % { 'id_string': xform.id_string, }, audit, request) return HttpResponseRedirect(url)
def delete_xform(request, username, id_string): xform = get_object_or_404(XForm, user__username__iexact=username, id_string__exact=id_string) # delete xform and submissions remove_xform(xform) audit = {} audit_log( Actions.FORM_DELETED, request.user, xform.user, _("Deleted form '%(id_string)s'.") % { 'id_string': xform.id_string, }, audit, request) return HttpResponseRedirect('/')
def delete_xform(request, username, id_string): xform = get_object_or_404(XForm, user__username=username, id_string=id_string) # delete xform and submissions remove_xform(xform) audit = {} audit_log( Actions.FORM_DELETED, request.user, xform.user, _("Deleted form '%(id_string)s'.") % { 'id_string': xform.id_string, }, audit, request) return HttpResponseRedirect('/')
def formList(request, username): """ This is where ODK Collect gets its download list. """ if username.lower() == 'crowdforms': xforms = XForm.objects.filter(is_crowd_form=True)\ .exclude(user__username=username) else: formlist_user = get_object_or_404(User, username=username) profile, created = \ UserProfile.objects.get_or_create(user=formlist_user) if profile.require_auth: authenticator = HttpDigestAuthenticator() if not authenticator.authenticate(request): return authenticator.build_challenge_response() # unauthorized if user in auth request does not match user in path # unauthorized if user not active if formlist_user.username != request.user.username or\ not request.user.is_active: return HttpResponseNotAuthorized() xforms = \ XForm.objects.filter(downloadable=True, user__username=username) # retrieve crowd_forms for this user crowdforms = XForm.objects.filter( metadata__data_type=MetaData.CROWDFORM_USERS, metadata__data_value=username) xforms = chain(xforms, crowdforms) audit = {} audit_log(Actions.USER_FORMLIST_REQUESTED, request.user, formlist_user, _("Requested forms list."), audit, request) response = render_to_response( "xformsList.xml", { #'urls': urls, 'host': request.build_absolute_uri().replace(request.get_full_path(), ''), 'xforms': xforms }, mimetype="text/xml; charset=utf-8") response['X-OpenRosa-Version'] = '1.0' tz = pytz.timezone(settings.TIME_ZONE) dt = datetime.now(tz).strftime('%a, %d %b %Y %H:%M:%S %Z') response['Date'] = dt return response
def google_xls_export(request, username, id_string): token = None if request.user.is_authenticated(): try: ts = TokenStorageModel.objects.get(id=request.user) except TokenStorageModel.DoesNotExist: pass else: token = ts.token elif request.session.get('access_token'): token = request.session.get('access_token') if token is None: request.session["google_redirect_url"] = reverse(google_xls_export, kwargs={ 'username': username, 'id_string': id_string }) return HttpResponseRedirect(redirect_uri) owner = get_object_or_404(User, username__iexact=username) xform = get_object_or_404(XForm, id_string__exact=id_string, user=owner) if not has_permission(xform, owner, request): return HttpResponseForbidden(_(u'Not shared.')) valid, dd = dd_for_params(id_string, owner, request) if not valid: return dd ddw = XlsWriter() tmp = NamedTemporaryFile(delete=False) ddw.set_file(tmp) ddw.set_data_dictionary(dd) temp_file = ddw.save_workbook_to_file() temp_file.close() url = google_export_xls(tmp.name, xform.title, token, blob=True) os.unlink(tmp.name) audit = {"xform": xform.id_string, "export_type": "google"} audit_log( Actions.EXPORT_CREATED, request.user, owner, _("Created Google Docs export on '%(id_string)s'.") % { 'id_string': xform.id_string, }, audit, request) return HttpResponseRedirect(url)
def formList(request, username): """ This is where ODK Collect gets its download list. """ formlist_user = get_object_or_404(User, username__iexact=username) profile, created = UserProfile.objects.get_or_create(user=formlist_user) if profile.require_auth: authenticator = HttpDigestAuthenticator() if not authenticator.authenticate(request): return authenticator.build_challenge_response() # unauthorized if user in auth request does not match user in path # unauthorized if user not active if not request.user.is_active: return HttpResponseNotAuthorized() # filter private forms (where require_auth=False) # for users who are non-owner if request.user.username == profile.user.username: xforms = XForm.objects.filter(downloadable=True, user__username__iexact=username) else: xforms = XForm.objects.filter(downloadable=True, user__username__iexact=username, require_auth=False) audit = {} audit_log(Actions.USER_FORMLIST_REQUESTED, request.user, formlist_user, _("Requested forms list."), audit, request) data = { 'host': request.build_absolute_uri().replace(request.get_full_path(), ''), 'xforms': xforms } response = render(request, "xformsList.xml", data, content_type="text/xml; charset=utf-8") response['X-OpenRosa-Version'] = '1.0' tz = pytz.timezone(settings.TIME_ZONE) dt = datetime.now(tz).strftime('%a, %d %b %Y %H:%M:%S %Z') response['Date'] = dt return response
def data_view(request, username, id_string): owner = get_object_or_404(User, username__iexact=username) xform = get_object_or_404(XForm, id_string__exact=id_string, user=owner) if not has_permission(xform, owner, request): return HttpResponseForbidden(_(u'Not shared.')) data = {'owner': owner, 'xform': xform} audit = { "xform": xform.id_string, } audit_log( Actions.FORM_DATA_VIEWED, request.user, owner, _("Requested data view for '%(id_string)s'.") % { 'id_string': xform.id_string, }, audit, request) return render(request, "data_view.html", data)
def download_xlsform(request, username, id_string): """ Download XLSForm view. """ xform = get_form({ 'user__username__iexact': username, 'id_string__iexact': id_string }) owner = User.objects.get(username__iexact=username) helper_auth_helper(request) if not has_permission(xform, owner, request, xform.shared): return HttpResponseForbidden('Not shared.') file_path = xform.xls.name default_storage = get_storage_class()() if file_path != '' and default_storage.exists(file_path): audit = {"xform": xform.id_string} audit_log( Actions.FORM_XLS_DOWNLOADED, request.user, xform.user, _("Downloaded XLS file for form '%(id_string)s'.") % {"id_string": xform.id_string}, audit, request) split_path = file_path.split(os.extsep) extension = 'xls' if len(split_path) > 1: extension = split_path[len(split_path) - 1] response = response_with_mimetype_and_name('vnd.ms-excel', id_string, show_date=False, extension=extension, file_path=file_path) return response else: messages.add_message( request, messages.WARNING, _(u'No XLS file for your form ' u'<strong>%(id)s</strong>') % {'id': id_string}) return HttpResponseRedirect("/%s" % username)
def test_audit_log_call(self): account_user = User(username="******") request_user = User(username="******") request = RequestFactory().get("/") # create a log audit = {} audit_log(Actions.FORM_PUBLISHED, request_user, account_user, "Form published", audit, request) # function should just run without exception so we are good at this # point query for this log entry sort = {"created_on": -1} cursor = AuditLog.query_mongo(account_user.username, None, None, sort, 0, 1) self.assertTrue(cursor.count() > 0) record = cursor.next() self.assertEqual(record['account'], "alice") self.assertEqual(record['user'], "bob") self.assertEqual(record['action'], Actions.FORM_PUBLISHED)
def data_view(request, username, id_string): owner = get_object_or_404(User, username=username) xform = get_object_or_404(XForm, id_string=id_string, user=owner) if not has_permission(xform, owner, request): return HttpResponseForbidden(_(u'Not shared.')) context = RequestContext(request) context.owner = owner context.xform = xform audit = { "xform": xform.id_string, } audit_log( Actions.FORM_DATA_VIEWED, request.user, owner, _("Requested data view for '%(id_string)s'.") % { 'id_string': xform.id_string, }, audit, request) return render_to_response("data_view.html", context_instance=context)
def delete_xform(request, username, id_string): """ Delete XForm view. """ xform = get_form({ 'user__username__iexact': username, 'id_string__iexact': id_string }) # delete xform and submissions remove_xform(xform) audit = {} audit_log(Actions.FORM_DELETED, request.user, xform.user, _("Deleted form '%(id_string)s'.") % { 'id_string': xform.id_string, }, audit, request) return HttpResponseRedirect('/')
def _generate_new_export(request, xform, query, export_type): query = _set_start_end_params(request, query) extension = _get_extension_from_export_type(export_type) try: export = generate_export(export_type, extension, xform.user.username, xform.id_string, None, query) audit = {"xform": xform.id_string, "export_type": export_type} log.audit_log( log.Actions.EXPORT_CREATED, request.user, xform.user, t("Created %(export_type)s export on '%(id_string)s'.") % { 'id_string': xform.id_string, 'export_type': export_type.upper() }, audit, request) except NoRecordsFoundError: raise Http404(t("No records found to export")) else: return export
def delete_xform(request, username, id_string): try: xform = get_object_or_404(XForm, user__username__iexact=username, id_string__iexact=id_string) except MultipleObjectsReturned: return HttpResponse("Your account has multiple forms with same formid") # delete xform and submissions remove_xform(xform) audit = {} audit_log( Actions.FORM_DELETED, request.user, xform.user, _("Deleted form '%(id_string)s'.") % { 'id_string': xform.id_string, }, audit, request) return HttpResponseRedirect('/')
def export_download(request, username, id_string, export_type, filename): """ Export download view. """ owner = get_object_or_404(User, username__iexact=username) xform = get_form({'user': owner, 'id_string__iexact': id_string}) helper_auth_helper(request) if not has_permission(xform, owner, request): return HttpResponseForbidden(_(u'Not shared.')) # find the export entry in the db export = get_object_or_404(Export, xform=xform, filename=filename) if (export_type == Export.GOOGLE_SHEETS_EXPORT or export_type == Export.EXTERNAL_EXPORT) and \ export.export_url is not None: return HttpResponseRedirect(export.export_url) ext, mime_type = export_def_from_filename(export.filename) audit = {"xform": xform.id_string, "export_type": export.export_type} audit_log( Actions.EXPORT_DOWNLOADED, request.user, owner, _("Downloaded %(export_type)s export '%(filename)s' " "on '%(id_string)s'.") % { 'export_type': export.export_type.upper(), 'filename': export.filename, 'id_string': xform.id_string, }, audit, request) if request.GET.get('raw'): id_string = None default_storage = get_storage_class()() if not isinstance(default_storage, FileSystemStorage): return HttpResponseRedirect(default_storage.url(export.filepath)) basename = os.path.splitext(export.filename)[0] response = response_with_mimetype_and_name(mime_type, name=basename, extension=ext, file_path=export.filepath, show_date=False) return response
def delete_metadata(request, username, id_string, data_id): xform = get_object_or_404(XForm, user__username=username, id_string=id_string) owner = xform.user data = get_object_or_404(MetaData, pk=data_id) dfs = get_storage_class()() req_username = request.user.username if request.GET.get('del', False) and username == req_username: try: dfs.delete(data.data_file.name) data.delete() audit = { 'xform': xform.id_string } audit_log( Actions.FORM_UPDATED, request.user, owner, _("Document '%(filename)s' deleted from '%(id_string)s'.") % { 'id_string': xform.id_string, 'filename': os.path.basename(data.data_file.name) }, audit, request) return HttpResponseRedirect(reverse(show, kwargs={ 'username': username, 'id_string': id_string })) except Exception: return HttpResponseServerError() elif request.GET.get('map_name_del', False) and username == req_username: data.delete() audit = { 'xform': xform.id_string } audit_log( Actions.FORM_UPDATED, request.user, owner, _("Map layer deleted from '%(id_string)s'.") % { 'id_string': xform.id_string, }, audit, request) return HttpResponseRedirect(reverse(show, kwargs={ 'username': username, 'id_string': id_string })) return HttpResponseForbidden(_(u'Permission denied.'))
def edit(request, username, id_string): xform = XForm.objects.get(user__username__iexact=username, id_string__exact=id_string) owner = xform.user if username == request.user.username or\ request.user.has_perm('logger.change_xform', xform): if request.POST.get('media_url'): uri = request.POST.get('media_url') try: SSRFProtect.validate(uri) except SSRFProtectException: return HttpResponseForbidden( t('URL {uri} is forbidden.').format(uri=uri)) MetaData.media_add_uri(xform, uri) elif request.FILES.get('media'): audit = {'xform': xform.id_string} audit_log( Actions.FORM_UPDATED, request.user, owner, t("Media added to '%(id_string)s'.") % {'id_string': xform.id_string}, audit, request) for aFile in request.FILES.getlist("media"): MetaData.media_upload(xform, aFile) xform.update() if request.is_ajax(): return HttpResponse(t('Updated succeeded.')) else: if 'HTTP_REFERER' in request.META and request.META[ 'HTTP_REFERER'].strip(): return HttpResponseRedirect(request.META['HTTP_REFERER']) return HttpResponseRedirect( reverse(show, kwargs={ 'username': username, 'id_string': id_string })) return HttpResponseForbidden(t('Update failed.'))
def zip_export(request, username, id_string): owner = get_object_or_404(User, username=username) xform = get_object_or_404(XForm, id_string=id_string, user=owner) helper_auth_helper(request) if not has_permission(xform, owner, request): return HttpResponseForbidden(_(u'Not shared.')) if request.GET.get('raw'): id_string = None attachments = Attachment.objects.filter(instance__xform=xform) zip_file = None try: zip_file = create_attachments_zipfile(attachments) audit = { "xform": xform.id_string, "export_type": Export.ZIP_EXPORT } audit_log( Actions.EXPORT_CREATED, request.user, owner, _("Created ZIP export on '%(id_string)s'.") % { 'id_string': xform.id_string, }, audit, request) # log download as well audit_log( Actions.EXPORT_DOWNLOADED, request.user, owner, _("Downloaded ZIP export on '%(id_string)s'.") % { 'id_string': xform.id_string, }, audit, request) if request.GET.get('raw'): id_string = None response = response_with_mimetype_and_name('zip', id_string) response.write(FileWrapper(zip_file)) response['Content-Length'] = zip_file.tell() zip_file.seek(0) finally: zip_file and zip_file.close() return response
def toggle_downloadable(request, username, id_string): """ Toggle XForm view, changes downloadable status of a form. """ xform = get_form({ 'user__username__iexact': username, 'id_string__iexact': id_string }) xform.downloadable = not xform.downloadable xform.save() audit = {} audit_log( Actions.FORM_UPDATED, request.user, xform.user, _("Made form '%(id_string)s' %(downloadable)s.") % { 'id_string': xform.id_string, 'downloadable': _("downloadable") if xform.downloadable else _("un-downloadable") }, audit, request) return HttpResponseRedirect("/%s" % username)
def download_xform(request, username, id_string): user = get_object_or_404(User, username__iexact=username) xform = get_object_or_404(XForm, user=user, id_string__exact=id_string) profile, created =\ UserProfile.objects.get_or_create(user=user) if profile.require_auth: authenticator = HttpDigestAuthenticator() if not authenticator.authenticate(request): return authenticator.build_challenge_response() audit = {"xform": xform.id_string} audit_log( Actions.FORM_XML_DOWNLOADED, request.user, xform.user, _("Downloaded XML for form '%(id_string)s'.") % {"id_string": xform.id_string}, audit, request) response = response_with_mimetype_and_name('xml', id_string, show_date=False) response.content = xform.xml return response
def formList(request, username): """ This is where ODK Collect gets its download list. """ print '####' formlist_user = get_object_or_404(User, username=username) content_user = get_object_or_404(User, username=username) profile, created = UserProfile.objects.get_or_create(user=formlist_user) if profile.require_auth: authenticator = HttpDigestAuthenticator() if not authenticator.authenticate(request): return authenticator.build_challenge_response() # unauthorized if user in auth request does not match user in path # unauthorized if user not active if not request.user.is_active: return HttpResponseNotAuthorized() #xforms = XForm.objects.filter(downloadable=True, user__username=username) # forms shared with user xfct = ContentType.objects.get(app_label='logger', model='xform') xfs = content_user.userobjectpermission_set.filter(content_type=xfct) shared_forms_pks = list(set([xf.object_pk for xf in xfs])) xforms = XForm.objects.filter( pk__in=shared_forms_pks).select_related('user') audit = {} audit_log(Actions.USER_FORMLIST_REQUESTED, request.user, formlist_user, _("Requested forms list."), audit, request) response = render_to_response("xformsList.xml", { 'host': request.build_absolute_uri().replace( request.get_full_path(), ''), 'xforms': xforms }, mimetype="text/xml; charset=utf-8") response['X-OpenRosa-Version'] = '1.0' tz = pytz.timezone(settings.TIME_ZONE) dt = datetime.now(tz).strftime('%a, %d %b %Y %H:%M:%S %Z') response['Date'] = dt return response
def set_form(): form_owner = request.POST.get('username') id_string = request.POST.get('id_string') xform = XForm.objects.get(user__username=form_owner, id_string=id_string) if len(id_string) > 0 and id_string[0].isdigit(): id_string = '_' + id_string path = xform.xls.name if default_storage.exists(path): xls_file = upload_to(None, '%s%s.xls' % ( id_string, XForm.CLONED_SUFFIX), to_username) xls_data = default_storage.open(path) xls_file = default_storage.save(xls_file, xls_data) context.message = u'%s-%s' % (form_owner, xls_file) survey = DataDictionary.objects.create( user=request.user, xls=xls_file ).survey # log to cloner's account audit = {} audit_log( Actions.FORM_CLONED, request.user, request.user, _("Cloned form '%(id_string)s'.") % { 'id_string': survey.id_string, }, audit, request) clone_form_url = reverse( show, kwargs={ 'username': to_username, 'id_string': xform.id_string + XForm.CLONED_SUFFIX}) return { 'type': 'alert-success', 'text': _(u'Successfully cloned to %(form_url)s into your ' u'%(profile_url)s') % {'form_url': u'<a href="%(url)s">%(id_string)s</a> ' % { 'id_string': survey.id_string, 'url': clone_form_url }, 'profile_url': u'<a href="%s">profile</a>.' % reverse(profile, kwargs={'username': to_username})} }
def delete_export(request, username, id_string, export_type, is_project=None, id=None, site_id=None, version="0"): owner = get_object_or_404(User, username__iexact=username) xform = get_object_or_404(XForm, id_string__exact=id_string, user=owner) if not has_forms_permission(xform, owner, request): return HttpResponseForbidden(_(u'Not shared.')) export_id = request.POST.get('export_id') # find the export entry in the db export = get_object_or_404(Export, id=export_id) export.delete() audit = {"xform": xform.id_string, "export_type": export.export_type} audit_log( Actions.EXPORT_DOWNLOADED, request.user, owner, _("Deleted %(export_type)s export '%(filename)s'" " on '%(id_string)s'.") % { 'export_type': export.export_type.upper(), 'filename': export.filename, 'id_string': xform.id_string, }, audit, request) kwargs = { "username": username, "id_string": id_string, "export_type": export_type, "is_project": is_project, "id": id, "version": version } if site_id is not None: kwargs['site_id'] = site_id return HttpResponseRedirect(reverse(export_list, kwargs=kwargs))
def delete_export(request, username, id_string, export_type): owner = get_object_or_404(User, username__iexact=username) xform = get_object_or_404(XForm, id_string__exact=id_string, user=owner) if not has_permission(xform, owner, request): return HttpResponseForbidden(_(u'Not shared.')) export_id = request.POST.get('export_id') # find the export entry in the db export = get_object_or_404(Export, id=export_id) export.delete() audit = {"xform": xform.id_string, "export_type": export.export_type} audit_log( Actions.EXPORT_DOWNLOADED, request.user, owner, _("Deleted %(export_type)s export '%(filename)s'" " on '%(id_string)s'.") % { 'export_type': export.export_type.upper(), 'filename': export.filename, 'id_string': xform.id_string, }, audit, request) # mpower start: added for redirection to custom view custom = request.POST.get("custom", "default") if custom != 'default': return HttpResponseRedirect('/usermodule/' + owner.username + '/projects-views/' + xform.id_string + '/?tab_selection=' + custom) # mpower end: added for redirection to custom view return HttpResponseRedirect( reverse(export_list, kwargs={ "username": username, "id_string": id_string, "export_type": export_type }))