Exemplo n.º 1
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)
Exemplo n.º 2
0
def update_xform(request, username, id_string):
    xform = get_object_or_404(XForm, user__username=username, id_string=id_string)
    owner = xform.user

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

    message = publish_form(set_form)
    messages.add_message(request, messages.INFO, message["text"], extra_tags=message["type"])
    return HttpResponseRedirect(reverse(show, kwargs={"username": username, "id_string": id_string}))
Exemplo n.º 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": "...."}

    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"])
Exemplo n.º 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)
Exemplo n.º 5
0
def publish_project_xform(request, project):
    def set_form():
        form = QuickConverter(request.POST, request.FILES)
        return form.publish(project.organization)
    xform = publish_form(set_form)
    if isinstance(xform, XForm):
        add_xform_to_project(xform, project, request.user)
    return xform
Exemplo n.º 6
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)
Exemplo n.º 7
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'])
Exemplo n.º 8
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'])
Exemplo n.º 9
0
def form_upload(request, username):
    class DoXmlFormUpload():
        def __init__(self, xml_file, user):
            self.xml_file = xml_file
            self.user = user

        def publish(self):
            return publish_xml_form(self.xml_file, self.user)

    form_user = get_object_or_404(User, username=username)
    profile, created = \
        UserProfile.objects.get_or_create(user=form_user)
    authenticator = HttpDigestAuthenticator()
    if not authenticator.authenticate(request):
        return authenticator.build_challenge_response()
    if form_user != request.user:
        return HttpResponseForbidden(
            _(u"Not allowed to upload form[s] to %(user)s account." %
              {'user': form_user}))
    if request.method == 'HEAD':
        response = OpenRosaResponse(status=204)
        response['Location'] = request.build_absolute_uri().replace(
            request.get_full_path(), '/%s/formUpload' % form_user.username)
        return response
    xform_def = request.FILES.get('form_def_file', None)
    content = u""
    if isinstance(xform_def, File):
        do_form_upload = DoXmlFormUpload(xform_def, form_user)
        dd = publish_form(do_form_upload.publish)
        status = 201
        if isinstance(dd, XForm):
            content = _(u"%s successfully published." % dd.id_string)
        else:
            content = dd['text']
            if isinstance(content, Exception):
                content = content.message
                status = 500
            else:
                status = 400
    return OpenRosaResponse(content, status=status)
Exemplo n.º 10
0
def form_upload(request, username):
    class DoXmlFormUpload():
        def __init__(self, xml_file, user):
            self.xml_file = xml_file
            self.user = user

        def publish(self):
            return publish_xml_form(self.xml_file, self.user)

    form_user = get_object_or_404(User, username=username)
    profile, created = \
        UserProfile.objects.get_or_create(user=form_user)
    authenticator = HttpDigestAuthenticator()
    if not authenticator.authenticate(request):
        return authenticator.build_challenge_response()
    if form_user != request.user:
        return HttpResponseForbidden(
            _(u"Not allowed to upload form[s] to %(user)s account." %
              {'user': form_user}))
    if request.method == 'HEAD':
        response = OpenRosaResponse(status=204)
        response['Location'] = request.build_absolute_uri().replace(
            request.get_full_path(), '/%s/formUpload' % form_user.username)
        return response
    xform_def = request.FILES.get('form_def_file', None)
    content = u""
    if isinstance(xform_def, File):
        do_form_upload = DoXmlFormUpload(xform_def, form_user)
        dd = publish_form(do_form_upload.publish)
        status = 201
        if isinstance(dd, XForm):
            content = _(u"%s successfully published." % dd.id_string)
        else:
            content = dd['text']
            if isinstance(content, Exception):
                content = content.message
                status = 500
            else:
                status = 400
    return OpenRosaResponse(content, status=status)
Exemplo n.º 11
0
def update_xform(request, username, id_string):
    xform = get_object_or_404(
        XForm, user__username=username, id_string=id_string)
    owner = xform.user

    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}
        }
    message = publish_form(set_form)
    messages.add_message(
        request, messages.INFO, message['text'], extra_tags=message['type'])
    return HttpResponseRedirect(reverse(show, kwargs={
        'username': username,
        'id_string': id_string
    }))
Exemplo n.º 12
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'])
Exemplo n.º 13
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)