def get_enketo_url(self, obj):
        if obj:
            _enketo_url = cache.get(
                '{}{}'.format(ENKETO_URL_CACHE, obj.pk))
            if _enketo_url:
                return _enketo_url

            try:
                metadata = MetaData.objects.get(
                    xform=obj, data_type="enketo_url")
            except MetaData.DoesNotExist:
                request = self.context.get('request')
                form_url = _get_form_url(request, obj.user.username)
                url = ""

                try:
                    url = enketo_url(form_url, obj.id_string)
                    MetaData.enketo_url(obj, url)
                except (EnketoError, ConnectionError):
                    pass

                cache.set('{}{}'.format(ENKETO_URL_CACHE, obj.pk), url)
                return url

            _enketo_url = metadata.data_value
            cache.set('{}{}'.format(ENKETO_URL_CACHE, obj.pk), _enketo_url)
            return _enketo_url

        return None
Beispiel #2
0
def enter_data(request, username, id_string):
    owner = get_object_or_404(User, username__iexact=username)
    xform = get_object_or_404(XForm, user__username__iexact=username,
                              id_string__exact=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:
        data = {}
        owner = User.objects.get(username__iexact=username)
        data['profile'], created = \
            UserProfile.objects.get_or_create(user=owner)
        data['xform'] = xform
        data['content_user'] = owner
        data['form_view'] = True
        data['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(request, "profile.html", data)

    return HttpResponseRedirect(reverse('onadata.apps.main.views.show',
                                kwargs={'username': username,
                                        'id_string': id_string}))
Beispiel #3
0
    def handle(self, *args, **options):
        request = HttpRequest()
        server_name = options.get('server_name')
        server_port = options.get('server_port')
        protocol = options.get('protocol')
        generate_consistent_urls = options.get('generate_consistent_urls')

        if not server_name or not server_port or not protocol:
            raise CommandError(
                'please provide a server_name, a server_port and a protocol')

        if server_name not in ['ona.io', 'stage.ona.io', 'localhost']:
            raise CommandError('server name provided is not valid')

        if protocol not in ['http', 'https']:
            raise CommandError('protocol provided is not valid')

        # required for generation of enketo url
        request.META['HTTP_HOST'] = '%s:%s' % (server_name, server_port)\
            if server_port != '80' else server_name

        # required for generation of enketo preview url
        request.META['SERVER_NAME'] = server_name
        request.META['SERVER_PORT'] = server_port

        resultset = MetaData.objects.filter(
            Q(data_type='enketo_url') | Q(data_type='enketo_preview_url'))

        for meta_data in resultset:
            username = meta_data.content_object.user.username
            id_string = meta_data.content_object.id_string

            data_type = meta_data.data_type
            data_value = meta_data.data_value
            xform = meta_data.content_object
            xform_pk = xform.pk

            with open('/tmp/enketo_url', 'a') as f:
                if data_type == 'enketo_url':
                    form_url = get_form_url(
                        request,
                        username=username,
                        id_string=id_string,
                        xform_pk=xform_pk,
                        generate_consistent_urls=generate_consistent_urls)
                    _enketo_url = enketo_url(form_url, id_string)
                    MetaData.enketo_url(xform, _enketo_url)
                elif data_type == 'enketo_preview_url':
                    _enketo_preview_url = get_enketo_preview_url(
                        request,
                        id_string,
                        username=username,
                        xform_pk=xform_pk,
                        generate_consistent_urls=generate_consistent_urls)
                    MetaData.enketo_preview_url(xform, _enketo_preview_url)

                f.write('%s : %s \n' % (id_string, data_value))
            self.stdout.write('%s: %s' % (data_type, meta_data.data_value))

        self.stdout.write("enketo urls update complete!!")
Beispiel #4
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}))
Beispiel #5
0
    def get_enketo_url(self, obj):
        if obj:
            _enketo_url = cache.get('{}{}'.format(ENKETO_URL_CACHE, obj.pk))
            if _enketo_url:
                return _enketo_url

            try:
                metadata = MetaData.objects.get(xform=obj,
                                                data_type="enketo_url")
            except MetaData.DoesNotExist:
                request = self.context.get('request')
                form_url = _get_form_url(request, obj.user.username)
                url = ""

                try:
                    url = enketo_url(form_url, obj.id_string)
                    MetaData.enketo_url(obj, url)
                except (EnketoError, ConnectionError):
                    pass

                cache.set('{}{}'.format(ENKETO_URL_CACHE, obj.pk), url)
                return url

            _enketo_url = metadata.data_value
            cache.set('{}{}'.format(ENKETO_URL_CACHE, obj.pk), _enketo_url)
            return _enketo_url

        return None
    def enketo(self, request, **kwargs):
        self.object = self.get_object()
        form_url = get_form_url(
            request, self.object.user.username, settings.ENKETO_PROTOCOL,
            xform_pk=self.object.pk)

        data = {'message': _(u"Enketo not properly configured.")}
        http_status = status.HTTP_400_BAD_REQUEST

        try:
            # pass default arguments to enketo_url to prepopulate form fields
            request_vars = request.GET
            defaults = generate_enketo_form_defaults(
                self.object, **request_vars)
            url = enketo_url(form_url, self.object.id_string, **defaults)
            preview_url = get_enketo_preview_url(request,
                                                 self.object.user.username,
                                                 self.object.id_string,
                                                 xform_pk=self.object.pk)
        except EnketoError as e:
            data = {'message': _(u"Enketo error: %s" % e)}
        else:
            if url and preview_url:
                http_status = status.HTTP_200_OK
                data = {"enketo_url": url, "enketo_preview_url": preview_url}

        return Response(data, http_status)
Beispiel #7
0
def qrcode(request, username, id_string):
    try:
        formhub_url = "http://%s/" % request.META['HTTP_HOST']
    except:
        formhub_url = "http://formhub.org/"
    formhub_url = formhub_url + username

    if settings.TESTING_MODE:
        formhub_url = "https://{}/{}".format(settings.TEST_HTTP_HOST,
                                             settings.TEST_USERNAME)

    results = _(u"Unexpected Error occured: No QRCODE generated")
    status = 200
    try:
        url = enketo_url(formhub_url, id_string)
    except Exception as e:
        error_msg = _(u"Error Generating QRCODE: %s" % e)
        results = """<div class="alert alert-error">%s</div>""" % error_msg
        status = 400
    else:
        if url:
            image = generate_qrcode(url)
            results = """<img class="qrcode" src="%s" alt="%s" />
                    </br><a href="%s" target="_blank">%s</a>""" \
                % (image, url, url, url)
        else:
            status = 400
    return HttpResponse(results, mimetype='text/html', status=status)
Beispiel #8
0
def enter_data(request, username, id_string):
    owner = get_object_or_404(User, username__iexact=username)
    xform = get_object_or_404(XForm, user__username__iexact=username, id_string__exact=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:
        data = {}
        owner = User.objects.get(username__iexact=username)
        data["profile"], created = UserProfile.objects.get_or_create(user=owner)
        data["xform"] = xform
        data["content_user"] = owner
        data["form_view"] = True
        data["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(request, "profile.html", data)

    return HttpResponseRedirect(
        reverse("onadata.apps.main.views.show", kwargs={"username": username, "id_string": id_string})
    )
Beispiel #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)
Beispiel #10
0
def enter_data(request, username, id_string):
    owner = get_object_or_404(User, username__iexact=username)
    xform = get_object_or_404(XForm, user__username__iexact=username,
                              id_string__iexact=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:
        data = {}
        owner = User.objects.get(username__iexact=username)
        data['profile'], created = \
            UserProfile.objects.get_or_create(user=owner)
        data['xform'] = xform
        data['content_user'] = owner
        data['form_view'] = True
        data['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(request, "profile.html", data)

    return HttpResponseRedirect(reverse('onadata.apps.main.views.show',
                                kwargs={'username': username,
                                        'id_string': id_string}))
Beispiel #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
                }) + "#/" + 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 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
                }))
Beispiel #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}))
Beispiel #13
0
 def test_enketo_remote_server(self):
     if not self._running_enketo():
         raise SkipTest
     with HTTMock(enketo_mock):
         server_url = 'https://testserver.com/bob'
         form_id = "test_%s" % re.sub(re.compile("\."), "_", str(time()))
         url = enketo_url(server_url, form_id)
         self.assertIsInstance(url, basestring)
         self.assertIsNone(URLValidator()(url))
 def test_enketo_remote_server(self):
     if not self._running_enketo():
         raise SkipTest
     with HTTMock(enketo_mock):
         server_url = 'https://testserver.com/bob'
         form_id = "test_%s" % re.sub(re.compile("\."), "_", str(time()))
         url = enketo_url(server_url, form_id)
         self.assertIsInstance(url, basestring)
         self.assertIsNone(URLValidator()(url))
Beispiel #15
0
 def enketo(self, request, **kwargs):
     self.object = self.get_object()
     form_url = _get_form_url(request, self.object.user.username)
     url = enketo_url(form_url, self.object.id_string)
     data = {'message': _(u"Enketo not properly configured.")}
     status = 400
     if url:
         status = 200
         data = {"enketo_url": url}
     return Response(data, status)
Beispiel #16
0
 def test_enketo_url_with_http_protocol_on_formlist(self):
     if not self._running_enketo():
         raise SkipTest
     with HTTMock(enketo_mock_http):
         server_url = "http://testserver.com/bob"
         form_id = "test_%s" % re.sub(re.compile("\."), "_", str(time()))  # noqa
         url = enketo_url(server_url, form_id)
         self.assertIn("http:", url)
         self.assertIsInstance(url, basestring)
         self.assertIsNone(URLValidator()(url))
 def test_enketo_url_with_http_protocol_on_formlist(self):
     if not self._running_enketo():
         raise SkipTest
     with HTTMock(enketo_mock_http):
         server_url = 'http://testserver.com/bob'
         form_id = "test_%s" % re.sub(re.compile("\."), "_", str(time()))
         url = enketo_url(server_url, form_id)
         self.assertIn('http:', url)
         self.assertIsInstance(url, basestring)
         self.assertIsNone(URLValidator()(url))
Beispiel #18
0
 def enketo(self, request, **kwargs):
     self.object = self.get_object()
     form_url = _get_form_url(request, self.object.user.username)
     url = enketo_url(form_url, self.object.id_string)
     data = {'message': _(u"Enketo not properly configured.")}
     status = 400
     if url:
         status = 200
         data = {"enketo_url": url}
     return Response(data, status)
Beispiel #19
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)
    instance_attachments = image_urls_dict(instance)
    if not has_edit_permission(xform, owner, request):
        return HttpResponseForbidden(_('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(username)

    try:
        url = enketo_url(form_url,
                         xform.id_string,
                         instance_xml=injected_xml,
                         instance_id=instance.uuid,
                         return_url=return_url,
                         instance_attachments=instance_attachments)
    except Exception as e:
        context.message = {
            'type': 'alert-error',
            'text': "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
                }))
Beispiel #20
0
    def enketo(self, request, **kwargs):
        self.object = self.get_object()
        form_url = _get_form_url(request, self.object.user.username)
        url = enketo_url(form_url, self.object.id_string)
        data = {'message': _(u"Enketo not properly configured.")}
        http_status = status.HTTP_400_BAD_REQUEST

        if url:
            http_status = status.HTTP_200_OK
            data = {"enketo_url": url}

        return Response(data, http_status)
Beispiel #21
0
    def handle(self, *args, **options):
        request = HttpRequest()
        server_name = options.get('server_name')
        server_port = options.get('server_port')
        protocol = options.get('protocol')

        if not server_name or not server_port or not protocol:
            raise CommandError(
                'please provide a server_name, a server_port and a protocol')

        if server_name not in ['ona.io', 'stage.ona.io', 'localhost']:
            raise CommandError('server name provided is not valid')

        if protocol not in ['http', 'https']:
            raise CommandError('protocol provided is not valid')

        # required for generation of enketo url
        request.META['HTTP_HOST'] = '%s:%s' % (server_name, server_port)\
            if server_port != '80' else server_name

        # required for generation of enketo preview url
        request.META['SERVER_NAME'] = server_name
        request.META['SERVER_PORT'] = server_port

        resultset = MetaData.objects.filter(
            Q(data_type='enketo_url') | Q(data_type='enketo_preview_url'))
        for meta_data in resultset:
            username = meta_data.content_object.user.username
            id_string = meta_data.content_object.id_string
            data_type = meta_data.data_type
            data_value = meta_data.data_value
            xform = meta_data.content_object
            with open('/tmp/enketo_url', 'a') as f:

                if data_type == 'enketo_url':
                    form_url = get_form_url(
                        request, username, protocol=protocol,
                        xform_pk=xform.pk)
                    _enketo_url = enketo_url(form_url, id_string)
                    MetaData.enketo_url(xform, _enketo_url)
                elif data_type == 'enketo_preview_url':
                    _enketo_preview_url = get_enketo_preview_url(
                        request, username, id_string, xform_pk=xform.pk)
                    MetaData.enketo_preview_url(xform, _enketo_preview_url)
                f.write('%s : %s \n' % (id_string, data_value))

            self.stdout.write('%s: %s' % (data_type, meta_data.data_value))

        self.stdout.write("enketo urls update complete!!")
Beispiel #22
0
def qrcode(request, username, id_string):
    try:
        formhub_url = "http://%s/" % request.META["HTTP_HOST"]
    except:
        formhub_url = "http://formhub.org/"
    formhub_url = formhub_url + username
    if settings.TESTING_MODE:
        formhub_url = "https://testserver.com/bob"
    results = _(u"Unexpected Error occured: No QRCODE generated")
    status = 200
    try:
        url = enketo_url(formhub_url, id_string)
    except Exception, e:
        error_msg = _(u"Error Generating QRCODE: %s" % e)
        results = """<div class="alert alert-error">%s</div>""" % error_msg
        status = 400
Beispiel #23
0
    def enketo(self, request, **kwargs):
        self.object = self.get_object()
        form_url = _get_form_url(request, self.object.user.username)

        data = {'message': _(u"Enketo not properly configured.")}
        http_status = status.HTTP_400_BAD_REQUEST

        try:
            url = enketo_url(form_url, self.object.id_string)
        except EnketoError:
            pass
        else:
            if url:
                http_status = status.HTTP_200_OK
                data = {"enketo_url": url}

        return Response(data, http_status)
def _create_enketo_url(request, xform):
    """
    Generate enketo url for a form

    :param request:
    :param xform:
    :return: enketo url
    """
    form_url = get_form_url(request, xform.user.username,
                            settings.ENKETO_PROTOCOL)
    url = ""

    try:
        url = enketo_url(form_url, xform.id_string)
        MetaData.enketo_url(xform, url)
    except ConnectionError, e:
        logging.exception("Connection Error: %s" % e.message)
Beispiel #25
0
def _create_enketo_url(request, xform):
    """
    Generate enketo url for a form

    :param request:
    :param xform:
    :return: enketo url
    """
    form_url = get_form_url(request, xform.user.username,
                            settings.ENKETO_PROTOCOL, xform_pk=xform.pk)
    url = ""

    try:
        url = enketo_url(form_url, xform.id_string)
        MetaData.enketo_url(xform, url)
    except ConnectionError as e:
        logging.exception("Connection Error: %s" % e)
    except EnketoError as e:
        logging.exception("Enketo Error: %s" % e.message)

    return url
Beispiel #26
0
    def enketo(self, request, **kwargs):
        """Expose enketo urls."""
        survey_type = self.kwargs.get('survey_type') or \
            request.GET.get('survey_type')
        self.object = self.get_object()
        form_url = get_form_url(request,
                                self.object.user.username,
                                protocol=settings.ENKETO_PROTOCOL,
                                xform_pk=self.object.pk,
                                generate_consistent_urls=True)

        data = {'message': _(u"Enketo not properly configured.")}
        http_status = status.HTTP_400_BAD_REQUEST

        try:
            # pass default arguments to enketo_url to prepopulate form fields
            request_vars = request.GET
            defaults = generate_enketo_form_defaults(self.object,
                                                     **request_vars)
            url = enketo_url(form_url, self.object.id_string, **defaults)
            preview_url = get_enketo_preview_url(request,
                                                 self.object.user.username,
                                                 self.object.id_string,
                                                 xform_pk=self.object.pk)
        except EnketoError as e:
            data = {'message': _(u"Enketo error: %s" % e)}
        else:
            if survey_type == 'single':
                single_submit_url = get_enketo_single_submit_url(
                    request,
                    self.object.user.username,
                    self.object.id_string,
                    xform_pk=self.object.pk)
                data = {"single_submit_url": single_submit_url}
            elif url and preview_url:
                http_status = status.HTTP_200_OK
                data = {"enketo_url": url, "enketo_preview_url": preview_url}

        return Response(data, http_status)
Beispiel #27
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(
            '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)

    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)
Beispiel #28
0
    def enketo(self, request, **kwargs):
        """Expose enketo urls."""
        survey_type = self.kwargs.get('survey_type') or \
            request.GET.get('survey_type')
        self.object = self.get_object()
        form_url = get_form_url(
            request, self.object.user.username, settings.ENKETO_PROTOCOL,
            xform_pk=self.object.pk)

        data = {'message': _(u"Enketo not properly configured.")}
        http_status = status.HTTP_400_BAD_REQUEST

        try:
            # pass default arguments to enketo_url to prepopulate form fields
            request_vars = request.GET
            defaults = generate_enketo_form_defaults(
                self.object, **request_vars)
            url = enketo_url(
                form_url, self.object.id_string, **defaults)
            preview_url = get_enketo_preview_url(request,
                                                 self.object.user.username,
                                                 self.object.id_string,
                                                 xform_pk=self.object.pk)
        except EnketoError as e:
            data = {'message': _(u"Enketo error: %s" % e)}
        else:
            if survey_type == 'single':
                single_submit_url = get_enketo_single_submit_url(
                    request, self.object.user.username, self.object.id_string,
                    xform_pk=self.object.pk)
                data = {"single_submit_url": single_submit_url}
            elif url and preview_url:
                http_status = status.HTTP_200_OK
                data = {"enketo_url": url,
                        "enketo_preview_url": preview_url}

        return Response(data, http_status)
Beispiel #29
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})
    )
    def enketo(self, request, **kwargs):
        self.object = self.get_object()
        form_url = _get_form_url(request, self.object.user.username)

        data = {'message': _(u"Enketo not properly configured.")}
        http_status = status.HTTP_400_BAD_REQUEST

        try:
            # pass default arguments to enketo_url to prepopulate form fields
            request_vars = request.GET
            defaults = generate_enketo_form_defaults(
                self.object, **request_vars)
            url = enketo_url(form_url, self.object.id_string, **defaults)
            preview_url = get_enketo_preview_url(request,
                                                 request.user.username,
                                                 self.object.id_string)
        except EnketoError:
            pass
        else:
            if url and preview_url:
                http_status = status.HTTP_200_OK
                data = {"enketo_url": url, "enketo_preview_url": preview_url}

        return Response(data, http_status)
    def handle(self, *args, **options):
        request = HttpRequest()
        server_name = options.get('server_name')
        server_port = options.get('server_port')
        protocol = options.get('protocol')
        username = options.get('username')
        id_string = options.get('id_string')

        if not server_name or not server_port or not protocol:
            raise CommandError(
                'please provide a server_name, a server_port and a protocol')

        if server_name not in ['api.ona.io', 'stage-api.ona.io', 'localhost']:
            raise CommandError('server name provided is not valid')

        if protocol not in ['http', 'https']:
            raise CommandError('protocol provided is not valid')

        # required for generation of enketo url
        request.META['HTTP_HOST'] = '%s:%s' % (server_name, server_port)\
            if server_port != '80' else server_name

        # required for generation of enketo preview url
        request.META['SERVER_NAME'] = server_name
        request.META['SERVER_PORT'] = server_port

        if username and id_string:
            try:
                xform = XForm.objects.get(
                    user__username=username, id_string=id_string)
                form_url = get_form_url(request, username, protocol=protocol,
                                        xform_pk=xform.pk)
                id_string = xform.id_string
                _url = enketo_url(form_url, id_string)
                _preview_url = get_enketo_preview_url(request, username,
                                                      id_string,
                                                      xform_pk=xform.pk)
                self.stdout.write('enketo url: %s | preview url: %s' %
                                  (_url, _preview_url))
                self.stdout.write("enketo urls generation completed!!")
            except XForm.DoesNotExist:
                self.stdout.write(
                    "No xform matching the provided username and id_string")
        elif username and id_string is None:
            xforms = XForm.objects.filter(user__username=username)
            num_of_xforms = xforms.count()
            if xforms:
                for xform in queryset_iterator(xforms):
                    form_url = get_form_url(request, username,
                                            protocol=protocol,
                                            xform_pk=xform.pk)
                    id_string = xform.id_string
                    _url = enketo_url(form_url, id_string)
                    _preview_url = get_enketo_preview_url(
                        request, username, id_string, xform_pk=xform.pk)
                    num_of_xforms -= 1
                    self.stdout.write(
                        'enketo url: %s | preview url: %s | remaining: %s' %
                        (_url, _preview_url, num_of_xforms))
                self.stdout.write("enketo urls generation completed!!")
            else:
                self.stdout.write("Username doesn't own any form")
        else:
            xforms = XForm.objects.all()
            num_of_xforms = xforms.count()
            for xform in queryset_iterator(xforms):
                username = xform.user.username
                id_string = xform.id_string
                form_url = get_form_url(request, username, protocol=protocol,
                                        xform_pk=xform.pk)
                _url = enketo_url(form_url, id_string)
                _preview_url = get_enketo_preview_url(request, username,
                                                      id_string,
                                                      xform_pk=xform.pk)
                num_of_xforms -= 1
                self.stdout.write(
                    'enketo url: %s | preview url: %s | remaining: %s' %
                    (_url, _preview_url, num_of_xforms))
            self.stdout.write("enketo urls generation completed!!")
    def handle(self, *args, **kwargs):
        request = HttpRequest()
        server_name = kwargs.get('server_name')
        server_port = kwargs.get('server_port')
        protocol = kwargs.get('protocol')
        username = kwargs.get('username')
        id_string = kwargs.get('id_string')

        if not server_name or not server_port or not protocol:
            raise CommandError(
                'please provide a server_name, a server_port and a protocol')

        if server_name not in ['api.ona.io', 'stage-api.ona.io', 'localhost']:
            raise CommandError('server name provided is not valid')

        if protocol not in ['http', 'https']:
            raise CommandError('protocol provided is not valid')

        # required for generation of enketo url
        request.META['HTTP_HOST'] = '%s:%s' % (server_name, server_port)\
            if server_port != '80' else server_name

        # required for generation of enketo preview url
        request.META['SERVER_NAME'] = server_name
        request.META['SERVER_PORT'] = server_port

        if username and id_string:
            form_url = get_form_url(request, username, protocol=protocol)
            try:
                xform = XForm.objects.get(user__username=username,
                                          id_string=id_string)
                id_string = xform.id_string
                _url = enketo_url(form_url, id_string)
                _preview_url = get_enketo_preview_url(request, username,
                                                      id_string)
                self.stdout.write('enketo url: %s | preview url: %s' %
                                  (_url, _preview_url))
                self.stdout.write("enketo urls generation completed!!")
            except XForm.DoesNotExist:
                self.stdout.write(
                    "No xform matching the provided username and id_string")
        elif username and id_string is None:
            form_url = get_form_url(request, username, protocol=protocol)
            xforms = XForm.objects.filter(user__username=username)
            num_of_xforms = xforms.count()
            if xforms:
                for xform in queryset_iterator(xforms):
                    id_string = xform.id_string
                    _url = enketo_url(form_url, id_string)
                    _preview_url = get_enketo_preview_url(
                        request, username, id_string)
                    num_of_xforms -= 1
                    self.stdout.write(
                        'enketo url: %s | preview url: %s | remaining: %s' %
                        (_url, _preview_url, num_of_xforms))
                self.stdout.write("enketo urls generation completed!!")
            else:
                self.stdout.write("Username doesn't own any form")
        else:
            xforms = XForm.objects.all()
            num_of_xforms = xforms.count()
            for xform in queryset_iterator(xforms):
                username = xform.user.username
                id_string = xform.id_string
                form_url = get_form_url(request, username, protocol=protocol)
                _url = enketo_url(form_url, id_string)
                _preview_url = get_enketo_preview_url(request, username,
                                                      id_string)
                num_of_xforms -= 1
                self.stdout.write(
                    'enketo url: %s | preview url: %s | remaining: %s' %
                    (_url, _preview_url, num_of_xforms))
            self.stdout.write("enketo urls generation completed!!")