<commit_before>import json
import datetime

from django import forms
from django.conf import settings
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from django.utils.html import escape

from publicbody.models import PublicBody
from publicbody.widgets import PublicBodySelect
from foirequest.models import FoiRequest, FoiAttachment


new_publicbody_allowed = settings.FROIDE_CONFIG.get(
        'create_new_publicbody', False)
publicbody_empty = settings.FROIDE_CONFIG.get('publicbody_empty', True)
payment_possible = settings.FROIDE_CONFIG.get('payment_possible', False)


class RequestForm(forms.Form):
    public_body = forms.CharField(widget=PublicBodySelect,
            label=_("Search for a topic or a public body:"),
            required=False)
    subject = forms.CharField(label=_("Subject"),
            widget=forms.TextInput(attrs={'placeholder': _("Subject")}))
    body = forms.CharField(label=_("Body"), 
            widget=forms.Textarea(
            attrs={'placeholder': _("Specify your request here...")}))
    public = forms.BooleanField(required=False, initial=True,
            label=_("This request will be public immediately."))

    def __init__(self, list_of_laws, default_law, hidden, *args, **kwargs):
        super(RequestForm, self).__init__(*args, **kwargs)
        self.list_of_laws = list_of_laws
        self.indexed_laws = dict([(l.pk, l) for l in self.list_of_laws])
        self.default_law = self.indexed_laws[default_law]
        self.fields["law"] = forms.ChoiceField(label=_("Information Law"),
            required=False,
            widget=forms.RadioSelect if not hidden else forms.HiddenInput,
            initial=default_law,
            choices=((l.pk, mark_safe(
                '%(name)s<span class="lawinfo">%(description)s</span>' %
                    {"name": escape(l.name),
                    "description": l.formatted_description
                })) for l in list_of_laws))

    def laws_to_json(self):
        return json.dumps(dict([(l.id, l.as_dict()) for l in self.list_of_laws]))

    def clean_public_body(self):
        pb = self.cleaned_data['public_body']
        if pb == "new":
            if not new_publicbody_allowed:
                raise forms.ValidationError(
                        _("You are not allowed to create a new public body"))
        elif pb == "":
            if not publicbody_empty:
                raise forms.ValidationError(
                        _("You must specify a public body"))
            pb = None
        else:
            try:
                pb_pk = int(pb)
            except ValueError:
                raise forms.ValidationError(_("Invalid value"))
            try:
                public_body = PublicBody.objects.get(pk=pb_pk)
            except PublicBody.DoesNotExist:
                raise forms.ValidationError(_("Invalid value"))
            self.public_body_object = public_body
            self.foi_law_object = public_body.default_law
        return pb
    
    public_body_object = None

    def clean_law_for_public_body(self, public_body):
        return self.clean_law_without_public_body()

    def clean_law_without_public_body(self):
        try:
            law = self.cleaned_data['law']
            law = self.indexed_laws[int(law)]
        except (ValueError, KeyError):
            self._errors["law"] = self.error_class([_("Invalid Information Law")])
            return None
        return law

    def clean(self):
        cleaned = self.cleaned_data
        public_body = cleaned.get("public_body")
        if public_body is not None and (public_body != "new"
                and public_body != ""):
            self.foi_law = self.clean_law_for_public_body(self.public_body_object)
        else:
            self.foi_law = self.clean_law_without_public_body()
        return cleaned

class MessagePublicBodySenderForm(forms.Form):
    sender = forms.IntegerField(label=_("Sending Public Body"),
            widget=PublicBodySelect, min_value=1)

    def __init__(self, message, *args, **kwargs):
        if not "initial" in kwargs:
            if message.sender_public_body:
                kwargs['initial'] = {"sender": message.sender_public_body.id}
        if not "prefix" in kwargs:
            kwargs['prefix'] = "m%d" % message.id
        self.message = message
        super(MessagePublicBodySenderForm, self).__init__(*args, **kwargs)

    def clean_sender(self):
        pk = self.cleaned_data['sender']
        try:
            self._public_body = PublicBody.objects.get(id=pk)
        except PublicBody.DoesNotExist:
            raise forms.ValidationError(_("Invalid value"))
        return pk

    def save(self):
        self.message.sender_public_body = self._public_body
        self.message.save()

class SendMessageForm(forms.Form):
    subject = forms.CharField(label=_("Subject"),
            widget=forms.TextInput(attrs={"class": "long-input"}))
    message = forms.CharField(widget=forms.Textarea,
            label=_("Your message"))

    def __init__(self, foirequest, *args, **kwargs):
        super(SendMessageForm, self).__init__(*args, **kwargs)
        self.foirequest = foirequest
        choices = [(m.id, m.real_sender) for k, m in foirequest.possible_reply_addresses().items()]
        choices.append((0, _("Default address of %(publicbody)s") % {
                "publicbody": foirequest.public_body.name}))
        self.fields['to'] = forms.TypedChoiceField(
                choices=choices, coerce=int, required=True)

    def save(self, user):
        if self.cleaned_data["to"] == 0:
            recipient_name = self.foirequest.public_body.name
            recipient_email = self.foirequest.public_body.email
            recipient_pb = self.foirequest.public_body
        else:
            message = filter(lambda x: x.id == self.cleaned_data["to"],
                    list(self.foirequest.messages))[0]
            recipient_name = message.sender_name<commit_msg>Add i18n label to "To" field of SendMessageForm<commit_after>import json
import datetime

from django import forms
from django.conf import settings
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from django.utils.html import escape

from publicbody.models import PublicBody
from publicbody.widgets import PublicBodySelect
from foirequest.models import FoiRequest, FoiAttachment


new_publicbody_allowed = settings.FROIDE_CONFIG.get(
        'create_new_publicbody', False)
publicbody_empty = settings.FROIDE_CONFIG.get('publicbody_empty', True)
payment_possible = settings.FROIDE_CONFIG.get('payment_possible', False)


class RequestForm(forms.Form):
    public_body = forms.CharField(widget=PublicBodySelect,
            label=_("Search for a topic or a public body:"),
            required=False)
    subject = forms.CharField(label=_("Subject"),
            widget=forms.TextInput(attrs={'placeholder': _("Subject")}))
    body = forms.CharField(label=_("Body"), 
            widget=forms.Textarea(
            attrs={'placeholder': _("Specify your request here...")}))
    public = forms.BooleanField(required=False, initial=True,
            label=_("This request will be public immediately."))

    def __init__(self, list_of_laws, default_law, hidden, *args, **kwargs):
        super(RequestForm, self).__init__(*args, **kwargs)
        self.list_of_laws = list_of_laws
        self.indexed_laws = dict([(l.pk, l) for l in self.list_of_laws])
        self.default_law = self.indexed_laws[default_law]
        self.fields["law"] = forms.ChoiceField(label=_("Information Law"),
            required=False,
            widget=forms.RadioSelect if not hidden else forms.HiddenInput,
            initial=default_law,
            choices=((l.pk, mark_safe(
                '%(name)s<span class="lawinfo">%(description)s</span>' %
                    {"name": escape(l.name),
                    "description": l.formatted_description
                })) for l in list_of_laws))

    def laws_to_json(self):
        return json.dumps(dict([(l.id, l.as_dict()) for l in self.list_of_laws]))

    def clean_public_body(self):
        pb = self.cleaned_data['public_body']
        if pb == "new":
            if not new_publicbody_allowed:
                raise forms.ValidationError(
                        _("You are not allowed to create a new public body"))
        elif pb == "":
            if not publicbody_empty:
                raise forms.ValidationError(
                        _("You must specify a public body"))
            pb = None
        else:
            try:
                pb_pk = int(pb)
            except ValueError:
                raise forms.ValidationError(_("Invalid value"))
            try:
                public_body = PublicBody.objects.get(pk=pb_pk)
            except PublicBody.DoesNotExist:
                raise forms.ValidationError(_("Invalid value"))
            self.public_body_object = public_body
            self.foi_law_object = public_body.default_law
        return pb
    
    public_body_object = None

    def clean_law_for_public_body(self, public_body):
        return self.clean_law_without_public_body()

    def clean_law_without_public_body(self):
        try:
            law = self.cleaned_data['law']
            law = self.indexed_laws[int(law)]
        except (ValueError, KeyError):
            self._errors["law"] = self.error_class([_("Invalid Information Law")])
            return None
        return law

    def clean(self):
        cleaned = self.cleaned_data
        public_body = cleaned.get("public_body")
        if public_body is not None and (public_body != "new"
                and public_body != ""):
            self.foi_law = self.clean_law_for_public_body(self.public_body_object)
        else:
            self.foi_law = self.clean_law_without_public_body()
        return cleaned

class MessagePublicBodySenderForm(forms.Form):
    sender = forms.IntegerField(label=_("Sending Public Body"),
            widget=PublicBodySelect, min_value=1)

    def __init__(self, message, *args, **kwargs):
        if not "initial" in kwargs:
            if message.sender_public_body:
                kwargs['initial'] = {"sender": message.sender_public_body.id}
        if not "prefix" in kwargs:
            kwargs['prefix'] = "m%d" % message.id
        self.message = message
        super(MessagePublicBodySenderForm, self).__init__(*args, **kwargs)

    def clean_sender(self):
        pk = self.cleaned_data['sender']
        try:
            self._public_body = PublicBody.objects.get(id=pk)
        except PublicBody.DoesNotExist:
            raise forms.ValidationError(_("Invalid value"))
        return pk

    def save(self):
        self.message.sender_public_body = self._public_body
        self.message.save()

class SendMessageForm(forms.Form):
    subject = forms.CharField(label=_("Subject"),
            widget=forms.TextInput(attrs={"class": "long-input"}))
    message = forms.CharField(widget=forms.Textarea,
            label=_("Your message"))

    def __init__(self, foirequest, *args, **kwargs):
        super(SendMessageForm, self).__init__(*args, **kwargs)
        self.foirequest = foirequest
        choices = [(m.id, m.real_sender) for k, m in foirequest.possible_reply_addresses().items()]
        choices.append((0, _("Default address of %(publicbody)s") % {
                "publicbody": foirequest.public_body.name}))
        self.fields['to'] = forms.TypedChoiceField(label=_("To"),
                choices=choices, coerce=int, required=True)

    def save(self, user):
        if self.cleaned_data["to"] == 0:
            recipient_name = self.foirequest.public_body.name
            recipient_email = self.foirequest.public_body.email
            recipient_pb = self.foirequest.public_body
        else:
            message = filter(lambda x: x.id == self.cleaned_data["to"],
                    list(self.foirequest.messages))[0]
            recipient_name = message.sender_name
{'fraction_non_alphanumeric': 0.10817547357926222, 'fraction_numerical': 0.0008308408109006315, 'mean_word_length': 2.5696915776986953, 'pattern_counts': {'":': 14, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6058300', 'n_tokens_mistral': 3448, 'n_tokens_neox': 3409, 'n_words': 724}