Пример #1
0
 def test_user_add_crowdform_duplicate_entry(self):
     self._add_crowdform()
     self.assertEqual(self.response.status_code, 302)
     meta = MetaData.crowdform_users(self.xform)
     self.assertEqual(len(meta), 1)
     self._add_crowdform()
     meta = MetaData.crowdform_users(self.xform)
     self.assertEqual(len(meta), 1)
Пример #2
0
 def test_user_add_crowdform_duplicate_entry(self):
     self._add_crowdform()
     self.assertEqual(self.response.status_code, 302)
     meta = MetaData.crowdform_users(self.xform)
     self.assertEqual(len(meta), 1)
     self._add_crowdform()
     meta = MetaData.crowdform_users(self.xform)
     self.assertEqual(len(meta), 1)
Пример #3
0
def edit(request, username, id_string):
    xform = XForm.objects.get(user__username=username, id_string=id_string)

    if request.GET.get("crowdform"):
        crowdform_action = request.GET["crowdform"]
        request_username = request.user.username

        # ensure is crowdform
        if xform.is_crowd_form:
            if crowdform_action == "delete":
                MetaData.objects.get(
                    xform__id_string=id_string, data_value=request_username, data_type=MetaData.CROWDFORM_USERS
                ).delete()
            elif crowdform_action == "add":
                MetaData.crowdform_users(xform, request_username)

            return HttpResponseRedirect(reverse(profile, kwargs={"username": request_username}))

    if username == request.user.username or request.user.has_perm("odk_logger.change_xform", xform):
        if request.POST.get("description"):
            xform.description = request.POST["description"]
        elif request.POST.get("title"):
            xform.title = request.POST["title"]
        elif request.POST.get("toggle_shared"):
            if request.POST["toggle_shared"] == "data":
                xform.shared_data = not xform.shared_data
            elif request.POST["toggle_shared"] == "form":
                xform.shared = not xform.shared
            elif request.POST["toggle_shared"] == "active":
                xform.downloadable = not xform.downloadable
            elif request.POST["toggle_shared"] == "crowd":
                if xform.is_crowd_form:
                    xform.is_crowd_form = False
                else:
                    xform.is_crowd_form = True
                    xform.shared = True
                    xform.shared_data = True
        elif request.POST.get("form-license"):
            MetaData.form_license(xform, request.POST["form-license"])
        elif request.POST.get("data-license"):
            MetaData.data_license(xform, request.POST["data-license"])
        elif request.POST.get("source") or request.FILES.get("source"):
            MetaData.source(xform, request.POST.get("source"), request.FILES.get("source"))
        elif request.FILES.get("media"):
            MetaData.media_upload(xform, request.FILES.get("media"))
        elif request.POST.get("map_name"):
            mapbox_layer = MapboxLayerForm(request.POST)
            if mapbox_layer.is_valid():
                MetaData.mapbox_layer_upload(xform, mapbox_layer.cleaned_data)
        elif request.FILES:
            MetaData.supporting_docs(xform, request.FILES["doc"])
        xform.update()

        if request.is_ajax():
            return HttpResponse(_(u"Updated succeeded."))
        else:
            return HttpResponseRedirect(reverse(show, kwargs={"username": username, "id_string": id_string}))
    return HttpResponseForbidden(_(u"Update failed."))
Пример #4
0
def auto_add_crowd_form_to_registered_user(sender, **kwargs):
    new_user = kwargs.get('user')
    if hasattr(settings, 'AUTO_ADD_CROWDFORM') and \
            settings.AUTO_ADD_CROWDFORM and \
            hasattr(settings, 'DEFAULT_CROWDFORM'):
        try:
            default_crowdform = settings.DEFAULT_CROWDFORM
            if isinstance(default_crowdform, dict) and\
                    'xform_username' in default_crowdform and\
                    'xform_id_string' in default_crowdform:
                xform = XForm.objects.get(
                    id_string=default_crowdform['xform_id_string'],
                    user__username=default_crowdform['xform_username'])
                MetaData.crowdform_users(xform, new_user.username)
        except XForm.DoesNotExist:
            pass
Пример #5
0
def auto_add_crowd_form_to_registered_user(sender, **kwargs):
    new_user = kwargs.get("user")
    if (
        hasattr(settings, "AUTO_ADD_CROWDFORM")
        and settings.AUTO_ADD_CROWDFORM
        and hasattr(settings, "DEFAULT_CROWDFORM")
    ):
        try:
            default_crowdform = settings.DEFAULT_CROWDFORM
            if (
                isinstance(default_crowdform, dict)
                and "xform_username" in default_crowdform
                and "xform_id_string" in default_crowdform
            ):
                xform = XForm.objects.get(
                    id_string=default_crowdform["xform_id_string"], user__username=default_crowdform["xform_username"]
                )
                MetaData.crowdform_users(xform, new_user.username)
        except XForm.DoesNotExist:
            pass
Пример #6
0
 def save(self, profile_callback=None):
     new_user = RegistrationProfile.objects.create_inactive_user(
         username=self.cleaned_data['username'],
         password=self.cleaned_data['password1'],
         email=self.cleaned_data['email'])
     UserProfileFormRegister.save(self, new_user)
     if hasattr(settings, 'AUTO_ADD_CROWDFORM') and \
             settings.AUTO_ADD_CROWDFORM and \
             hasattr(settings, 'DEFAULT_CROWDFORM'):
         try:
             default_crowdform = settings.DEFAULT_CROWDFORM
             if isinstance(default_crowdform, dict) and\
                     default_crowdform.has_key('xform_username') and\
                     default_crowdform.has_key('xform_id_string'):
                 xform = XForm.objects.get(
                     id_string=default_crowdform['xform_id_string'],
                     user__username=default_crowdform['xform_username'])
                 MetaData.crowdform_users(xform, new_user.username)
         except XForm.DoesNotExist:
             pass
     return new_user
Пример #7
0
    def test_crowdform_for_new_user(self):
        # initial
        meta = MetaData.crowdform_users(self.xform)
        self.assertEqual(len(meta), 0)

        #save settings to be restored later
        old_auto_add_cf = settings.AUTO_ADD_CROWDFORM
        old_default_cf = settings.DEFAULT_CROWDFORM

        # enable auto add crowdform
        settings.AUTO_ADD_CROWDFORM = True
        settings.DEFAULT_CROWDFORM = {
            'xform_username': self.user.username,
            'xform_id_string': self.xform.id_string
        }

        # register new user
        post_data = {
            'username': self.alice,
            'email': '*****@*****.**',
            'password1': 'bobbob',
            'password2': 'bobbob',
            'name': 'Alice',
            'city': 'Ecila',
            'country': 'US',
            'organization': 'Alic Inc.',
            'home_page': 'alice.com',
            'twitter': 'alicerama'
        }
        url = '/accounts/register/'
        self.response = self.client.post(url, post_data)

        # check to ensure that crowd form was added
        meta = MetaData.crowdform_users(self.xform)
        self.assertEqual(len(meta), 1)
        self.assertEqual(meta[0].data_value, self.alice)

        # restore old settings
        settings.AUTO_ADD_CROWDFORM = old_auto_add_cf
        settings.DEFAULT_CROWDFORM = old_default_cf
Пример #8
0
    def test_crowdform_for_new_user(self):
        # initial
        meta = MetaData.crowdform_users(self.xform)
        self.assertEqual(len(meta), 0)

        #save settings to be restored later
        old_auto_add_cf = settings.AUTO_ADD_CROWDFORM
        old_default_cf = settings.DEFAULT_CROWDFORM

        # enable auto add crowdform
        settings.AUTO_ADD_CROWDFORM = True
        settings.DEFAULT_CROWDFORM = {
            'xform_username': self.user.username,
            'xform_id_string': self.xform.id_string}

        # register new user
        post_data = {
            'username': self.alice,
            'email': '*****@*****.**',
            'password1': 'bobbob',
            'password2': 'bobbob',
            'name': 'Alice',
            'city': 'Ecila',
            'country': 'US',
            'organization': 'Alic Inc.',
            'home_page': 'alice.com',
            'twitter': 'alicerama'
        }
        url = '/accounts/register/'
        self.response = self.client.post(url, post_data)

        # check to ensure that crowd form was added
        meta = MetaData.crowdform_users(self.xform)
        self.assertEqual(len(meta), 1)
        self.assertEqual(meta[0].data_value, self.alice)

        # restore old settings
        settings.AUTO_ADD_CROWDFORM = old_auto_add_cf
        settings.DEFAULT_CROWDFORM = old_default_cf
Пример #9
0
 def test_user_add_crowdform(self):
     self._add_crowdform()
     self.assertEqual(self.response.status_code, 302)
     meta = MetaData.crowdform_users(self.xform)
     self.assertEqual(len(meta), 1)
     self.assertEqual(meta[0].data_value, self.alice)
Пример #10
0
 def _add_crowdform(self):
     self._create_user_and_login(self.alice, self.alice)
     self.assertEqual(len(MetaData.crowdform_users(self.xform)),
                      self.crowdform_count)
     self.response = self.client.get(self.edit_url, {'crowdform': 'add'})
     self.crowdform_count += 1
Пример #11
0
 def test_user_delete_crowdform(self):
     self._add_crowdform()
     self.response = self.client.get(self.edit_url, {'crowdform': 'delete'})
     meta = MetaData.crowdform_users(self.xform)
     self.assertEqual(len(meta), 0)
     self.assertEqual(self.response.status_code, 302)
Пример #12
0
def edit(request, username, id_string):
    xform = XForm.objects.get(user__username=username, id_string=id_string)

    if request.GET.get('crowdform'):
        crowdform_action = request.GET['crowdform']
        request_username = request.user.username

        # ensure is crowdform
        if xform.is_crowd_form:
            if crowdform_action == 'delete':
                MetaData.objects.get(
                    xform__id_string=id_string,
                    data_value=request_username,
                    data_type=MetaData.CROWDFORM_USERS
                ).delete()
            elif crowdform_action == 'add':
                MetaData.crowdform_users(xform, request_username)

            return HttpResponseRedirect(reverse(profile, kwargs={
                'username': request_username
            }))

    if username == request.user.username or\
            request.user.has_perm('odk_logger.change_xform', xform):
        if request.POST.get('description'):
            xform.description = request.POST['description']
        elif request.POST.get('title'):
            xform.title = request.POST['title']
        elif request.POST.get('toggle_shared'):
            if request.POST['toggle_shared'] == 'data':
                xform.shared_data = not xform.shared_data
            elif request.POST['toggle_shared'] == 'form':
                xform.shared = not xform.shared
            elif request.POST['toggle_shared'] == 'active':
                xform.downloadable = not xform.downloadable
            elif request.POST['toggle_shared'] == 'crowd':
                if xform.is_crowd_form:
                    xform.is_crowd_form = False
                else:
                    xform.is_crowd_form = True
                    xform.shared = True
                    xform.shared_data = True
        elif request.POST.get('form-license'):
            MetaData.form_license(xform, request.POST['form-license'])
        elif request.POST.get('data-license'):
            MetaData.data_license(xform, request.POST['data-license'])
        elif request.POST.get('source') or request.FILES.get('source'):
            MetaData.source(xform, request.POST.get('source'),
                            request.FILES.get('source'))
        elif request.FILES.get('media'):
            MetaData.media_upload(xform, request.FILES.get('media'))
        elif request.POST.get('map_name'):
            mapbox_layer = MapboxLayerForm(request.POST)
            if mapbox_layer.is_valid():
                MetaData.mapbox_layer_upload(xform, mapbox_layer.cleaned_data)
        elif request.FILES:
            MetaData.supporting_docs(xform, request.FILES['doc'])
        xform.update()

        if request.is_ajax():
            return HttpResponse(_(u'Updated succeeded.'))
        else:
            return HttpResponseRedirect(reverse(show, kwargs={
                'username': username,
                'id_string': id_string
            }))
    return HttpResponseForbidden(_(u'Update failed.'))
Пример #13
0
 def test_user_delete_crowdform(self):
     self._add_crowdform()
     self.response = self.client.get(self.edit_url, {'crowdform': 'delete'})
     meta = MetaData.crowdform_users(self.xform)
     self.assertEqual(len(meta), 0)
     self.assertEqual(self.response.status_code, 302)
Пример #14
0
 def test_user_add_crowdform(self):
     self._add_crowdform()
     self.assertEqual(self.response.status_code, 302)
     meta = MetaData.crowdform_users(self.xform)
     self.assertEqual(len(meta), 1)
     self.assertEqual(meta[0].data_value, self.alice)
Пример #15
0
 def _add_crowdform(self):
     self._create_user_and_login(self.alice, self.alice)
     self.assertEqual(len(MetaData.crowdform_users(self.xform)),
                      self.crowdform_count)
     self.response = self.client.get(self.edit_url, {'crowdform': 'add'})
     self.crowdform_count += 1
Пример #16
0
def edit(request, username, id_string):
    
    xform = XForm.objects.get(user__username=username, id_string=id_string)
    owner = xform.user

    if request.GET.get('crowdform'):
        crowdform_action = request.GET['crowdform']
        request_username = request.user.username

        # ensure is crowdform
        if xform.is_crowd_form:
            if crowdform_action == 'delete':
                MetaData.objects.get(
                    xform__id_string=id_string,
                    data_value=request_username,
                    data_type=MetaData.CROWDFORM_USERS
                ).delete()
            elif crowdform_action == 'add':
                MetaData.crowdform_users(xform, request_username)

            return HttpResponseRedirect(reverse(profile, kwargs={
                'username': request_username
            }))

    if username == request.user.username or\
            request.user.has_perm('odk_logger.change_xform', xform):
        if request.POST.get('description'):
            audit = {
                'xform': xform.id_string
            }
            audit_log(
                Actions.FORM_UPDATED, request.user, owner,
                _("Description for '%(id_string)s' updated from "
                    "'%(old_description)s' to '%(new_description)s'.") %
                {
                    'id_string': xform.id_string,
                    'old_description': xform.description,
                    'new_description': request.POST['description']
                }, audit, request)
            xform.description = request.POST['description']
        elif request.POST.get('title'):
            audit = {
                'xform': xform.id_string
            }
            audit_log(
                Actions.FORM_UPDATED, request.user, owner,
                _("Title for '%(id_string)s' updated from "
                    "'%(old_title)s' to '%(new_title)s'.") %
                {
                    'id_string': xform.id_string,
                    'old_title': xform.title,
                    'new_title': request.POST.get('title')
                }, audit, request)
            xform.title = request.POST['title']
        elif request.POST.get('settings_form'):
            #white list of fields that can be changed
            settings = ('shared', 'shared_data', 'form_active', 'is_crowd_form')
            for setting in settings:
                new_state = request.POST.get(setting, 'off') == 'on'
                old_state = getattr(xform, setting)
                if new_state != old_state:
                    audit = {
                        'xform': xform.id_string
                    }
                    audit_log(
                        Actions.FORM_UPDATED, request.user, owner,
                        _("'%(field_name)s' for '%(id_string)s' updated from "
                            "'%(old_value)s' to '%(new_value)s'.") %
                        {
                            'field_name': setting,
                            'id_string': xform.id_string,
                            'old_value': str(old_state),
                            'new_value': str(new_state)
                        }, audit, request)
                    setattr(xform, setting, new_state)
                    if setting == 'is_crowd_form' and new_state:
                        xform.shared = xform.shared_data = True  # crowd forms must be shared.

        elif request.POST.get('form-license'):
            audit = {
                'xform': xform.id_string
            }
            audit_log(
                Actions.FORM_UPDATED, request.user, owner,
                _("Form License for '%(id_string)s' updated to "
                    "'%(form_license)s'.") %
                {
                    'id_string': xform.id_string,
                    'form_license': request.POST['form-license'],
                }, audit, request)
            MetaData.form_license(xform, request.POST['form-license'])
        elif request.POST.get('data-license'):
            audit = {
                'xform': xform.id_string
            }
            audit_log(
                Actions.FORM_UPDATED, request.user, owner,
                _("Data license for '%(id_string)s' updated to "
                    "'%(data_license)s'.") %
                {
                    'id_string': xform.id_string,
                    'data_license': request.POST['data-license'],
                }, audit, request)
            MetaData.data_license(xform, request.POST['data-license'])
        elif request.POST.get('source') or request.FILES.get('source'):
            audit = {
                'xform': xform.id_string
            }
            audit_log(
                Actions.FORM_UPDATED, request.user, owner,
                _("Source for '%(id_string)s' updated to '%(source)s'.") %
                {
                    'id_string': xform.id_string,
                    'source': request.POST.get('source'),
                }, audit, request)
            MetaData.source(xform, request.POST.get('source'),
                            request.FILES.get('source'))
        elif request.POST.get('enable_sms_support_trigger') is not None:
            sms_support_form = ActivateSMSSupportFom(request.POST)
            if sms_support_form.is_valid():
                audit = {
                    'xform': xform.id_string
                }
                enabled = \
                    sms_support_form.cleaned_data.get('enable_sms_support')
                if enabled:
                    audit_action = Actions.SMS_SUPPORT_ACTIVATED
                    audit_message = _(u"SMS Support Activated on")
                else:
                    audit_action = Actions.SMS_SUPPORT_DEACTIVATED
                    audit_message = _(u"SMS Support Deactivated on")
                audit_log(
                    audit_action, request.user, owner,
                    audit_message
                    % {'id_string': xform.id_string}, audit, request)
                # stored previous states to be able to rollback form status
                # in case we can't save.
                pe = xform.allows_sms
                pid = xform.sms_id_string
                xform.allows_sms = enabled
                xform.sms_id_string = \
                    sms_support_form.cleaned_data.get('sms_id_string')
                compat = check_form_sms_compatibility(None,
                                                      json.loads(xform.json))
                if compat['type'] == 'alert-error':
                    xform.allows_sms = False
                    xform.sms_id_string = pid
                try:
                    xform.save()
                except IntegrityError:
                    # unfortunately, there's no feedback mechanism here
                    xform.allows_sms = pe
                    xform.sms_id_string = pid

        elif request.FILES.get('media'):
            audit = {
                'xform': xform.id_string
            }
            audit_log(
                Actions.FORM_UPDATED, request.user, owner,
                _("Media added to '%(id_string)s'.") %
                {
                    'id_string': xform.id_string
                }, audit, request)
            for aFile in request.FILES.getlist("media"):
                MetaData.media_upload(xform, aFile)
        elif request.POST.get('map_name'):
            mapbox_layer = MapboxLayerForm(request.POST)
            if mapbox_layer.is_valid():
                audit = {
                    'xform': xform.id_string
                }
                audit_log(
                    Actions.FORM_UPDATED, request.user, owner,
                    _("Map layer added to '%(id_string)s'.") %
                    {
                        'id_string': xform.id_string
                    }, audit, request)
                MetaData.mapbox_layer_upload(xform, mapbox_layer.cleaned_data)
        elif request.FILES:
            audit = {
                'xform': xform.id_string
            }
            audit_log(
                Actions.FORM_UPDATED, request.user, owner,
                _("Supporting document added to '%(id_string)s'.") %
                {
                    'id_string': xform.id_string
                }, audit, request)
            MetaData.supporting_docs(xform, request.FILES['doc'])

        xform.update()

        if request.is_ajax():
            return HttpResponse(_(u'Update succeeded.'))
        else:
            return HttpResponseRedirect(reverse(show, kwargs={
                'username': username,
                'id_string': id_string
            }))
    return HttpResponseForbidden(_(u'Update failed.'))
Пример #17
0
def edit(request, username, id_string):
    xform = XForm.objects.get(user__username=username, id_string=id_string)
    owner = xform.user

    if request.GET.get("crowdform"):
        crowdform_action = request.GET["crowdform"]
        request_username = request.user.username

        # ensure is crowdform
        if xform.is_crowd_form:
            if crowdform_action == "delete":
                MetaData.objects.get(
                    xform__id_string=id_string, data_value=request_username, data_type=MetaData.CROWDFORM_USERS
                ).delete()
            elif crowdform_action == "add":
                MetaData.crowdform_users(xform, request_username)

            return HttpResponseRedirect(reverse(profile, kwargs={"username": request_username}))

    if username == request.user.username or request.user.has_perm("odk_logger.change_xform", xform):
        if request.POST.get("description"):
            audit = {"xform": xform.id_string}
            audit_log(
                Actions.FORM_UPDATED,
                request.user,
                owner,
                _("Description for '%(id_string)s' updated from " "'%(old_description)s' to '%(new_description)s'.")
                % {
                    "id_string": xform.id_string,
                    "old_description": xform.description,
                    "new_description": request.POST["description"],
                },
                audit,
                request,
            )
            xform.description = request.POST["description"]
        elif request.POST.get("title"):
            audit = {"xform": xform.id_string}
            audit_log(
                Actions.FORM_UPDATED,
                request.user,
                owner,
                _("Title for '%(id_string)s' updated from " "'%(old_title)s' to '%(new_title)s'.")
                % {"id_string": xform.id_string, "old_title": xform.title, "new_title": request.POST.get("title")},
                audit,
                request,
            )
            xform.title = request.POST["title"]
        elif request.POST.get("toggle_shared"):
            if request.POST["toggle_shared"] == "data":
                audit = {"xform": xform.id_string}
                audit_log(
                    Actions.FORM_UPDATED,
                    request.user,
                    owner,
                    _("Data sharing updated for '%(id_string)s' from " "'%(old_shared)s' to '%(new_shared)s'.")
                    % {
                        "id_string": xform.id_string,
                        "old_shared": _("shared") if xform.shared_data else _("not shared"),
                        "new_shared": _("shared") if not xform.shared_data else _("not shared"),
                    },
                    audit,
                    request,
                )
                xform.shared_data = not xform.shared_data
            elif request.POST["toggle_shared"] == "form":
                audit = {"xform": xform.id_string}
                audit_log(
                    Actions.FORM_UPDATED,
                    request.user,
                    owner,
                    _("Form sharing for '%(id_string)s' updated " "from '%(old_shared)s' to '%(new_shared)s'.")
                    % {
                        "id_string": xform.id_string,
                        "old_shared": _("shared") if xform.shared else _("not shared"),
                        "new_shared": _("shared") if not xform.shared else _("not shared"),
                    },
                    audit,
                    request,
                )
                xform.shared = not xform.shared
            elif request.POST["toggle_shared"] == "active":
                audit = {"xform": xform.id_string}
                audit_log(
                    Actions.FORM_UPDATED,
                    request.user,
                    owner,
                    _("Active status for '%(id_string)s' updated from " "'%(old_shared)s' to '%(new_shared)s'.")
                    % {
                        "id_string": xform.id_string,
                        "old_shared": _("shared") if xform.downloadable else _("not shared"),
                        "new_shared": _("shared") if not xform.downloadable else _("not shared"),
                    },
                    audit,
                    request,
                )
                xform.downloadable = not xform.downloadable
            elif request.POST["toggle_shared"] == "crowd":
                audit = {"xform": xform.id_string}
                audit_log(
                    Actions.FORM_UPDATED,
                    request.user,
                    owner,
                    _("Crowdform status for '%(id_string)s' updated from " "'%(old_status)s' to '%(new_status)s'.")
                    % {
                        "id_string": xform.id_string,
                        "old_status": _("crowdform") if not xform.is_crowd_form else _("not crowdform"),
                        "new_status": _("crowdform") if xform.is_crowd_form else _("not crowdform"),
                    },
                    audit,
                    request,
                )
                if xform.is_crowd_form:
                    xform.is_crowd_form = False
                else:
                    xform.is_crowd_form = True
                    xform.shared = True
                    xform.shared_data = True
        elif request.POST.get("form-license"):
            audit = {"xform": xform.id_string}
            audit_log(
                Actions.FORM_UPDATED,
                request.user,
                owner,
                _("Form License for '%(id_string)s' updated to " "'%(form_license)s'.")
                % {"id_string": xform.id_string, "form_license": request.POST["form-license"]},
                audit,
                request,
            )
            MetaData.form_license(xform, request.POST["form-license"])
        elif request.POST.get("data-license"):
            audit = {"xform": xform.id_string}
            audit_log(
                Actions.FORM_UPDATED,
                request.user,
                owner,
                _("Data license for '%(id_string)s' updated to " "'%(data_license)s'.")
                % {"id_string": xform.id_string, "data_license": request.POST["data-license"]},
                audit,
                request,
            )
            MetaData.data_license(xform, request.POST["data-license"])
        elif request.POST.get("source") or request.FILES.get("source"):
            audit = {"xform": xform.id_string}
            audit_log(
                Actions.FORM_UPDATED,
                request.user,
                owner,
                _("Source for '%(id_string)s' updated to '%(source)s'.")
                % {"id_string": xform.id_string, "source": request.POST.get("source")},
                audit,
                request,
            )
            MetaData.source(xform, request.POST.get("source"), request.FILES.get("source"))
        elif request.POST.get("enable_sms_support_trigger") is not None:
            sms_support_form = ActivateSMSSupportFom(request.POST)
            if sms_support_form.is_valid():
                audit = {"xform": xform.id_string}
                enabled = sms_support_form.cleaned_data.get("enable_sms_support")
                if enabled:
                    audit_action = Actions.SMS_SUPPORT_ACTIVATED
                    audit_message = _(u"SMS Support Activated on")
                else:
                    audit_action = Actions.SMS_SUPPORT_DEACTIVATED
                    audit_message = _(u"SMS Support Deactivated on")
                audit_log(
                    audit_action, request.user, owner, audit_message % {"id_string": xform.id_string}, audit, request
                )
                # stored previous states to be able to rollback form status
                # in case we can't save.
                pe = xform.allows_sms
                pid = xform.sms_id_string
                xform.allows_sms = enabled
                xform.sms_id_string = sms_support_form.cleaned_data.get("sms_id_string")
                compat = check_form_sms_compatibility(None, json.loads(xform.json))
                if compat["type"] == "alert-error":
                    xform.allows_sms = False
                    xform.sms_id_string = pid
                try:
                    xform.save()
                except IntegrityError:
                    # unfortunately, there's no feedback mechanism here
                    xform.allows_sms = pe
                    xform.sms_id_string = pid

        elif request.FILES.get("media"):
            audit = {"xform": xform.id_string}
            audit_log(
                Actions.FORM_UPDATED,
                request.user,
                owner,
                _("Media added to '%(id_string)s'.") % {"id_string": xform.id_string},
                audit,
                request,
            )
            for aFile in request.FILES.getlist("media"):
                MetaData.media_upload(xform, aFile)
        elif request.POST.get("map_name"):
            mapbox_layer = MapboxLayerForm(request.POST)
            if mapbox_layer.is_valid():
                audit = {"xform": xform.id_string}
                audit_log(
                    Actions.FORM_UPDATED,
                    request.user,
                    owner,
                    _("Map layer added to '%(id_string)s'.") % {"id_string": xform.id_string},
                    audit,
                    request,
                )
                MetaData.mapbox_layer_upload(xform, mapbox_layer.cleaned_data)
        elif request.FILES:
            audit = {"xform": xform.id_string}
            audit_log(
                Actions.FORM_UPDATED,
                request.user,
                owner,
                _("Supporting document added to '%(id_string)s'.") % {"id_string": xform.id_string},
                audit,
                request,
            )
            MetaData.supporting_docs(xform, request.FILES["doc"])
        xform.update()

        if request.is_ajax():
            return HttpResponse(_(u"Updated succeeded."))
        else:
            return HttpResponseRedirect(reverse(show, kwargs={"username": username, "id_string": id_string}))
    return HttpResponseForbidden(_(u"Update failed."))
Пример #18
0
def edit(request, username, id_string):
    xform = XForm.objects.get(user__username=username, id_string=id_string)
    owner = xform.user

    if request.GET.get('crowdform'):
        crowdform_action = request.GET['crowdform']
        request_username = request.user.username

        # ensure is crowdform
        if xform.is_crowd_form:
            if crowdform_action == 'delete':
                MetaData.objects.get(
                    xform__id_string=id_string,
                    data_value=request_username,
                    data_type=MetaData.CROWDFORM_USERS
                ).delete()
            elif crowdform_action == 'add':
                MetaData.crowdform_users(xform, request_username)

            return HttpResponseRedirect(reverse(profile, kwargs={
                'username': request_username
            }))

    if username == request.user.username or\
            request.user.has_perm('odk_logger.change_xform', xform):
        if request.POST.get('description'):
            audit = {
                'xform': xform.id_string
            }
            audit_log(Actions.FORM_UPDATED, request.user, owner,
                _("Description for '%(id_string)s' updated from '%(old_description)s' to '%(new_description)s'.") %\
                {
                    'id_string': xform.id_string,
                    'old_description': xform.description,
                    'new_description': request.POST['description']
                }, audit, request)
            xform.description = request.POST['description']
        elif request.POST.get('title'):
            audit = {
                'xform': xform.id_string
            }
            audit_log(Actions.FORM_UPDATED, request.user, owner,
                _("Title for '%(id_string)s' updated from '%(old_title)s' to '%(new_title)s'.") %\
                {
                    'id_string': xform.id_string,
                    'old_title': xform.title,
                    'new_title': request.POST.get('title')
                }, audit, request)
            xform.title = request.POST['title']
        elif request.POST.get('toggle_shared'):
            if request.POST['toggle_shared'] == 'data':
                audit = {
                    'xform': xform.id_string
                }
                audit_log(Actions.FORM_UPDATED, request.user, owner,
                    _("Data sharing updated for '%(id_string)s' from '%(old_shared)s' to '%(new_shared)s'.") %\
                    {
                        'id_string': xform.id_string,
                        'old_shared': _("shared") if xform.shared_data else _("not shared"),
                        'new_shared': _("shared") if not xform.shared_data else _("not shared")
                    }, audit, request)
                xform.shared_data = not xform.shared_data
            elif request.POST['toggle_shared'] == 'form':
                audit = {
                    'xform': xform.id_string
                }
                audit_log(Actions.FORM_UPDATED, request.user, owner,
                    _("Form sharing for '%(id_string)s' updated from '%(old_shared)s' to '%(new_shared)s'.") %\
                    {
                        'id_string': xform.id_string,
                        'old_shared': _("shared") if xform.shared else _("not shared"),
                        'new_shared': _("shared") if not xform.shared else _("not shared")
                    }, audit, request)
                xform.shared = not xform.shared
            elif request.POST['toggle_shared'] == 'active':
                audit = {
                    'xform': xform.id_string
                }
                audit_log(Actions.FORM_UPDATED, request.user, owner,
                    _("Active status for '%(id_string)s' updated from '%(old_shared)s' to '%(new_shared)s'.") %\
                    {
                        'id_string': xform.id_string,
                        'old_shared': _("shared") if xform.downloadable else _("not shared"),
                        'new_shared': _("shared") if not xform.downloadable else _("not shared")
                    }, audit, request)
                xform.downloadable = not xform.downloadable
            elif request.POST['toggle_shared'] == 'crowd':
                audit = {
                    'xform': xform.id_string
                }
                audit_log(Actions.FORM_UPDATED, request.user, owner,
                    _("Crowdform status for '%(id_string)s' updated from '%(old_status)s' to '%(new_status)s'.") %\
                    {
                        'id_string': xform.id_string,
                        'old_status': _("crowdform") if not xform.is_crowd_form else _("not crowdform"),
                        'new_status': _("crowdform") if xform.is_crowd_form else _("not crowdform"),
                    }, audit, request)
                if xform.is_crowd_form:
                    xform.is_crowd_form = False
                else:
                    xform.is_crowd_form = True
                    xform.shared = True
                    xform.shared_data = True
        elif request.POST.get('form-license'):
            audit = {
                'xform': xform.id_string
            }
            audit_log(Actions.FORM_UPDATED, request.user, owner,
                _("Form License for '%(id_string)s' updated to '%(form_license)s'.") %\
                {
                    'id_string': xform.id_string,
                    'form_license': request.POST['form-license'],
                }, audit, request)
            MetaData.form_license(xform, request.POST['form-license'])
        elif request.POST.get('data-license'):
            audit = {
                'xform': xform.id_string
            }
            audit_log(Actions.FORM_UPDATED, request.user, owner,
                _("Data license for '%(id_string)s' updated to '%(data_license)s'.") %\
                {
                    'id_string': xform.id_string,
                    'data_license': request.POST['data-license'],
                }, audit, request)
            MetaData.data_license(xform, request.POST['data-license'])
        elif request.POST.get('source') or request.FILES.get('source'):
            audit = {
                'xform': xform.id_string
            }
            audit_log(Actions.FORM_UPDATED, request.user, owner,
                _("Source for '%(id_string)s' updated to '%(source)s'.") %\
                {
                    'id_string': xform.id_string,
                    'source': request.POST.get('source'),
                }, audit, request)
            MetaData.source(xform, request.POST.get('source'),
                            request.FILES.get('source'))
        elif request.FILES.get('media'):
            audit = {
                'xform': xform.id_string
            }
            audit_log(Actions.FORM_UPDATED, request.user, owner,
                _("Media added to '%(id_string)s'.") %\
                {
                    'id_string': xform.id_string
                }, audit, request)
            MetaData.media_upload(xform, request.FILES.get('media'))
        elif request.POST.get('map_name'):
            mapbox_layer = MapboxLayerForm(request.POST)
            if mapbox_layer.is_valid():
                audit = {
                    'xform': xform.id_string
                }
                audit_log(Actions.FORM_UPDATED, request.user, owner,
                    _("Map layer added to '%(id_string)s'.") %\
                    {
                        'id_string': xform.id_string
                    }, audit, request)
                MetaData.mapbox_layer_upload(xform, mapbox_layer.cleaned_data)
        elif request.FILES:
            audit = {
                'xform': xform.id_string
            }
            audit_log(Actions.FORM_UPDATED, request.user, owner,
                _("Supporting document added to '%(id_string)s'.") %\
                {
                    'id_string': xform.id_string
                }, audit, request)
            MetaData.supporting_docs(xform, request.FILES['doc'])
        xform.update()

        if request.is_ajax():
            return HttpResponse(_(u'Updated succeeded.'))
        else:
            return HttpResponseRedirect(reverse(show, kwargs={
                'username': username,
                'id_string': id_string
            }))
    return HttpResponseForbidden(_(u'Update failed.'))