We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
In auto-reply message form, some issue around AM/PM datetime picker
In auto-reply message form, some issue around AM/PM datetime picker
![capture d ecran 2015-04-29 a 15 18 23](https://cloud.githubusercontent.com/assets/230143/7391824/07cfbbfa-ee84-11e4-950c-a3a34fd2c6e4.png)

I can't select AM or PM.

Suggest : enable 24h format


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `modoboa/extensions/postfix_autoreply/forms.py`
Content:
```
1 # coding: utf-8
2 from django import forms
3 from django.utils.translation import ugettext as _, ugettext_lazy
4 from django.utils import timezone
5 from .models import ARmessage
6 
7 
8 class ARmessageForm(forms.ModelForm):
9     fromdate = forms.DateTimeField(
10         label=ugettext_lazy('From'),
11         required=False,
12         help_text=ugettext_lazy("Activate your auto reply from this date"),
13         widget=forms.TextInput(
14             attrs={'class': 'datefield form-control', 'readonly': 'readonly'}
15         )
16     )
17     untildate = forms.DateTimeField(
18         label=ugettext_lazy('Until'),
19         required=False,
20         help_text=ugettext_lazy("Activate your auto reply until this date"),
21         widget=forms.TextInput(
22             attrs={'class': 'datefield form-control', 'readonly': 'readonly'}
23         )
24     )
25     subject = forms.CharField(
26             widget=forms.TextInput(
27                     attrs={'class': 'form-control'}
28                 )
29     )
30     content = forms.CharField(
31                 widget=forms.Textarea(
32                         attrs={'class': 'form-control'}
33                     )
34         )
35 
36     class Meta:
37         model = ARmessage
38         fields = ('subject', 'content', 'enabled')
39 
40     def __init__(self, *args, **kwargs):
41         super(ARmessageForm, self).__init__(*args, **kwargs)
42         self.fields.keyOrder = [
43             'subject', 'content', 'fromdate', 'untildate', 'enabled'
44         ]
45         if 'instance' in kwargs and kwargs['instance'] is not None:
46             self.fields['fromdate'].initial = \
47                 kwargs['instance'].fromdate.replace(second=0, microsecond=0)
48             self.fields['untildate'].initial = kwargs['instance'].untildate
49 
50     def clean(self):
51         """Custom fields validaton.
52 
53         We want to be sure that fromdate < untildate and that they are
54         both in the future ONLY IF the autoreply is beeing activated.
55 
56         """
57         super(ARmessageForm, self).clean()
58         if self._errors:
59             raise forms.ValidationError(self._errors)
60         if not self.cleaned_data["enabled"]:
61             return self.cleaned_data
62         if self.cleaned_data["fromdate"] is not None:
63             if self.cleaned_data["fromdate"] < timezone.now():
64                 self._errors["fromdate"] = self.error_class(
65                     [_("This date is over")])
66                 del self.cleaned_data['fromdate']
67         else:
68             self.cleaned_data['fromdate'] = timezone.now()
69         if self.cleaned_data["untildate"] is not None:
70             if self.cleaned_data["untildate"] < timezone.now():
71                 self._errors["untildate"] = self.error_class(
72                     [_("This date is over")])
73                 del self.cleaned_data['untildate']
74             elif 'fromdate' in self.cleaned_data and \
75                     self.cleaned_data['untildate'] < self.cleaned_data['fromdate']:
76                 self._errors["untildate"] = \
77                     self.error_class([_("Must be greater than start date")])
78                 del self.cleaned_data['untildate']
79         return self.cleaned_data
80
```

Path: `modoboa/extensions/postfix_autoreply/general_callbacks.py`
Content:
```
1 from django.utils import timezone
2 from django.utils.translation import ugettext_lazy
3 from modoboa.lib import events, parameters
4 from modoboa.extensions.postfix_autoreply.models import Transport, Alias
5 from .models import ARmessage
6 
7 
8 @events.observe("ExtraUprefsJS")
9 def extra_js(user):
10     return ["""function autoreply_cb() {
11     $('.datefield').datetimepicker({
12         format: 'YYYY-MM-DD hh:mm:ss',
13         language: '%(lang)s'
14     });
15 }
16 """ % {'lang': parameters.get_user(user, "LANG", app="core")}
17     ]
18 
19 
20 @events.observe("UserMenuDisplay")
21 def menu(target, user):
22     if target != "uprefs_menu":
23         return []
24     if not user.mailbox_set.count():
25         return []
26     return [
27         {"name": "autoreply",
28          "class": "ajaxnav",
29          "url": "autoreply/",
30          "label": ugettext_lazy("Auto-reply message")}
31     ]
32 
33 
34 @events.observe("DomainCreated")
35 def onDomainCreated(user, domain):
36     transport = Transport()
37     transport.domain = "autoreply.%s" % domain.name
38     transport.method = "autoreply:"
39     transport.save()
40 
41 
42 @events.observe("DomainModified")
43 def onDomainModified(domain):
44     if domain.oldname == domain.name:
45         return
46     Transport.objects.filter(domain="autoreply.%s" % domain.oldname) \
47         .update(domain="autoreply.%s" % domain.name)
48     for al in Alias.objects.filter(full_address__contains="@%s" % domain.oldname):
49         new_address = al.full_address.replace("@%s" % domain.oldname, "@%s" % domain.name)
50         al.full_address = new_address
51         al.autoreply_address = "%s@autoreply.%s" % (new_address, domain.name)
52         al.save()
53 
54 
55 @events.observe("DomainDeleted")
56 def onDomainDeleted(domain):
57     Transport.objects.filter(domain="autoreply.%s" % domain.name).delete()
58 
59 
60 @events.observe("MailboxCreated")
61 def onMailboxCreated(user, mailbox):
62     alias = Alias()
63     alias.full_address = mailbox.full_address
64     alias.autoreply_address = \
65         "%s@autoreply.%s" % (mailbox.full_address, mailbox.domain.name)
66     alias.save()
67 
68 
69 @events.observe("MailboxDeleted")
70 def onMailboxDeleted(mailboxes):
71     from modoboa.extensions.admin.models import Mailbox
72 
73     if isinstance(mailboxes, Mailbox):
74         mailboxes = [mailboxes]
75     for mailbox in mailboxes:
76         try:
77             alias = Alias.objects.get(full_address=mailbox.full_address)
78         except Alias.DoesNotExist:
79             pass
80         else:
81             alias.delete()
82 
83 
84 @events.observe("MailboxModified")
85 def onMailboxModified(mailbox):
86     if not hasattr(mailbox, 'old_full_address'):
87         return
88     if mailbox.full_address == mailbox.old_full_address:
89         return
90     alias = Alias.objects.get(full_address=mailbox.old_full_address)
91     alias.full_address = mailbox.full_address
92     alias.autoreply_address =  \
93         "%s@autoreply.%s" % (mailbox.full_address, mailbox.domain.name)
94     alias.save()
95 
96 
97 @events.observe("ExtraFormFields")
98 def extra_mailform_fields(form_name, mailbox=None):
99     """Define extra fields to include in mail forms.
100 
101     For now, only the auto-reply state can be modified.
102 
103     :param str form_name: form name (must be 'mailform')
104     :param Mailbox mailbox: mailbox
105     """
106     from modoboa.lib.formutils import YesNoField
107 
108     if form_name != "mailform":
109         return []
110     status = False
111     if mailbox is not None and mailbox.armessage_set.count():
112         status = mailbox.armessage_set.all()[0].enabled
113     return [
114         ('autoreply', YesNoField(
115             label=ugettext_lazy("Enable auto-reply"),
116             initial="yes" if status else "no",
117             help_text=ugettext_lazy("Enable or disable Postfix auto-reply")
118         ))
119     ]
120 
121 
122 @events.observe("SaveExtraFormFields")
123 def save_extra_mailform_fields(form_name, mailbox, values):
124     """Set the auto-reply status for a mailbox.
125 
126     If a corresponding auto-reply message exists, we update its
127     status. Otherwise, we create a message using default values.
128 
129     :param str form_name: form name (must be 'mailform')
130     :param Mailbox mailbox: mailbox
131     :param dict values: form values
132     """
133     if form_name != 'mailform':
134         return
135     if mailbox.armessage_set.count():
136         arm = mailbox.armessage_set.all()[0]
137     else:
138         arm = ARmessage(mbox=mailbox)
139         arm.subject = parameters.get_admin("DEFAULT_SUBJECT")
140         arm.content = parameters.get_admin("DEFAULT_CONTENT") \
141             % {'name': mailbox.user.fullname}
142         arm.fromdate = timezone.now()
143     arm.enabled = True if values['autoreply'] == 'yes' else False
144     arm.save()
145
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/modoboa/extensions/postfix_autoreply/forms.py b/modoboa/extensions/postfix_autoreply/forms.py
--- a/modoboa/extensions/postfix_autoreply/forms.py
+++ b/modoboa/extensions/postfix_autoreply/forms.py
@@ -11,7 +11,7 @@
         required=False,
         help_text=ugettext_lazy("Activate your auto reply from this date"),
         widget=forms.TextInput(
-            attrs={'class': 'datefield form-control', 'readonly': 'readonly'}
+            attrs={'class': 'datefield form-control'}
         )
     )
     untildate = forms.DateTimeField(
@@ -19,7 +19,7 @@
         required=False,
         help_text=ugettext_lazy("Activate your auto reply until this date"),
         widget=forms.TextInput(
-            attrs={'class': 'datefield form-control', 'readonly': 'readonly'}
+            attrs={'class': 'datefield form-control'}
         )
     )
     subject = forms.CharField(
diff --git a/modoboa/extensions/postfix_autoreply/general_callbacks.py b/modoboa/extensions/postfix_autoreply/general_callbacks.py
--- a/modoboa/extensions/postfix_autoreply/general_callbacks.py
+++ b/modoboa/extensions/postfix_autoreply/general_callbacks.py
@@ -9,7 +9,7 @@
 def extra_js(user):
     return ["""function autoreply_cb() {
     $('.datefield').datetimepicker({
-        format: 'YYYY-MM-DD hh:mm:ss',
+        format: 'YYYY-MM-DD HH:mm:ss',
         language: '%(lang)s'
     });
 }

{"golden_diff": "diff --git a/modoboa/extensions/postfix_autoreply/forms.py b/modoboa/extensions/postfix_autoreply/forms.py\n--- a/modoboa/extensions/postfix_autoreply/forms.py\n+++ b/modoboa/extensions/postfix_autoreply/forms.py\n@@ -11,7 +11,7 @@\n         required=False,\n         help_text=ugettext_lazy(\"Activate your auto reply from this date\"),\n         widget=forms.TextInput(\n-            attrs={'class': 'datefield form-control', 'readonly': 'readonly'}\n+            attrs={'class': 'datefield form-control'}\n         )\n     )\n     untildate = forms.DateTimeField(\n@@ -19,7 +19,7 @@\n         required=False,\n         help_text=ugettext_lazy(\"Activate your auto reply until this date\"),\n         widget=forms.TextInput(\n-            attrs={'class': 'datefield form-control', 'readonly': 'readonly'}\n+            attrs={'class': 'datefield form-control'}\n         )\n     )\n     subject = forms.CharField(\ndiff --git a/modoboa/extensions/postfix_autoreply/general_callbacks.py b/modoboa/extensions/postfix_autoreply/general_callbacks.py\n--- a/modoboa/extensions/postfix_autoreply/general_callbacks.py\n+++ b/modoboa/extensions/postfix_autoreply/general_callbacks.py\n@@ -9,7 +9,7 @@\n def extra_js(user):\n     return [\"\"\"function autoreply_cb() {\n     $('.datefield').datetimepicker({\n-        format: 'YYYY-MM-DD hh:mm:ss',\n+        format: 'YYYY-MM-DD HH:mm:ss',\n         language: '%(lang)s'\n     });\n }\n", "issue": "In auto-reply message form, some issue around AM/PM datetime picker\nIn auto-reply message form, some issue around AM/PM datetime picker\n![capture d ecran 2015-04-29 a 15 18 23](https://cloud.githubusercontent.com/assets/230143/7391824/07cfbbfa-ee84-11e4-950c-a3a34fd2c6e4.png)\n\nI can't select AM or PM.\n\nSuggest : enable 24h format\n\n", "before_files": [{"content": "# coding: utf-8\nfrom django import forms\nfrom django.utils.translation import ugettext as _, ugettext_lazy\nfrom django.utils import timezone\nfrom .models import ARmessage\n\n\nclass ARmessageForm(forms.ModelForm):\n    fromdate = forms.DateTimeField(\n        label=ugettext_lazy('From'),\n        required=False,\n        help_text=ugettext_lazy(\"Activate your auto reply from this date\"),\n        widget=forms.TextInput(\n            attrs={'class': 'datefield form-control', 'readonly': 'readonly'}\n        )\n    )\n    untildate = forms.DateTimeField(\n        label=ugettext_lazy('Until'),\n        required=False,\n        help_text=ugettext_lazy(\"Activate your auto reply until this date\"),\n        widget=forms.TextInput(\n            attrs={'class': 'datefield form-control', 'readonly': 'readonly'}\n        )\n    )\n    subject = forms.CharField(\n            widget=forms.TextInput(\n                    attrs={'class': 'form-control'}\n                )\n    )\n    content = forms.CharField(\n                widget=forms.Textarea(\n                        attrs={'class': 'form-control'}\n                    )\n        )\n\n    class Meta:\n        model = ARmessage\n        fields = ('subject', 'content', 'enabled')\n\n    def __init__(self, *args, **kwargs):\n        super(ARmessageForm, self).__init__(*args, **kwargs)\n        self.fields.keyOrder = [\n            'subject', 'content', 'fromdate', 'untildate', 'enabled'\n        ]\n        if 'instance' in kwargs and kwargs['instance'] is not None:\n            self.fields['fromdate'].initial = \\\n                kwargs['instance'].fromdate.replace(second=0, microsecond=0)\n            self.fields['untildate'].initial = kwargs['instance'].untildate\n\n    def clean(self):\n        \"\"\"Custom fields validaton.\n\n        We want to be sure that fromdate < untildate and that they are\n        both in the future ONLY IF the autoreply is beeing activated.\n\n        \"\"\"\n        super(ARmessageForm, self).clean()\n        if self._errors:\n            raise forms.ValidationError(self._errors)\n        if not self.cleaned_data[\"enabled\"]:\n            return self.cleaned_data\n        if self.cleaned_data[\"fromdate\"] is not None:\n            if self.cleaned_data[\"fromdate\"] < timezone.now():\n                self._errors[\"fromdate\"] = self.error_class(\n                    [_(\"This date is over\")])\n                del self.cleaned_data['fromdate']\n        else:\n            self.cleaned_data['fromdate'] = timezone.now()\n        if self.cleaned_data[\"untildate\"] is not None:\n            if self.cleaned_data[\"untildate\"] < timezone.now():\n                self._errors[\"untildate\"] = self.error_class(\n                    [_(\"This date is over\")])\n                del self.cleaned_data['untildate']\n            elif 'fromdate' in self.cleaned_data and \\\n                    self.cleaned_data['untildate'] < self.cleaned_data['fromdate']:\n                self._errors[\"untildate\"] = \\\n                    self.error_class([_(\"Must be greater than start date\")])\n                del self.cleaned_data['untildate']\n        return self.cleaned_data\n", "path": "modoboa/extensions/postfix_autoreply/forms.py"}, {"content": "from django.utils import timezone\nfrom django.utils.translation import ugettext_lazy\nfrom modoboa.lib import events, parameters\nfrom modoboa.extensions.postfix_autoreply.models import Transport, Alias\nfrom .models import ARmessage\n\n\n@events.observe(\"ExtraUprefsJS\")\ndef extra_js(user):\n    return [\"\"\"function autoreply_cb() {\n    $('.datefield').datetimepicker({\n        format: 'YYYY-MM-DD hh:mm:ss',\n        language: '%(lang)s'\n    });\n}\n\"\"\" % {'lang': parameters.get_user(user, \"LANG\", app=\"core\")}\n    ]\n\n\n@events.observe(\"UserMenuDisplay\")\ndef menu(target, user):\n    if target != \"uprefs_menu\":\n        return []\n    if not user.mailbox_set.count():\n        return []\n    return [\n        {\"name\": \"autoreply\",\n         \"class\": \"ajaxnav\",\n         \"url\": \"autoreply/\",\n         \"label\": ugettext_lazy(\"Auto-reply message\")}\n    ]\n\n\n@events.observe(\"DomainCreated\")\ndef onDomainCreated(user, domain):\n    transport = Transport()\n    transport.domain = \"autoreply.%s\" % domain.name\n    transport.method = \"autoreply:\"\n    transport.save()\n\n\n@events.observe(\"DomainModified\")\ndef onDomainModified(domain):\n    if domain.oldname == domain.name:\n        return\n    Transport.objects.filter(domain=\"autoreply.%s\" % domain.oldname) \\\n        .update(domain=\"autoreply.%s\" % domain.name)\n    for al in Alias.objects.filter(full_address__contains=\"@%s\" % domain.oldname):\n        new_address = al.full_address.replace(\"@%s\" % domain.oldname, \"@%s\" % domain.name)\n        al.full_address = new_address\n        al.autoreply_address = \"%s@autoreply.%s\" % (new_address, domain.name)\n        al.save()\n\n\n@events.observe(\"DomainDeleted\")\ndef onDomainDeleted(domain):\n    Transport.objects.filter(domain=\"autoreply.%s\" % domain.name).delete()\n\n\n@events.observe(\"MailboxCreated\")\ndef onMailboxCreated(user, mailbox):\n    alias = Alias()\n    alias.full_address = mailbox.full_address\n    alias.autoreply_address = \\\n        \"%s@autoreply.%s\" % (mailbox.full_address, mailbox.domain.name)\n    alias.save()\n\n\n@events.observe(\"MailboxDeleted\")\ndef onMailboxDeleted(mailboxes):\n    from modoboa.extensions.admin.models import Mailbox\n\n    if isinstance(mailboxes, Mailbox):\n        mailboxes = [mailboxes]\n    for mailbox in mailboxes:\n        try:\n            alias = Alias.objects.get(full_address=mailbox.full_address)\n        except Alias.DoesNotExist:\n            pass\n        else:\n            alias.delete()\n\n\n@events.observe(\"MailboxModified\")\ndef onMailboxModified(mailbox):\n    if not hasattr(mailbox, 'old_full_address'):\n        return\n    if mailbox.full_address == mailbox.old_full_address:\n        return\n    alias = Alias.objects.get(full_address=mailbox.old_full_address)\n    alias.full_address = mailbox.full_address\n    alias.autoreply_address =  \\\n        \"%s@autoreply.%s\" % (mailbox.full_address, mailbox.domain.name)\n    alias.save()\n\n\n@events.observe(\"ExtraFormFields\")\ndef extra_mailform_fields(form_name, mailbox=None):\n    \"\"\"Define extra fields to include in mail forms.\n\n    For now, only the auto-reply state can be modified.\n\n    :param str form_name: form name (must be 'mailform')\n    :param Mailbox mailbox: mailbox\n    \"\"\"\n    from modoboa.lib.formutils import YesNoField\n\n    if form_name != \"mailform\":\n        return []\n    status = False\n    if mailbox is not None and mailbox.armessage_set.count():\n        status = mailbox.armessage_set.all()[0].enabled\n    return [\n        ('autoreply', YesNoField(\n            label=ugettext_lazy(\"Enable auto-reply\"),\n            initial=\"yes\" if status else \"no\",\n            help_text=ugettext_lazy(\"Enable or disable Postfix auto-reply\")\n        ))\n    ]\n\n\n@events.observe(\"SaveExtraFormFields\")\ndef save_extra_mailform_fields(form_name, mailbox, values):\n    \"\"\"Set the auto-reply status for a mailbox.\n\n    If a corresponding auto-reply message exists, we update its\n    status. Otherwise, we create a message using default values.\n\n    :param str form_name: form name (must be 'mailform')\n    :param Mailbox mailbox: mailbox\n    :param dict values: form values\n    \"\"\"\n    if form_name != 'mailform':\n        return\n    if mailbox.armessage_set.count():\n        arm = mailbox.armessage_set.all()[0]\n    else:\n        arm = ARmessage(mbox=mailbox)\n        arm.subject = parameters.get_admin(\"DEFAULT_SUBJECT\")\n        arm.content = parameters.get_admin(\"DEFAULT_CONTENT\") \\\n            % {'name': mailbox.user.fullname}\n        arm.fromdate = timezone.now()\n    arm.enabled = True if values['autoreply'] == 'yes' else False\n    arm.save()\n", "path": "modoboa/extensions/postfix_autoreply/general_callbacks.py"}], "after_files": [{"content": "# coding: utf-8\nfrom django import forms\nfrom django.utils.translation import ugettext as _, ugettext_lazy\nfrom django.utils import timezone\nfrom .models import ARmessage\n\n\nclass ARmessageForm(forms.ModelForm):\n    fromdate = forms.DateTimeField(\n        label=ugettext_lazy('From'),\n        required=False,\n        help_text=ugettext_lazy(\"Activate your auto reply from this date\"),\n        widget=forms.TextInput(\n            attrs={'class': 'datefield form-control'}\n        )\n    )\n    untildate = forms.DateTimeField(\n        label=ugettext_lazy('Until'),\n        required=False,\n        help_text=ugettext_lazy(\"Activate your auto reply until this date\"),\n        widget=forms.TextInput(\n            attrs={'class': 'datefield form-control'}\n        )\n    )\n    subject = forms.CharField(\n            widget=forms.TextInput(\n                    attrs={'class': 'form-control'}\n                )\n    )\n    content = forms.CharField(\n                widget=forms.Textarea(\n                        attrs={'class': 'form-control'}\n                    )\n        )\n\n    class Meta:\n        model = ARmessage\n        fields = ('subject', 'content', 'enabled')\n\n    def __init__(self, *args, **kwargs):\n        super(ARmessageForm, self).__init__(*args, **kwargs)\n        self.fields.keyOrder = [\n            'subject', 'content', 'fromdate', 'untildate', 'enabled'\n        ]\n        if 'instance' in kwargs and kwargs['instance'] is not None:\n            self.fields['fromdate'].initial = \\\n                kwargs['instance'].fromdate.replace(second=0, microsecond=0)\n            self.fields['untildate'].initial = kwargs['instance'].untildate\n\n    def clean(self):\n        \"\"\"Custom fields validaton.\n\n        We want to be sure that fromdate < untildate and that they are\n        both in the future ONLY IF the autoreply is beeing activated.\n\n        \"\"\"\n        super(ARmessageForm, self).clean()\n        if self._errors:\n            raise forms.ValidationError(self._errors)\n        if not self.cleaned_data[\"enabled\"]:\n            return self.cleaned_data\n        if self.cleaned_data[\"fromdate\"] is not None:\n            if self.cleaned_data[\"fromdate\"] < timezone.now():\n                self._errors[\"fromdate\"] = self.error_class(\n                    [_(\"This date is over\")])\n                del self.cleaned_data['fromdate']\n        else:\n            self.cleaned_data['fromdate'] = timezone.now()\n        if self.cleaned_data[\"untildate\"] is not None:\n            if self.cleaned_data[\"untildate\"] < timezone.now():\n                self._errors[\"untildate\"] = self.error_class(\n                    [_(\"This date is over\")])\n                del self.cleaned_data['untildate']\n            elif 'fromdate' in self.cleaned_data and \\\n                    self.cleaned_data['untildate'] < self.cleaned_data['fromdate']:\n                self._errors[\"untildate\"] = \\\n                    self.error_class([_(\"Must be greater than start date\")])\n                del self.cleaned_data['untildate']\n        return self.cleaned_data\n", "path": "modoboa/extensions/postfix_autoreply/forms.py"}, {"content": "from django.utils import timezone\nfrom django.utils.translation import ugettext_lazy\nfrom modoboa.lib import events, parameters\nfrom modoboa.extensions.postfix_autoreply.models import Transport, Alias\nfrom .models import ARmessage\n\n\n@events.observe(\"ExtraUprefsJS\")\ndef extra_js(user):\n    return [\"\"\"function autoreply_cb() {\n    $('.datefield').datetimepicker({\n        format: 'YYYY-MM-DD HH:mm:ss',\n        language: '%(lang)s'\n    });\n}\n\"\"\" % {'lang': parameters.get_user(user, \"LANG\", app=\"core\")}\n    ]\n\n\n@events.observe(\"UserMenuDisplay\")\ndef menu(target, user):\n    if target != \"uprefs_menu\":\n        return []\n    if not user.mailbox_set.count():\n        return []\n    return [\n        {\"name\": \"autoreply\",\n         \"class\": \"ajaxnav\",\n         \"url\": \"autoreply/\",\n         \"label\": ugettext_lazy(\"Auto-reply message\")}\n    ]\n\n\n@events.observe(\"DomainCreated\")\ndef onDomainCreated(user, domain):\n    transport = Transport()\n    transport.domain = \"autoreply.%s\" % domain.name\n    transport.method = \"autoreply:\"\n    transport.save()\n\n\n@events.observe(\"DomainModified\")\ndef onDomainModified(domain):\n    if domain.oldname == domain.name:\n        return\n    Transport.objects.filter(domain=\"autoreply.%s\" % domain.oldname) \\\n        .update(domain=\"autoreply.%s\" % domain.name)\n    for al in Alias.objects.filter(full_address__contains=\"@%s\" % domain.oldname):\n        new_address = al.full_address.replace(\"@%s\" % domain.oldname, \"@%s\" % domain.name)\n        al.full_address = new_address\n        al.autoreply_address = \"%s@autoreply.%s\" % (new_address, domain.name)\n        al.save()\n\n\n@events.observe(\"DomainDeleted\")\ndef onDomainDeleted(domain):\n    Transport.objects.filter(domain=\"autoreply.%s\" % domain.name).delete()\n\n\n@events.observe(\"MailboxCreated\")\ndef onMailboxCreated(user, mailbox):\n    alias = Alias()\n    alias.full_address = mailbox.full_address\n    alias.autoreply_address = \\\n        \"%s@autoreply.%s\" % (mailbox.full_address, mailbox.domain.name)\n    alias.save()\n\n\n@events.observe(\"MailboxDeleted\")\ndef onMailboxDeleted(mailboxes):\n    from modoboa.extensions.admin.models import Mailbox\n\n    if isinstance(mailboxes, Mailbox):\n        mailboxes = [mailboxes]\n    for mailbox in mailboxes:\n        try:\n            alias = Alias.objects.get(full_address=mailbox.full_address)\n        except Alias.DoesNotExist:\n            pass\n        else:\n            alias.delete()\n\n\n@events.observe(\"MailboxModified\")\ndef onMailboxModified(mailbox):\n    if not hasattr(mailbox, 'old_full_address'):\n        return\n    if mailbox.full_address == mailbox.old_full_address:\n        return\n    alias = Alias.objects.get(full_address=mailbox.old_full_address)\n    alias.full_address = mailbox.full_address\n    alias.autoreply_address =  \\\n        \"%s@autoreply.%s\" % (mailbox.full_address, mailbox.domain.name)\n    alias.save()\n\n\n@events.observe(\"ExtraFormFields\")\ndef extra_mailform_fields(form_name, mailbox=None):\n    \"\"\"Define extra fields to include in mail forms.\n\n    For now, only the auto-reply state can be modified.\n\n    :param str form_name: form name (must be 'mailform')\n    :param Mailbox mailbox: mailbox\n    \"\"\"\n    from modoboa.lib.formutils import YesNoField\n\n    if form_name != \"mailform\":\n        return []\n    status = False\n    if mailbox is not None and mailbox.armessage_set.count():\n        status = mailbox.armessage_set.all()[0].enabled\n    return [\n        ('autoreply', YesNoField(\n            label=ugettext_lazy(\"Enable auto-reply\"),\n            initial=\"yes\" if status else \"no\",\n            help_text=ugettext_lazy(\"Enable or disable Postfix auto-reply\")\n        ))\n    ]\n\n\n@events.observe(\"SaveExtraFormFields\")\ndef save_extra_mailform_fields(form_name, mailbox, values):\n    \"\"\"Set the auto-reply status for a mailbox.\n\n    If a corresponding auto-reply message exists, we update its\n    status. Otherwise, we create a message using default values.\n\n    :param str form_name: form name (must be 'mailform')\n    :param Mailbox mailbox: mailbox\n    :param dict values: form values\n    \"\"\"\n    if form_name != 'mailform':\n        return\n    if mailbox.armessage_set.count():\n        arm = mailbox.armessage_set.all()[0]\n    else:\n        arm = ARmessage(mbox=mailbox)\n        arm.subject = parameters.get_admin(\"DEFAULT_SUBJECT\")\n        arm.content = parameters.get_admin(\"DEFAULT_CONTENT\") \\\n            % {'name': mailbox.user.fullname}\n        arm.fromdate = timezone.now()\n    arm.enabled = True if values['autoreply'] == 'yes' else False\n    arm.save()\n", "path": "modoboa/extensions/postfix_autoreply/general_callbacks.py"}]}