Esempio n. 1
0
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")
Esempio n. 2
0
 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}),
             },
         }
Esempio n. 3
0
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
Esempio n. 4
0
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
Esempio n. 5
0
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')
Esempio n. 6
0
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)
Esempio n. 7
0
 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
     }
Esempio n. 8
0
 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}
     }
Esempio n. 9
0
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)
Esempio n. 10
0
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
Esempio n. 11
0
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.'))
Esempio n. 12
0
 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,
     }
Esempio n. 13
0
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
    })
Esempio n. 14
0
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
Esempio n. 15
0
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
        }))
Esempio n. 16
0
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
Esempio n. 17
0
    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
Esempio n. 18
0
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.'))
Esempio n. 19
0
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
Esempio n. 20
0
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)}
Esempio n. 21
0
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
            })
        )
Esempio n. 22
0
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)
Esempio n. 23
0
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)
Esempio n. 24
0
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)
Esempio n. 25
0
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)
Esempio n. 26
0
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
Esempio n. 27
0
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)
Esempio n. 28
0
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)
Esempio n. 29
0
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
Esempio n. 30
0
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('/')