Merge branch 'production' of github.com:fnp/redakcja into production
[redakcja.git] / apps / filebrowser / forms.py
1 # coding: utf-8
2
3 import os
4 import re
5
6 from django import forms
7 from django.forms.formsets import BaseFormSet
8 from django.utils.translation import ugettext as _
9
10 # filebrowser imports
11 from filebrowser.fb_settings import MAX_UPLOAD_SIZE
12 from filebrowser.functions import _get_file_type, _convert_filename
13
14 alnum_name_re = re.compile(r'^[\sa-zA-Z0-9._/-]+$')
15
16
17 class MakeDirForm(forms.Form):
18     """
19     Form for creating Directory.
20     """
21
22     def __init__(self, path, *args, **kwargs):
23         self.path = path
24         super(MakeDirForm, self).__init__(*args, **kwargs)
25
26     dir_name = forms.CharField(widget=forms.TextInput(attrs=dict({'class': 'vTextField'}, max_length=50, min_length=3)), label=_(u'Name'), help_text=_(u'Only letters, numbers, underscores, spaces and hyphens are allowed.'), required=True)
27
28     def clean_dir_name(self):
29         if self.cleaned_data['dir_name']:
30             # only letters, numbers, underscores, spaces and hyphens are allowed.
31             if not alnum_name_re.search(self.cleaned_data['dir_name']):
32                 raise forms.ValidationError(_(u'Only letters, numbers, underscores, spaces and hyphens are allowed.'))
33             # directory must not already exist.
34             if os.path.isdir(os.path.join(self.path, _convert_filename(self.cleaned_data['dir_name']))):
35                 raise forms.ValidationError(_(u'The Folder already exists.'))
36         return _convert_filename(self.cleaned_data['dir_name'])
37
38
39 class RenameForm(forms.Form):
40     """
41     Form for renaming File/Directory.
42     """
43
44     def __init__(self, path, file_extension, *args, **kwargs):
45         self.path = path
46         self.file_extension = file_extension
47         super(RenameForm, self).__init__(*args, **kwargs)
48
49     name = forms.CharField(widget=forms.TextInput(attrs=dict({'class': 'vTextField'}, max_length=50, min_length=3)), label=_(u'New Name'), help_text=_('Only letters, numbers, underscores, spaces and hyphens are allowed.'), required=True)
50
51     def clean_name(self):
52         if self.cleaned_data['name']:
53             # only letters, numbers, underscores, spaces and hyphens are allowed.
54             if not alnum_name_re.search(self.cleaned_data['name']):
55                 raise forms.ValidationError(_(u'Only letters, numbers, underscores, spaces and hyphens are allowed.'))
56             # file/directory must not already exist.
57             if os.path.isdir(os.path.join(self.path, _convert_filename(self.cleaned_data['name']))) or os.path.isfile(os.path.join(self.path, _convert_filename(self.cleaned_data['name']) + self.file_extension)):
58                 raise forms.ValidationError(_(u'The File/Folder already exists.'))
59         return _convert_filename(self.cleaned_data['name'])