Example #1
0
def clone_xlsform(request, username):
    """
    Copy a public/Shared form to a users list of forms.
    Eliminates the need to download Excel File and upload again.
    """
    to_username = request.user.username
    context = RequestContext(request)
    context.message = {"type": None, "text": "...."}

    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
            return {
                "type": "alert-success",
                "text": "Successfully cloned %s into your "
                '<a href="%s">profile</a>.' % (survey.id_string, reverse(profile, kwargs={"username": to_username})),
            }

    context.message = publish_form(set_form)
    if request.is_ajax():
        res = loader.render_to_string("message.html", context_instance=context).replace("'", r"\'").replace("\n", "")
        return HttpResponse("$('#mfeedback').html('%s').show();" % res)
    else:
        return HttpResponse(context.message["text"])
Example #2
0
def clone_xlsform(request, username):
    """
    Copy a public/Shared form to a users list of forms.
    Eliminates the need to download Excel File and upload again.
    """
    to_username = request.user.username
    context = RequestContext(request)
    context.message = {'type': None, 'text': '....'}

    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)
            return {
                'type': 'alert-success',
                'text': _(u'Successfully cloned %(id_string)s into your '
                          u'%(profile_url)s') % {
                              'id_string': survey.id_string,
                              'profile_url': u'<a href="%s">profile</a>.' %
                              reverse(profile,
                                      kwargs={'username': to_username})
                          }
            }
    context.message = publish_form(set_form)
    if request.is_ajax():
        res = loader.render_to_string(
            'message.html',
            context_instance=context).replace("'", r"\'").replace('\n', '')
        return HttpResponse(
            "$('#mfeedback').html('%s').show();" % res)
    else:
        return HttpResponse(context.message['text'])
Example #3
0
def clone_xlsform(request, username):
    """
    Copy a public/Shared form to a users list of forms.
    Eliminates the need to download Excel File and upload again.
    """
    to_username = request.user.username
    context = RequestContext(request)
    context.message = {'type': None, 'text': '....'}

    try:
        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, id_string + '_cloned.xls', 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
            context.message = {
                'type': 'success',
                'text': 'Successfully cloned %s into your '\
                        '<a href="%s">profile</a>.' % \
                        (survey.id_string, reverse(profile,
                            kwargs={'username': to_username}))
                }
    except (PyXFormError, XLSFormError) as e:
        context.message = {
            'type': 'error',
            'text': unicode(e),
            }
    except IntegrityError as e:
        context.message = {
            'type': 'error',
            'text': 'Form with this id already exists.',
            }
    if request.is_ajax():
        return HttpResponse(simplejson.dumps(context.message), \
                        mimetype='application/json')
    else:
        return HttpResponse(context.message['text'])
Example #4
0
def profile(request, username):
    context = RequestContext(request)
    content_user = None
    context.num_surveys = Instance.objects.count()
    context.form = QuickConverter()

    # xlsform submission...
    if request.method == 'POST' and request.user.is_authenticated():
        def set_form():
            form = QuickConverter(request.POST, request.FILES)
            survey = form.publish(request.user).survey
            return {
                'type': 'alert-success',
                'text': 'Successfully published %s.' % survey.id_string,
                }
        context.message = publish_form(set_form)

    # profile view...
    content_user = get_object_or_404(User, username=username)
    # for the same user -> dashboard
    if content_user == request.user:
        context.show_dashboard = True
        context.user_surveys = content_user.surveys.count()
        context.all_forms = content_user.xforms.count()
        context.form = QuickConverterFile()
        context.form_url = QuickConverterURL()
        context.odk_url = request.build_absolute_uri("/%s" % request.user.username)
    # for any other user -> profile
    profile, created = UserProfile.objects.get_or_create(user=content_user)
    set_profile_data(context, content_user)
    return render_to_response("profile.html", context_instance=context)
Example #5
0
def profile(request, username):
    context = RequestContext(request)
    content_user = None
    context.num_surveys = Instance.objects.count()
    context.form = QuickConverter()

    # xlsform submission...
    if request.method == "POST" and request.user.is_authenticated():

        def set_form():
            form = QuickConverter(request.POST, request.FILES)
            survey = form.publish(request.user).survey
            return {"type": "alert-success", "text": "Successfully published %s." % survey.id_string}

        context.message = publish_form(set_form)

    # profile view...
    content_user = get_object_or_404(User, username=username)
    # for the same user -> dashboard
    if content_user == request.user:
        context.show_dashboard = True
        context.user_surveys = content_user.surveys.count()
        context.all_forms = content_user.xforms.count()
        context.form = QuickConverterFile()
        context.form_url = QuickConverterURL()
        context.odk_url = request.build_absolute_uri("/%s" % request.user.username)
    # for any other user -> profile
    profile, created = UserProfile.objects.get_or_create(user=content_user)
    set_profile_data(context, content_user)
    return render_to_response("profile.html", context_instance=context)
Example #6
0
def enter_data(request, username, id_string):
    owner = get_object_or_404(User, username=username)
    xform = get_object_or_404(XForm, user__username=username,
                              id_string=id_string)
    if not has_edit_permission(xform, owner, request, xform.shared):
        return HttpResponseForbidden(_(u'Not shared.'))
    try:
        formhub_url = "http://%s/" % request.META['HTTP_HOST']
    except:
        formhub_url = "http://formhub.org/"
    form_url = formhub_url + username
    if settings.TESTING_MODE:
        form_url = "https://testserver.com/bob"
    try:
        url = enketo_url(form_url, xform.id_string)
        if not url:
            return HttpResponseRedirect(reverse('main.views.show',
                                        kwargs={'username': username,
                                                'id_string': id_string}))
        return HttpResponseRedirect(url)
    except Exception, e:
        context = RequestContext(request)
        owner = User.objects.get(username=username)
        context.profile, created = \
            UserProfile.objects.get_or_create(user=owner)
        context.xform = xform
        context.content_user = owner
        context.form_view = True
        context.message = {
            'type': 'alert-error',
            'text': u"Enketo error, reason: %s" % e}
        messages.add_message(
            request, messages.WARNING,
            _("Enketo error: enketo replied %s") % e, fail_silently=True)
        return render_to_response("profile.html", context_instance=context)
Example #7
0
def kml_export(request, username, id_string):
    # read the locations from the database
    context = RequestContext(request)
    context.message = "HELLO!!"
    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.'))
    context.data = kml_export_data(id_string, user=owner)
    response = \
        render_to_response("survey.kml", context_instance=context,
                           mimetype="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
Example #8
0
def enter_data(request, username, id_string):
    owner = get_object_or_404(User, username=username)
    xform = get_object_or_404(XForm, user__username=username,
                              id_string=id_string)
    if not has_edit_permission(xform, owner, request, xform.shared):
        return HttpResponseForbidden(_(u'Not shared.'))

    form_url = _get_form_url(request, username, settings.ENKETO_PROTOCOL)

    try:
        url = enketo_url(form_url, xform.id_string)
        if not url:
            return HttpResponseRedirect(reverse('onadata.apps.main.views.show',
                                        kwargs={'username': username,
                                                'id_string': id_string}))
        return HttpResponseRedirect(url)
    except Exception as e:
        context = RequestContext(request)
        owner = User.objects.get(username=username)
        context.profile, created = \
            UserProfile.objects.get_or_create(user=owner)
        context.xform = xform
        context.content_user = owner
        context.form_view = True
        context.message = {
            'type': 'alert-error',
            'text': u"Enketo error, reason: %s" % e}
        messages.add_message(
            request, messages.WARNING,
            _("Enketo error: enketo replied %s") % e, fail_silently=True)
        return render_to_response("profile.html", context_instance=context)
    return HttpResponseRedirect(reverse('onadata.apps.main.views.show',
                                kwargs={'username': username,
                                        'id_string': id_string}))
Example #9
0
def enter_data(request, username, id_string):
    owner = get_object_or_404(User, username=username)
    xform = get_object_or_404(XForm, user__username=username,
                              id_string=id_string)
    if not has_edit_permission(xform, owner, request, xform.shared):
        return HttpResponseForbidden(_(u'Not shared.'))

    form_url = _get_form_url(request, username)

    try:
        url = enketo_url(form_url, xform.id_string)
        if not url:
            return HttpResponseRedirect(reverse('onadata.apps.main.views.show',
                                        kwargs={'username': username,
                                                'id_string': id_string}))
        return HttpResponseRedirect(url)
    except Exception, e:
        context = RequestContext(request)
        owner = User.objects.get(username=username)
        context.profile, created = \
            UserProfile.objects.get_or_create(user=owner)
        context.xform = xform
        context.content_user = owner
        context.form_view = True
        context.message = {
            'type': 'alert-error',
            'text': u"Enketo error, reason: %s" % e}
        messages.add_message(
            request, messages.WARNING,
            _("Enketo error: enketo replied %s") % e, fail_silently=True)
        return render_to_response("profile.html", context_instance=context)
Example #10
0
def kml_export(request, username, id_string):
    # read the locations from the database
    context = RequestContext(request)
    context.message = "HELLO!!"
    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.'))
    context.data = kml_export_data(id_string, user=owner)
    response = \
        render_to_response("survey.kml", context_instance=context,
                           mimetype="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
Example #11
0
def edit_data(request, username, id_string, data_id):
    """
    Redirects to Enketo webform to edit a submission with the data_id.
    """
    context = RequestContext(request)
    owner = User.objects.get(username__iexact=username)
    xform_kwargs = {
        'id_string__iexact': id_string,
        'user__username__iexact': username
    }

    xform = get_form(xform_kwargs)
    instance = get_object_or_404(Instance, pk=data_id, xform=xform)
    if not has_edit_permission(xform, owner, request, xform.shared):
        return HttpResponseForbidden(_(u'Not shared.'))
    if not hasattr(settings, 'ENKETO_URL'):
        return HttpResponseRedirect(
            reverse('form-show',
                    kwargs={
                        'username': username,
                        'id_string': id_string
                    }))

    url = '%sdata/edit_url' % settings.ENKETO_URL
    # see commit 220f2dad0e for tmp file creation
    injected_xml = inject_instanceid(instance.xml, instance.uuid)
    return_url = request.build_absolute_uri(
        reverse('submission-instance',
                kwargs={
                    'username': username,
                    'id_string': id_string
                }) + "#/" + text(instance.id))
    form_url = get_form_url(request, username, settings.ENKETO_PROTOCOL)

    try:
        url = get_enketo_urls(form_url,
                              xform.id_string,
                              instance_xml=injected_xml,
                              instance_id=instance.uuid,
                              return_url=return_url)
    except EnketoError as e:
        context.message = {
            'type': 'alert-error',
            'text': u"Enketo error, reason: %s" % e
        }
        messages.add_message(request,
                             messages.WARNING,
                             _("Enketo error: enketo replied %s") % e,
                             fail_silently=True)
    else:
        if url:
            url = url['edit_url']
            context.enketo = url
            return HttpResponseRedirect(url)
    return HttpResponseRedirect(
        reverse('form-show',
                kwargs={
                    'username': username,
                    'id_string': id_string
                }))
Example #12
0
def edit_data(request, username, id_string, data_id):
    """
    Redirects to Enketo webform to edit a submission with the data_id.
    """
    context = RequestContext(request)
    owner = User.objects.get(username__iexact=username)
    xform_kwargs = {
        'id_string__iexact': id_string,
        'user__username__iexact': username
    }

    xform = get_form(xform_kwargs)
    instance = get_object_or_404(Instance, pk=data_id, xform=xform)
    if not has_edit_permission(xform, owner, request, xform.shared):
        return HttpResponseForbidden(_(u'Not shared.'))
    if not hasattr(settings, 'ENKETO_URL'):
        return HttpResponseRedirect(
            reverse(
                'form-show',
                kwargs={'username': username,
                        'id_string': id_string}))

    url = '%sdata/edit_url' % settings.ENKETO_URL
    # see commit 220f2dad0e for tmp file creation
    injected_xml = inject_instanceid(instance.xml, instance.uuid)
    return_url = request.build_absolute_uri(
        reverse(
            'submission-instance',
            kwargs={'username': username,
                    'id_string': id_string}) + "#/" + text(instance.id))
    form_url = get_form_url(request, username, settings.ENKETO_PROTOCOL)

    try:
        url = enketo_url(
            form_url,
            xform.id_string,
            instance_xml=injected_xml,
            instance_id=instance.uuid,
            return_url=return_url)
    except EnketoError as e:
        context.message = {
            'type': 'alert-error',
            'text': u"Enketo error, reason: %s" % e
        }
        messages.add_message(
            request,
            messages.WARNING,
            _("Enketo error: enketo replied %s") % e,
            fail_silently=True)
    else:
        if url:
            context.enketo = url
            return HttpResponseRedirect(url)
    return HttpResponseRedirect(
        reverse(
            'form-show', kwargs={'username': username,
                                 'id_string': id_string}))
Example #13
0
def edit_data(request, username, id_string, data_id):

    context = RequestContext(request)
    owner = User.objects.get(username__iexact=username)
    xform = get_object_or_404(XForm,
                              user__username__iexact=username,
                              id_string__exact=id_string)
    instance = get_object_or_404(Instance, pk=data_id, xform=xform)
    #if not has_edit_permission(xform, owner, request, xform.shared):
    if not check_form_permissions(xform, str(request.user), 'can_edit'):
        return HttpResponseForbidden(_(u'Not shared.'))
    if not hasattr(settings, 'ENKETO_URL'):
        return HttpResponseRedirect(
            reverse('onadata.apps.main.views.show',
                    kwargs={
                        'username': username,
                        'id_string': id_string
                    }))

    url = '%sdata/edit_url' % settings.ENKETO_URL

    # see commit 220f2dad0e for tmp file creation
    injected_xml = inject_instanceid(instance.xml, instance.uuid)
    return_url = request.build_absolute_uri(
        reverse('onadata.apps.viewer.views.instance',
                kwargs={
                    'username': username,
                    'id_string': id_string
                }) + "#/" + str(instance.id))
    form_url = _get_form_url(request, username, settings.ENKETO_PROTOCOL)

    try:
        url = enketo_url(form_url,
                         xform.id_string,
                         instance_xml=injected_xml,
                         instance_id=instance.uuid,
                         return_url=return_url)
    except Exception as e:
        context.message = {
            'type': 'alert-error',
            'text': u"Enketo error, reason: %s" % e
        }
        messages.add_message(request,
                             messages.WARNING,
                             _("Enketo error: enketo replied %s") % e,
                             fail_silently=True)
    else:
        if url:
            context.enketo = url
            return HttpResponseRedirect(url)
    return HttpResponseRedirect(
        reverse('onadata.apps.main.views.show',
                kwargs={
                    'username': username,
                    'id_string': id_string
                }))
Example #14
0
def profile(request, username):
    context = RequestContext(request)
    content_user = get_object_or_404(User, username=username)
    context.form = QuickConverter()
    # xlsform submission...
    if request.method == 'POST' and request.user.is_authenticated():
        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',
                'text': _(u'Successfully published %(form_id)s.'
                          u' <a href="%(form_url)s">Enter Web Form</a>')
                        % {'form_id': survey.id_string,
                            'form_url': enketo_webform_url}
            }
        context.message = publish_form(set_form)

    # profile view...
    # for the same user -> dashboard
    if content_user == request.user:
        context.show_dashboard = True
        context.user_surveys = content_user.surveys.count()
        context.all_forms = content_user.xforms.count()
        context.form = QuickConverterFile()
        context.form_url = QuickConverterURL()
        context.odk_url = request.build_absolute_uri(
            "/%s" % request.user.username)
        crowdforms = XForm.objects.filter(
            metadata__data_type=MetaData.CROWDFORM_USERS,
            metadata__data_value=username
        )
        context.crowdforms = crowdforms
        # forms shared with user
        xfct = ContentType.objects.get(app_label='odk_logger', model='xform')
        fsw = {}
        for xf in content_user.userobjectpermission_set\
                .filter(content_type=xfct):
            if isinstance(xf.content_object, XForm):
                fsw[xf.content_object.pk] = xf.content_object
        context.forms_shared_with = list(fsw.values())
    # for any other user -> profile
    set_profile_data(context, content_user)
    return render_to_response("profile.html", context_instance=context)
Example #15
0
def clone_xlsform(request, username):
    '''
    Copy a public/Shared form to a users list of forms.
    Eliminates the need to download Excel File and upload again.
    '''
    to_username = request.user.username
    context = RequestContext(request)
    context.message = {'type': None, 'text': '....'}

    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
            return {
                'type': 'alert-success',
                'text': 'Successfully cloned %s into your '\
                        '<a href="%s">profile</a>.' % \
                        (survey.id_string, reverse(profile,
                            kwargs={'username': to_username}))
                }
    context.message = publish_form(set_form)
    if request.is_ajax():
        res = loader.render_to_string('message.html',
                context_instance=context).replace("'", r"\'").replace('\n', '')
        return HttpResponse(
                "$('#mfeedback').html('%s').show();" % res)
    else:
        return HttpResponse(context.message['text'])
Example #16
0
def dashboard(request):
    context = RequestContext(request)
    context.form = QuickConverter()
    context.odk_url = request.build_absolute_uri("/%s" % request.user.username)

    if request.method == 'POST':
        try:
            form = QuickConverter(request.POST, request.FILES)
            survey = form.get_survey()
            publish(request.user, survey)
            context.message = {
                'type': 'success',
                'text': 'Successfully published %s.' % survey.id_string,
                }
        except PyXFormError as e:
            context.message = {
                'type': 'error',
                'text': unicode(e),
                }
    return render_to_response("dashboard.html", context_instance=context)
Example #17
0
def kml_export(request, username, id_string):
    # read the locations from the database
    context = RequestContext(request)
    context.message = "HELLO!!"
    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."))
    dd = DataDictionary.objects.get(id_string=id_string, user=owner)
    pis = ParsedInstance.objects.filter(
        instance__user=owner, instance__xform__id_string=id_string, lat__isnull=False, lng__isnull=False
    )
    data_for_template = []

    labels = {}

    def cached_get_labels(xpath):
        if xpath in labels.keys():
            return labels[xpath]
        labels[xpath] = dd.get_label(xpath)
        return labels[xpath]

    for pi in pis:
        # read the survey instances
        data_for_display = pi.to_dict()
        xpaths = data_for_display.keys()
        xpaths.sort(cmp=pi.data_dictionary.get_xpath_cmp())
        label_value_pairs = [
            (cached_get_labels(xpath), data_for_display[xpath]) for xpath in xpaths if not xpath.startswith(u"_")
        ]
        table_rows = []
        for key, value in label_value_pairs:
            table_rows.append("<tr><td>%s</td><td>%s</td></tr>" % (key, value))
        img_urls = image_urls(pi.instance)
        img_url = img_urls[0] if img_urls else ""
        data_for_template.append(
            {
                "name": id_string,
                "id": pi.id,
                "lat": pi.lat,
                "lng": pi.lng,
                "image_urls": img_urls,
                "table": '<table border="1"><a href="#"><img width="210" '
                'class="thumbnail" src="%s" alt=""></a>%s'
                "</table>" % (img_url, "".join(table_rows)),
            }
        )
    context.data = data_for_template
    response = render_to_response(
        "survey.kml", context_instance=context, mimetype="application/vnd.google-earth.kml+xml"
    )
    response["Content-Disposition"] = disposition_ext_and_date(id_string, "kml")
    return response
Example #18
0
def profile(request, username):
    context = RequestContext(request)
    content_user = None
    context.num_surveys = Instance.objects.count()
    context.form = QuickConverter()

    # xlsform submission...
    if request.method == 'POST' and request.user.is_authenticated():
        try:
            form = QuickConverter(request.POST, request.FILES)
            survey = form.publish(request.user).survey
            context.message = {
                'type': 'success',
                'text': 'Successfully published %s.' % survey.id_string,
                }
        except (PyXFormError, XLSFormError) as e:
            context.message = {
                'type': 'error',
                'text': unicode(e),
                }
        except IntegrityError as e:
            context.message = {
                'type': 'error',
                'text': 'Form with this id already exists.',
                }

    # profile view...
    content_user = get_object_or_404(User, username=username)
    # for the same user -> dashboard
    if content_user == request.user:
        context.show_dashboard = True
        context.user_surveys = content_user.surveys.count()
        context.all_forms = content_user.xforms.count()
        context.form = QuickConverterFile()
        context.form_url = QuickConverterURL()
        context.odk_url = request.build_absolute_uri("/%s" % request.user.username)
    # for any other user -> profile
    profile, created = UserProfile.objects.get_or_create(user=content_user)
    set_profile_data(context, content_user)
    return render_to_response("profile.html", context_instance=context)
Example #19
0
def edit_data(request, username, id_string, data_id):
    context = RequestContext(request)
    owner = User.objects.get(username=username)
    xform = get_object_or_404(
        XForm, user__username=username, id_string=id_string)
    instance = get_object_or_404(
        Instance, pk=data_id, xform=xform)
    if not has_edit_permission(xform, owner, request, xform.shared):
        return HttpResponseForbidden(_(u'Not shared.'))
    if not hasattr(settings, 'ENKETO_URL'):
        return HttpResponseRedirect(
            reverse(
                'main.views.show', kwargs={'username': username,
                                           'id_string': id_string}
            )
        )

    url = '%sdata/edit_url' % settings.ENKETO_URL
    # see commit 220f2dad0e for tmp file creation
    try:
        formhub_url = "http://%s/" % request.META['HTTP_HOST']
    except:
        formhub_url = "http://formhub.org/"
    injected_xml = inject_instanceid(instance.xml, instance.uuid)
    return_url = request.build_absolute_uri(
        reverse(
            'odk_viewer.views.instance',
            kwargs={
                'username': username,
                'id_string': id_string}
        ) + "#/" + str(instance.id))
    form_url = formhub_url + username
    
    if hasattr(settings, "TESTING_MODE") and settings.TESTING_MODE:
        form_url = "https://testserver.com/bob"

    try:
        url = enketo_url(
            form_url, xform.id_string, instance_xml=injected_xml,
            instance_id=instance.uuid, return_url=return_url
        )
    except Exception, e:
        context.message = {
            'type': 'alert-error',
            'text': u"Enketo error, reason: %s" % e}
        messages.add_message(
            request, messages.WARNING,
            _("Enketo error: enketo replied %s") % e, fail_silently=True)
Example #20
0
def edit_data(request, username, id_string, data_id):
    context = RequestContext(request)
    owner = User.objects.get(username=username)
    xform = get_object_or_404(XForm,
                              user__username=username,
                              id_string=id_string)
    instance = get_object_or_404(Instance, pk=data_id, xform=xform)
    if not has_edit_permission(xform, owner, request, xform.shared):
        return HttpResponseForbidden(_(u'Not shared.'))
    if not hasattr(settings, 'ENKETO_URL'):
        return HttpResponseRedirect(
            reverse('main.views.show',
                    kwargs={
                        'username': username,
                        'id_string': id_string
                    }))

    url = '%sdata/edit_url' % settings.ENKETO_URL
    # see commit 220f2dad0e for tmp file creation
    try:
        formhub_url = "http://%s/" % request.META['HTTP_HOST']
    except:
        formhub_url = "http://formhub.org/"
    injected_xml = inject_instanceid(instance.xml, instance.uuid)
    return_url = request.build_absolute_uri(
        reverse('odk_viewer.views.instance',
                kwargs={
                    'username': username,
                    'id_string': id_string
                }) + "#/" + str(instance.id))
    form_url = formhub_url + username
    if settings.TESTING_MODE:
        form_url = "https://testserver.com/bob"
    try:
        url = enketo_url(form_url,
                         xform.id_string,
                         instance_xml=injected_xml,
                         instance_id=instance.uuid,
                         return_url=return_url)
    except Exception, e:
        context.message = {
            'type': 'alert-error',
            'text': u"Enketo error, reason: %s" % e
        }
        messages.add_message(request,
                             messages.WARNING,
                             _("Enketo error: enketo replied %s") % e,
                             fail_silently=True)
Example #21
0
def kml_export(request, username, id_string):
    # read the locations from the database
    context = RequestContext(request)
    context.message="HELLO!!"
    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('Not shared.')
    dd = DataDictionary.objects.get(id_string=id_string,
                                    user=owner)
    pis = ParsedInstance.objects.filter(instance__user=owner,
            instance__xform__id_string=id_string, lat__isnull=False,
            lng__isnull=False)
    data_for_template = []

    labels = {}
    def cached_get_labels(xpath):
        if xpath in labels.keys(): return labels[xpath]
        labels[xpath] = dd.get_label(xpath)
        return labels[xpath]
    for pi in pis:
        # read the survey instances
        data_for_display = pi.to_dict()
        xpaths = data_for_display.keys()
        xpaths.sort(cmp=pi.data_dictionary.get_xpath_cmp())
        label_value_pairs = [
            (cached_get_labels(xpath),
            data_for_display[xpath]) for xpath in xpaths 
                                     if not xpath.startswith(u"_")]
        table_rows = []
        for key, value in label_value_pairs:
            table_rows.append('<tr><td>%s</td><td>%s</td></tr>' % (key, value))
        img_urls = image_urls(pi.instance)
        img_url = img_urls[0] if img_urls else ""
        data_for_template.append({
                'name':id_string,
                'id': pi.id,
                'lat': pi.lat,
                'lng': pi.lng,
                'image_urls': img_urls,
                'table': '<table border="1"><a href="#"><img width="210" class="thumbnail" src="%s" alt=""></a>%s</table>' % (img_url,''.join(table_rows))})
    context.data = data_for_template
    response = render_to_response("survey.kml",
        context_instance=context,
        mimetype="application/vnd.google-earth.kml+xml")
    response['Content-Disposition'] = disposition_ext_and_date(id_string, 'kml')
    return response
Example #22
0
def enter_data(request, username, id_string, test_server=None):
    owner = get_object_or_404(User, username=username)
    xform = get_object_or_404(XForm, user__username=username,
                              id_string=id_string)
    if not has_edit_permission(xform, owner, request, xform.shared):
        return HttpResponseForbidden(_(u'Not shared.'))
    
    if test_server:
        form_url = test_server
    else:
        try:
            formhub_url = "http://%s/" % request.META['HTTP_HOST']
        except:
            formhub_url = "http://formhub.org/"
        form_url = formhub_url + username   
        
        if hasattr(settings, "TESTING_MODE") and settings.TESTING_MODE:
            form_url = "https://testserver.com/bob"
    try:
        url = enketo_url(form_url, xform.id_string)
        if not url:
            return HttpResponseRedirect(reverse('main.views.show',
                                        kwargs={'username': username,
                                                'id_string': id_string}))
        return HttpResponseRedirect(url)
    except Exception, e:
        context = RequestContext(request)
        owner = User.objects.get(username=username)
        context.profile, created = \
            UserProfile.objects.get_or_create(user=owner)
        context.xform = xform
        context.content_user = owner
        context.form_view = True
        context.message = {
            'type': 'alert-error',
            'text': u"Enketo error, reason: %s" % e}
        messages.add_message(
            request, messages.WARNING,
            _("Enketo error: enketo replied %s") % e, fail_silently=True)
        return render_to_response("profile.html", context_instance=context)
Example #23
0
def kml_export(request, username, id_string):
    # read the locations from the database
    context = RequestContext(request)
    context.message="HELLO!!"
    owner = User.objects.get(username=username)
    xform = XForm.objects.get(id_string=id_string, user=owner)
    if not has_permission(xform, owner, request):
        return HttpResponseForbidden('Not shared.')
    dd = DataDictionary.objects.get(id_string=id_string,
                                    user=owner)
    pis = ParsedInstance.objects.filter(instance__user=owner, instance__xform__id_string=id_string, lat__isnull=False, lng__isnull=False)
    data_for_template = []
    for pi in pis:
        # read the survey instances
        data = pi.to_dict()
        # get rid of keys with leading underscores
        data_for_display = {}
        for k, v in data.items():
            if not k.startswith(u"_"):
                data_for_display[k] = v
        xpaths = data_for_display.keys()
        xpaths.sort(cmp=pi.data_dictionary.get_xpath_cmp())
        label_value_pairs = [
            (pi.data_dictionary.get_label(xpath),
            data_for_display[xpath]) for xpath in xpaths]
        table_rows = []
        for key, value in label_value_pairs:
            table_rows.append('<tr><td>%s</td><td>%s</td></tr>' % (key, value))
        img_urls = image_urls(pi.instance)
        img_url = img_urls[0] if img_urls else ""
        data_for_template.append({"name":id_string, "id": pi.id, "lat": pi.lat, "lng": pi.lng,'image_urls': img_urls, "table": '<table border="1"><a href="#"><img width="210" class="thumbnail" src="%s" alt=""></a><%s</table>' % (img_url,''.join(table_rows))})
    context.data = data_for_template
    response = render_to_response("survey.kml",
        context_instance=context,
        mimetype="application/vnd.google-earth.kml+xml")
    response['Content-Disposition'] = disposition_ext_and_date(id_string, 'kml')
    return response
Example #24
0
def edit_data(request, username, id_string, data_id):
    context = RequestContext(request)
    owner = User.objects.get(username__iexact=username)
    xform = get_object_or_404(XForm, user__username__iexact=username, id_string__exact=id_string)
    instance = get_object_or_404(Instance, pk=data_id, xform=xform)
    if not has_edit_permission(xform, owner, request, xform.shared):
        return HttpResponseForbidden(_(u"Not shared."))
    if not hasattr(settings, "ENKETO_URL"):
        return HttpResponseRedirect(
            reverse("onadata.apps.main.views.show", kwargs={"username": username, "id_string": id_string})
        )

    url = "%sdata/edit_url" % settings.ENKETO_URL
    # see commit 220f2dad0e for tmp file creation
    injected_xml = inject_instanceid(instance.xml, instance.uuid)
    return_url = request.build_absolute_uri(
        reverse("onadata.apps.viewer.views.instance", kwargs={"username": username, "id_string": id_string})
        + "#/"
        + str(instance.id)
    )
    form_url = _get_form_url(request, username, settings.ENKETO_PROTOCOL)

    try:
        url = enketo_url(
            form_url, xform.id_string, instance_xml=injected_xml, instance_id=instance.uuid, return_url=return_url
        )
    except Exception as e:
        context.message = {"type": "alert-error", "text": u"Enketo error, reason: %s" % e}
        messages.add_message(request, messages.WARNING, _("Enketo error: enketo replied %s") % e, fail_silently=True)
    else:
        if url:
            context.enketo = url
            return HttpResponseRedirect(url)
    return HttpResponseRedirect(
        reverse("onadata.apps.main.views.show", kwargs={"username": username, "id_string": id_string})
    )
Example #25
0
def kml_export(request, username, id_string):
    # read the locations from the database
    context = RequestContext(request)
    context.message = "HELLO!!"
    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.'))
    dd = DataDictionary.objects.get(id_string=id_string,
                                    user=owner)
    pis = ParsedInstance.objects.filter(instance__user=owner,
                                        instance__xform__id_string=id_string,
                                        lat__isnull=False, lng__isnull=False)
    data_for_template = []

    labels = {}

    def cached_get_labels(xpath):
        if xpath in labels.keys():
            return labels[xpath]
        labels[xpath] = dd.get_label(xpath)
        return labels[xpath]

    for pi in pis:
        # read the survey instances
        data_for_display = pi.to_dict()
        xpaths = data_for_display.keys()
        xpaths.sort(cmp=pi.data_dictionary.get_xpath_cmp())
        label_value_pairs = [
            (cached_get_labels(xpath),
             data_for_display[xpath]) for xpath in xpaths
            if not xpath.startswith(u"_")]
        table_rows = []
        for key, value in label_value_pairs:
            table_rows.append('<tr><td>%s</td><td>%s</td></tr>' % (key, value))
        img_urls = image_urls(pi.instance)
        img_url = img_urls[0] if img_urls else ""
        data_for_template.append({
            'name': id_string,
            'id': pi.id,
            'lat': pi.lat,
            'lng': pi.lng,
            'image_urls': img_urls,
            'table': '<table border="1"><a href="#"><img width="210" '
                     'class="thumbnail" src="%s" alt=""></a>%s'
                     '</table>' % (img_url, ''.join(table_rows))})
    context.data = data_for_template
    response = \
        render_to_response("survey.kml", context_instance=context,
                           mimetype="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
Example #26
0
def edit_data(request, username, id_string, data_id):
    owner = User.objects.get(username=username)
    xform = get_object_or_404(XForm,
                              user__username=username,
                              id_string=id_string)
    instance = get_object_or_404(Instance, pk=data_id, xform=xform)
    if not has_edit_permission(xform, owner, request, xform.shared):
        return HttpResponseForbidden(_(u'Not shared.'))
    if not hasattr(settings, 'ENKETO_URL'):
        return HttpResponseRedirect(
            reverse('main.views.show',
                    kwargs={
                        'username': username,
                        'id_string': id_string
                    }))

    url = '%sdata/edit_url' % settings.ENKETO_URL
    register_openers()
    response = None
    # see commit 220f2dad0e for tmp file creation
    try:
        formhub_url = "http://%s/" % request.META['HTTP_HOST']
    except:
        formhub_url = "http://formhub.org/"
    injected_xml = inject_instanceid(instance.xml, instance.uuid)
    values = {
        'format':
        'json',
        'form_id':
        xform.id_string,
        'server_url':
        formhub_url + username,
        'instance':
        injected_xml,
        'instance_id':
        instance.uuid,
        'return_url':
        request.build_absolute_uri(
            reverse('odk_viewer.views.instance',
                    kwargs={
                        'username': username,
                        'id_string': id_string
                    }) + "#/" + str(instance.id))
    }
    data, headers = multipart_encode(values)
    headers['User-Agent'] = 'formhub'
    req = urllib2.Request(url, data, headers)
    try:
        response = urllib2.urlopen(req)
        response = json.loads(response.read())
        context = RequestContext(request)
        owner = User.objects.get(username=username)
        context.profile, created = \
            UserProfile.objects.get_or_create(user=owner)
        context.xform = xform
        context.content_user = owner
        context.form_view = True
        if 'edit_url' in response:
            audit = {"xform": xform.id_string, "data_id": data_id}
            audit_log(
                Actions.SUBMISSION_EDIT_REQUESTED, request.user, owner,
                _("Requested to edit data with id "
                  "'%(data_id)s' on '%(id_string)s'.") % {
                      'id_string': xform.id_string,
                      'data_id': data_id
                  }, audit, request)
            context.enketo = response['edit_url']
            return HttpResponseRedirect(response['edit_url'])
        else:
            json_msg = response['reason']
            """
            return HttpResponse("<script>$('body')</script>")
            """
            context.message = {
                'type':
                'alert-error',
                'text':
                "Enketo error, reason: " +
                (response['reason'] and "Server not found.")
            }
            messages.add_message(request, messages.WARNING, json_msg)
            return render_to_response("profile.html", context_instance=context)

    except urllib2.URLError:
        # this will happen if we could not connect to enketo
        messages.add_message(request, messages.WARNING,
                             _("Enketo error: Unable to open webform url."))
    except ValueError, e:
        messages.add_message(request, messages.WARNING,
                             _("Enketo error: enketo replied %s") % e)
Example #27
0
def enter_data(request, username, id_string):
    owner = get_object_or_404(User, username=username)
    xform = get_object_or_404(XForm,
                              user__username=username,
                              id_string=id_string)
    if not has_edit_permission(xform, owner, request, xform.shared):
        return HttpResponseForbidden(_(u'Not shared.'))
    if not hasattr(settings, 'ENKETO_URL'):
        return HttpResponseRedirect(
            reverse('main.views.show',
                    kwargs={
                        'username': username,
                        'id_string': id_string
                    }))
    url = '%slaunch/launchSurvey' % settings.ENKETO_URL
    register_openers()
    response = None
    # see commit 220f2dad0e for tmp file creation
    try:
        formhub_url = "http://%s/" % request.META['HTTP_HOST']
    except:
        formhub_url = "http://formhub.org/"
    values = {
        'format': 'json',
        'form_id': xform.id_string,
        'server_url': formhub_url + username
    }
    data, headers = multipart_encode(values)
    headers['User-Agent'] = 'formhub'
    req = urllib2.Request(url, data, headers)
    try:
        response = urllib2.urlopen(req)
        response = json.loads(response.read())
        context = RequestContext(request)
        owner = User.objects.get(username=username)
        context.profile, created = \
            UserProfile.objects.get_or_create(user=owner)
        context.xform = xform
        context.content_user = owner
        context.form_view = True
        if 'url' in response:
            audit = {"xform": xform.id_string}
            audit_log(
                Actions.FORM_ENTER_DATA_REQUESTED, request.user, owner,
                _("Requested enter data url for '%(id_string)s'.") % {
                    'id_string': xform.id_string,
                }, audit, request)
            context.enketo = response['url']
            #return render_to_response("form_entry.html",
            #                          context_instance=context)
            return HttpResponseRedirect(response['url'])
        else:
            json_msg = response['reason']
            """
            return HttpResponse("<script>$('body')</script>")
            """
            context.message = {
                'type':
                'alert-error',
                'text':
                "Enketo error, reason: " +
                (response['reason'] and "Server not found.")
            }
            messages.add_message(request, messages.WARNING, json_msg)
            return render_to_response("profile.html", context_instance=context)

    except urllib2.URLError:
        # this will happen if we could not connect to enketo
        messages.add_message(request, messages.WARNING,
                             _("Enketo error: Unable to open webform url."))
    except ValueError, e:
        messages.add_message(request, messages.WARNING,
                             _("Enketo error: enketo replied %s") % e)
Example #28
0
def enter_data(request, username, id_string):
    owner = get_object_or_404(User, username=username)
    xform = get_object_or_404(XForm, user__username=username,
                              id_string=id_string)
    if not has_edit_permission(xform, owner, request, xform.shared):
        return HttpResponseForbidden(_(u'Not shared.'))
    if not hasattr(settings, 'ENKETO_URL'):
        return HttpResponseRedirect(reverse('main.views.show',
                                    kwargs={'username': username,
                                            'id_string': id_string}))
    url = '%slaunch/launchSurvey' % settings.ENKETO_URL
    register_openers()
    response = None
    # see commit 220f2dad0e for tmp file creation
    try:
        formhub_url = "http://%s/" % request.META['HTTP_HOST']
    except:
        formhub_url = "http://formhub.org/"
    values = {
        'format': 'json',
        'form_id': xform.id_string,
        'server_url': formhub_url + username
    }
    data, headers = multipart_encode(values)
    headers['User-Agent'] = 'formhub'
    req = urllib2.Request(url, data, headers)
    try:
        response = urllib2.urlopen(req)
        response = json.loads(response.read())
        context = RequestContext(request)
        owner = User.objects.get(username=username)
        context.profile, created = \
            UserProfile.objects.get_or_create(user=owner)
        context.xform = xform
        context.content_user = owner
        context.form_view = True
        if 'url' in response:
            audit = {
                "xform": xform.id_string
            }
            audit_log(Actions.FORM_ENTER_DATA_REQUESTED, request.user, owner,
                _("Requested enter data url for '%(id_string)s'.") %\
                {
                    'id_string': xform.id_string,
                }, audit, request)
            context.enketo = response['url']
            #return render_to_response("form_entry.html",
            #                          context_instance=context)
            return HttpResponseRedirect(response['url'])
        else:
            json_msg = response['reason']
            """
            return HttpResponse("<script>$('body')</script>")
            """
            context.message = {
                'type': 'alert-error',
                'text': "Enketo error, reason: " + (
                    response['reason'] and "Server not found.")}
            messages.add_message(request, messages.WARNING, json_msg)
            return render_to_response("profile.html", context_instance=context)

    except urllib2.URLError:
        # this will happen if we could not connect to enketo
        messages.add_message(
            request, messages.WARNING, _("Enketo error: Unable to open webform url."))
    except ValueError, e:
        messages.add_message(
            request, messages.WARNING, _("Enketo error: enketo replied %s") % e)
Example #29
0
def edit_data(request, username, id_string, data_id):
    owner = User.objects.get(username=username)
    xform = get_object_or_404(
        XForm, user__username=username, id_string=id_string)
    instance = get_object_or_404(
        Instance, pk=data_id, xform=xform)
    if not has_edit_permission(xform, owner, request, xform.shared):
        return HttpResponseForbidden(_(u'Not shared.'))
    if not hasattr(settings, 'ENKETO_URL'):
        return HttpResponseRedirect(
            reverse(
                'main.views.show', kwargs={'username': username,
                                           'id_string': id_string}
            )
        )

    url = '%sdata/edit_url' % settings.ENKETO_URL
    register_openers()
    response = None
    # see commit 220f2dad0e for tmp file creation
    try:
        formhub_url = "http://%s/" % request.META['HTTP_HOST']
    except:
        formhub_url = "http://formhub.org/"
    injected_xml = inject_instanceid(instance.xml, instance.uuid)
    values = {
        'format': 'json',
        'form_id': xform.id_string,
        'server_url': formhub_url + username,
        'instance': injected_xml,
        'instance_id': instance.uuid,
        'return_url': request.build_absolute_uri(
            reverse(
                'odk_viewer.views.instance',
                kwargs={
                    'username': username,
                    'id_string': id_string}
            ) + "#/" + str(instance.id))
    }
    data, headers = multipart_encode(values)
    headers['User-Agent'] = 'formhub'
    req = urllib2.Request(url, data, headers)
    try:
        response = urllib2.urlopen(req)
        response = json.loads(response.read())
        context = RequestContext(request)
        owner = User.objects.get(username=username)
        context.profile, created = \
            UserProfile.objects.get_or_create(user=owner)
        context.xform = xform
        context.content_user = owner
        context.form_view = True
        if 'edit_url' in response:
            audit = {
                "xform": xform.id_string,
                "data_id": data_id
            }
            audit_log(Actions.SUBMISSION_EDIT_REQUESTED, request.user, owner,
                _("Requested to edit data with id '%(data_id)s' on '%(id_string)s'.") %\
                {
                    'id_string': xform.id_string,
                    'data_id': data_id
                }, audit, request)
            context.enketo = response['edit_url']
            return HttpResponseRedirect(response['edit_url'])
        else:
            json_msg = response['reason']
            """
            return HttpResponse("<script>$('body')</script>")
            """
            context.message = {
                'type': 'alert-error',
                'text': "Enketo error, reason: " + (
                    response['reason'] and "Server not found.")
            }
            messages.add_message(request, messages.WARNING, json_msg)
            return render_to_response("profile.html", context_instance=context)

    except urllib2.URLError:
        # this will happen if we could not connect to enketo
        messages.add_message(
            request, messages.WARNING, _("Enketo error: Unable to open webform url."))
    except ValueError, e:
        messages.add_message(
            request, messages.WARNING, _("Enketo error: enketo replied %s") % e)
Example #30
0
def profile(request, username):
    context = RequestContext(request)
    content_user = get_object_or_404(User, username=username)
    context.form = QuickConverter()
    # xlsform submission...
    if request.method == "POST" and request.user.is_authenticated():

        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,
            }

        form_result = publish_form(set_form)
        if form_result["type"] == "alert-success":
            # comment the following condition (and else)
            # when we want to enable sms check for all.
            # until then, it checks if form barely related to sms
            if is_sms_related(form_result.get("form_o")):
                form_result_sms = check_form_sms_compatibility(form_result)
                context.message_list = [form_result, form_result_sms]
            else:
                context.message = form_result
        else:
            context.message = form_result

    # profile view...
    # for the same user -> dashboard
    if content_user == request.user:
        context.show_dashboard = True
        context.all_forms = content_user.xforms.count()
        context.form = QuickConverterFile()
        context.form_url = QuickConverterURL()
        context.odk_url = request.build_absolute_uri("/%s" % request.user.username)
        xforms = XForm.objects.filter(user=content_user).select_related("user", "surveys")
        context.user_xforms = xforms
        crowdforms = XForm.objects.filter(
            metadata__data_type=MetaData.CROWDFORM_USERS, metadata__data_value=username
        ).select_related("user")
        context.crowdforms = crowdforms
        # forms shared with user
        xfct = ContentType.objects.get(app_label="odk_logger", model="xform")
        xfs = content_user.userobjectpermission_set.filter(content_type=xfct)
        shared_forms_pks = list(set([xf.object_pk for xf in xfs]))
        context.forms_shared_with = (
            XForm.objects.filter(pk__in=shared_forms_pks).exclude(user=content_user).select_related("user")
        )
    # for any other user -> profile
    set_profile_data(context, content_user)
    return render_to_response("profile.html", context_instance=context)
Example #31
0
def profile(request, username):
    context = RequestContext(request)
    content_user = get_object_or_404(User, username=username)
    context.form = QuickConverter()

    # xlsform submission...
    if request.method == 'POST' and request.user.is_authenticated():
        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
            }
        form_result = publish_form(set_form)
        if form_result['type'] == 'alert-success':
            # comment the following condition (and else)
            # when we want to enable sms check for all.
            # until then, it checks if form barely related to sms
            if is_sms_related(form_result.get('form_o')):
                form_result_sms = check_form_sms_compatibility(form_result)
                context.message_list = [form_result, form_result_sms]
            else:
                context.message = form_result
        else:
            context.message = form_result

    # profile view...
    # for the same user -> dashboard
    if content_user == request.user:
        context.show_dashboard = True
        context.all_forms = content_user.xforms.count()
        context.form = QuickConverterFile()
        context.form_url = QuickConverterURL()

        request_url = request.build_absolute_uri(
            "/%s" % request.user.username)
        context.url = request_url.replace('http://', 'https://')
        xforms = XForm.objects.filter(user=content_user)\
            .select_related('user', 'instances')
        context.user_xforms = xforms
        # 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]))
        context.forms_shared_with = XForm.objects.filter(
            pk__in=shared_forms_pks).exclude(user=content_user)\
            .select_related('user')
        context.xforms_list = [
            {
                'id': 'published',
                'xforms': context.user_xforms,
                'title': _(u"Published Forms"),
                'small': _("Export, map, and view submissions.")
            },
            {
                'id': 'shared',
                'xforms': context.forms_shared_with,
                'title': _(u"Shared Forms"),
                'small': _("List of forms shared with you.")
            }
        ]
    # for any other user -> profile
    set_profile_data(context, content_user)
    return render_to_response("profile.html", context_instance=context)
Example #32
0
def clone_xlsform(request, username):
    """
    Copy a public/Shared form to a users list of forms.
    Eliminates the need to download Excel File and upload again.
    """
    to_username = request.user.username
    context = RequestContext(request)
    context.message = {'type': None, 'text': '....'}

    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})}
            }
    form_result = publish_form(set_form)
    if form_result['type'] == 'alert-success':
        # comment the following condition (and else)
        # when we want to enable sms check for all.
        # until then, it checks if form barely related to sms
        if is_sms_related(form_result.get('form_o')):
            form_result_sms = check_form_sms_compatibility(form_result)
            context.message_list = [form_result, form_result_sms]
        else:
            context.message = form_result
    else:
        context.message = form_result
    if request.is_ajax():
        res = loader.render_to_string(
            'message.html',
            context_instance=context).replace("'", r"\'").replace('\n', '')
        return HttpResponse(
            "$('#mfeedback').html('%s').show();" % res)
    else:
        return HttpResponse(context.message['text'])
Example #33
0
def profile(request, username):
    context = RequestContext(request)
    content_user = get_object_or_404(User, username=username)
    context.form = QuickConverter()
    # xlsform submission...
    if request.method == 'POST' and request.user.is_authenticated():
        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">Preview Web Form</a>')
                        % {'form_id': survey.id_string,
                            'form_url': enketo_webform_url},
                'form_o': survey
            }
        form_result = publish_form(set_form)
        if form_result['type'] == 'alert-success':
            # comment the following condition (and else)
            # when we want to enable sms check for all.
            # until then, it checks if form barely related to sms
            if is_sms_related(form_result.get('form_o')):
                form_result_sms = check_form_sms_compatibility(form_result)
                context.message_list = [form_result, form_result_sms]
            else:
                context.message = form_result
        else:
            context.message = form_result

    # profile view...
    # for the same user -> dashboard
    if content_user == request.user:
        context.show_dashboard = True
        context.user_surveys = content_user.surveys.count()
        context.all_forms = content_user.xforms.count()
        context.form = QuickConverterFile()
        context.form_url = QuickConverterURL()
        context.odk_url = request.build_absolute_uri(
            "/%s" % request.user.username)
        from django.db.models import Count
        xforms = XForm.objects.filter(user=content_user)\
            .select_related('user')\
                .extra(
                    select={
                        'submission_count': 'SELECT COUNT(*) FROM '
                        'odk_logger_instance WHERE '
                        'odk_logger_instance.xform_id=odk_logger_xform.id '
                        'AND odk_logger_instance.is_deleted=\'0\''
                    })
        context.user_xforms = xforms
        crowdforms = XForm.objects.filter(
            metadata__data_type=MetaData.CROWDFORM_USERS,
            metadata__data_value=username,)\
            .select_related('user')\
            .extra(
                select={
                    'submission_count': 'SELECT COUNT(*) FROM '
                    'odk_logger_instance WHERE '
                    'odk_logger_instance.xform_id=odk_logger_xform.id '
                    'AND odk_logger_instance.is_deleted=\'0\''
                })
        context.crowdforms = crowdforms
        # forms shared with user
        xfct = ContentType.objects.get(app_label='odk_logger', model='xform')
        xfs = content_user.userobjectpermission_set.filter(content_type=xfct)
        context.forms_shared_with = XForm.objects.filter(
            pk__in=[xf.object_pk for xf in xfs])\
            .select_related('user')\
            .extra(
                select={
                    'submission_count': 'SELECT COUNT(*) FROM '
                    'odk_logger_instance WHERE '
                    'odk_logger_instance.xform_id=odk_logger_xform.id '
                    'AND odk_logger_instance.is_deleted=\'0\''
                })
    # for any other user -> profile
    set_profile_data(context, content_user)
    return render_to_response("profile.html", context_instance=context)