Example #1
0
def download_jsonform(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 request.method == "OPTIONS":
        response = HttpResponse()
        add_cors_headers(response)
        return response
    helper_auth_helper(request)
    #if not has_permission(xform, owner, request, xform.shared):
    if not check_form_permissions(xform, str(request.user), 'can_view'):
        response = HttpResponseForbidden(_(u'Not shared.'))
        add_cors_headers(response)
        return response
    response = response_with_mimetype_and_name('json',
                                               id_string,
                                               show_date=False)
    if 'callback' in request.GET and request.GET.get('callback') != '':
        callback = request.GET.get('callback')
        response.content = "%s(%s)" % (callback, xform.json)
    else:
        add_cors_headers(response)
        response.content = xform.json
    return response
Example #2
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 #3
0
def custom_project_window(request, username, id_string, **kwargs):
    """
    Replaces the default kobo project window.
    Creates a one page solution with one page view.
    """
    owner = get_object_or_404(User, username__iexact=username)
    xform = get_object_or_404(XForm, id_string__exact=id_string, user=owner)

    #if not has_permission(xform, owner, request):
    if not check_form_permissions(xform, str(request.user), 'can_view'):
        return HttpResponseForbidden(_(u'Not shared.'))

    user_list = get_own_and_partner_orgs_usermodule_users(request)
    username_list = [
        str(custom_user.user.username) for custom_user in user_list
    ]
    username_list.append(str(request.user.username))
    # data grid view part
    data = {
        'owner': owner,
        'xform': xform,
        'form_map_url':
        '/' + owner.username + '/forms/' + xform.id_string + '/map',
        'user_list': username_list
    }

    # start: export part
    export_type = 'xls'

    if export_type == Export.GDOC_EXPORT:
        redirect_url = reverse(export_list,
                               kwargs={
                                   'username': username,
                                   'id_string': id_string,
                                   'export_type': export_type
                               })
        token = _get_google_token(request, redirect_url)
        if isinstance(token, HttpResponse):
            return token

    if export_type == Export.EXTERNAL_EXPORT:
        # check for template before trying to generate a report
        if not MetaData.external_export(xform=xform):
            return HttpResponseForbidden(_(u'No XLS Template set.'))
    # Get meta and token
    export_token = request.GET.get('token')
    export_meta = request.GET.get('meta')
    options = {
        'meta': export_meta,
        'token': export_token,
    }

    export_type_zip = 'zip'
    if export_type_zip == Export.GDOC_EXPORT:
        redirect_url = reverse(export_list,
                               kwargs={
                                   'username': username,
                                   'id_string': id_string,
                                   'export_type': export_type_zip
                               })
        token = _get_google_token(request, redirect_url)
        if isinstance(token, HttpResponse):
            return token

    if export_type_zip == Export.EXTERNAL_EXPORT:
        # check for template before trying to generate a report
        if not MetaData.external_export(xform=xform):
            return HttpResponseForbidden(_(u'No XLS Template set.'))
    #code is commented to stop auto export generation
    # if should_create_new_export(xform, export_type):
    #     try:
    #         create_async_export(
    #             xform, export_type, query=None, force_xlsx=True,
    #             options=options)
    #     except Export.ExportTypeError:
    #         return HttpResponseBadRequest(
    #             _("%s is not a valid export type" % export_type))

    metadata = MetaData.objects.filter(xform=xform,
                                       data_type="external_export")\
        .values('id', 'data_value')

    for m in metadata:
        m['data_value'] = m.get('data_value').split('|')[0]

    #tab_selection = '#' + request.GET.get('tab_selection','grid')
    tab_selection = '#' + request.GET.get('tab_selection', 'data_table')
    #    print tab_selection
    data.update({
        'username':
        owner.username,
        'xform':
        xform,
        'export_type':
        export_type,
        'export_type_zip':
        export_type_zip,
        'export_type_name':
        Export.EXPORT_TYPE_DICT[export_type],
        'export_type_name_zip':
        Export.EXPORT_TYPE_DICT[export_type_zip],
        'exports':
        Export.objects.filter(
            Q(xform=xform, export_type='xls')
            | Q(xform=xform, export_type='csv')).order_by('-created_on'),
        'exports_zip':
        Export.objects.filter(xform=xform,
                              export_type='zip').order_by('-created_on'),
        'metas':
        metadata,
        'tab_selection':
        tab_selection,
    })
    # end: export part

    # start: image gallery part
    # instances = Instance.objects.filter(xform=xform).values('id')
    # instances_list = [instance['id'] for instance in instances]
    # attachments = Attachment.objects.filter(instance__in=instances_list,mimetype__icontains='image').values('media_file')
    # image_list = []
    # for i in attachments:
    #     image = {}
    #     image['url'] = request.build_absolute_uri('/media/'+i['media_file'])
    #     image['title'] = i['media_file'][i['media_file'].rfind('/')+1:]
    #     image_list.append(image)
    # data.update({
    #     'image_list': image_list,
    # })
    # end: image gallery part
    return render(request, "usermodule/custom_project_window.html", data)
def custom_project_window(request, username, id_string, **kwargs):
    """
    Replaces the default kobo project window.
    Creates a one page solution with one page view.
    """
    owner = get_object_or_404(User, username__iexact=username)
    xform = get_object_or_404(XForm, id_string__exact=id_string, user=owner)
    if not check_form_permissions(xform, str(request.user), 'can_view'):
        return HttpResponseForbidden(_(u'Not shared.'))

    user_list = get_own_and_partner_orgs_usermodule_users(request)
    username_list = [
        str(custom_user.user.username) for custom_user in user_list
    ]
    username_list.append(str(request.user.username))

    # data grid view part
    data = {
        'owner': owner,
        'xform': xform,
        'form_map_url':
        '/' + owner.username + '/forms/' + xform.id_string + '/map',
        'user_list': username_list
    }

    #form multilanguage handle part

    languages = ['English']
    query = "select id FROM logger_instance WHERE xform_id = (select id from logger_xform where id_string =  '" + id_string + "') limit 1"
    print "##########testing##########"
    instance_id = __db_fetch_single_value(query)
    if instance_id:
        query = "SELECT * from public.get_instance_extracted_temp(" + str(
            instance_id) + ")"
        form_data = __db_fetch_values_dict(query)

        omitFieldsLang = [
            'formhub/uuid', 'meta/instanceID', '_xform_id_string', 'username'
        ]
        first_field = ''
        for f in form_data:
            if f['_field_name'] not in omitFieldsLang:
                first_field = f['_q_title']
                #print "data"
                #print first_field
                break
        if first_field.startswith('{'):
            languages = sjson.loads(first_field).keys()

    print languages
    # start: export part
    export_type = 'xls'

    if export_type == Export.GDOC_EXPORT:
        redirect_url = reverse(export_list,
                               kwargs={
                                   'username': username,
                                   'id_string': id_string,
                                   'export_type': export_type
                               })
        token = _get_google_token(request, redirect_url)
        if isinstance(token, HttpResponse):
            return token

    default_fields_query = "select default_fields from public.export_default_parent where id_string = '" + id_string + "'"
    cursor = connection.cursor()
    cursor.execute(default_fields_query)
    default_fields_data = cursor.fetchone()

    dictlist = []
    if default_fields_data is not None:
        sorted_keys = sorted(list(default_fields_data[0].keys()))
        #print type(sorted_keys)
        for value in sorted_keys:
            dictlist.append(str(default_fields_data[0][value]))

    if export_type == Export.EXTERNAL_EXPORT:
        # check for template before trying to generate a report
        if not MetaData.external_export(xform=xform):
            return HttpResponseForbidden(_(u'No XLS Template set.'))
    # Get meta and token
    export_token = request.GET.get('token')
    export_meta = request.GET.get('meta')
    options = {
        'meta': export_meta,
        'token': export_token,
    }

    export_type_zip = 'zip'
    if export_type_zip == Export.GDOC_EXPORT:
        redirect_url = reverse(export_list,
                               kwargs={
                                   'username': username,
                                   'id_string': id_string,
                                   'export_type': export_type_zip
                               })
        token = _get_google_token(request, redirect_url)
        if isinstance(token, HttpResponse):
            return token

    if export_type_zip == Export.EXTERNAL_EXPORT:
        # check for template before trying to generate a report
        if not MetaData.external_export(xform=xform):
            return HttpResponseForbidden(_(u'No XLS Template set.'))
    #code is commented to stop auto export generation
    # if should_create_new_export(xform, export_type):
    #     try:
    #         create_async_export(
    #             xform, export_type, query=None, force_xlsx=True,
    #             options=options)
    #     except Export.ExportTypeError:
    #         return HttpResponseBadRequest(
    #             _("%s is not a valid export type" % export_type))

    metadata = MetaData.objects.filter(xform=xform,
                                       data_type="external_export")\
        .values('id', 'data_value')

    for m in metadata:
        m['data_value'] = m.get('data_value').split('|')[0]

    #tab_selection = '#' + request.GET.get('tab_selection','grid')
    tab_selection = '#' + request.GET.get('tab_selection', 'data_table')
    #    print tab_selection
    data.update({
        'username':
        owner.username,
        'xform':
        xform,
        'export_type':
        export_type,
        'export_type_zip':
        export_type_zip,
        'export_type_name':
        Export.EXPORT_TYPE_DICT[export_type],
        'export_type_name_zip':
        Export.EXPORT_TYPE_DICT[export_type_zip],
        'exports':
        Export.objects.filter(
            Q(xform=xform, export_type='xls')
            | Q(xform=xform, export_type='csv')).order_by('-created_on'),
        'exports_zip':
        Export.objects.filter(xform=xform,
                              export_type='zip').order_by('-created_on'),
        'metas':
        metadata,
        'tab_selection':
        tab_selection,
        'default_fields_data':
        dictlist,
        'language':
        languages,
    })
    # end: export part

    # start: image gallery part
    # instances = Instance.objects.filter(xform=xform).values('id')
    # instances_list = [instance['id'] for instance in instances]
    # attachments = Attachment.objects.filter(instance__in=instances_list,mimetype__icontains='image').values('media_file')
    # image_list = []
    # for i in attachments:
    #     image = {}
    #     image['url'] = request.build_absolute_uri('/media/'+i['media_file'])
    #     image['title'] = i['media_file'][i['media_file'].rfind('/')+1:]
    #     image_list.append(image)
    # data.update({
    #     'image_list': image_list,
    # })
    # end: image gallery part
    return render(request, "usermodule/custom_project_window.html", data)