0b919ecc35a9f0b6cb68c026f4623f589993b45c
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage / chercheurs / views.py
1 # -*- encoding: utf-8 -*-
2 from chercheurs.decorators import chercheur_required
3 from chercheurs.forms import ChercheurSearchForm, SetPasswordForm, ChercheurFormGroup, AuthenticationForm, GroupeSearchForm, MessageForm
4 from chercheurs.models import Chercheur, Groupe, Message, ChercheurGroupe
5 from chercheurs.utils import get_django_user_for_email
6 from datamaster_modeles.models import Etablissement, Region
7 from django.conf import settings
8 from django.shortcuts import render_to_response
9 from django.http import HttpResponseRedirect, HttpResponse, HttpResponseForbidden, HttpResponseNotFound
10 from django.template import Context, RequestContext
11 from django.template.loader import get_template
12 from django.core.urlresolvers import reverse as url
13 from django.core.mail import send_mail
14 from django.contrib.auth import REDIRECT_FIELD_NAME
15 from django.contrib.auth import login as auth_login
16 from django.contrib.auth.decorators import login_required
17 from django.contrib.sites.models import RequestSite, Site
18 from django.utils import simplejson
19 from django.utils.http import int_to_base36, base36_to_int
20 from django.views.decorators.cache import never_cache
21 from django.contrib.auth import authenticate, login
22 from django.shortcuts import get_object_or_404
23 from savoirs.models import PageStatique, Discipline
24
25 def index(request):
26 """Répertoire des chercheurs"""
27 search_form = ChercheurSearchForm(request.GET)
28 search = search_form.save(commit=False)
29 chercheurs = search.run().select_related('etablissement')
30 sort = request.GET.get('tri')
31 if sort is not None and sort.endswith('_desc'):
32 sort = sort[:-5]
33 direction = '-'
34 else:
35 direction = ''
36 if sort == 'nom':
37 chercheurs = chercheurs.order_by_nom(direction)
38 elif sort == 'etablissement':
39 chercheurs = chercheurs.order_by_etablissement(direction)
40 elif sort == 'pays':
41 chercheurs = chercheurs.order_by_pays(direction)
42 else:
43 chercheurs = chercheurs.order_by('-date_modification')
44
45 try:
46 p = PageStatique.objects.get(id='repertoire')
47 entete = p.contenu
48 except PageStatique.DoesNotExist:
49 entete = u'<h1>Répertoire des chercheurs</h1>'
50
51 nb_chercheurs = chercheurs.count()
52
53 return render_to_response("chercheurs/index.html",
54 dict(chercheurs=chercheurs, nb_chercheurs=nb_chercheurs,
55 search_form=search_form, entete=entete),
56 context_instance=RequestContext(request))
57
58 def inscription(request):
59 if request.method == 'POST':
60 forms = ChercheurFormGroup(request.POST)
61 if forms.is_valid():
62 chercheur = forms.save()
63 id_base36 = int_to_base36(chercheur.id)
64 token = chercheur.activation_token()
65 template = get_template('chercheurs/activation_email.txt')
66 domain = RequestSite(request).domain
67 message = template.render(Context(dict(chercheur=chercheur, id_base36=id_base36, token=token, domain=domain)))
68 send_mail('Votre inscription à Savoirs en partage', message, None, [chercheur.courriel])
69 return HttpResponseRedirect(url('chercheurs-inscription-faite'))
70 else:
71 forms = ChercheurFormGroup()
72
73 return render_to_response("chercheurs/inscription.html",
74 dict(forms=forms),
75 context_instance=RequestContext(request))
76
77 def activation(request, id_base36, token):
78 """Activation d'un chercheur"""
79 id = base36_to_int(id_base36)
80 chercheur = get_object_or_404(Chercheur.all_objects, id=id)
81 if token == chercheur.activation_token():
82 validlink = True
83 if request.method == 'POST':
84 form = SetPasswordForm(request.POST)
85 if form.is_valid():
86 password = form.cleaned_data['password']
87 email = chercheur.courriel
88 chercheur.actif = True
89 chercheur.save()
90 user = get_django_user_for_email(email)
91 user.set_password(password)
92 user.save()
93
94 # Auto-login
95 auth_login(request, authenticate(username=email, password=password))
96 return HttpResponseRedirect(url('chercheurs.views.perso'))
97 else:
98 form = SetPasswordForm()
99 else:
100 form = None
101 validlink = False
102 return render_to_response('chercheurs/activation.html', dict(form=form, validlink=validlink),
103 context_instance=RequestContext(request))
104
105 @chercheur_required
106 def desinscription(request):
107 """Désinscription du chercheur"""
108 chercheur = request.chercheur
109 if request.method == 'POST':
110 if request.POST.get('confirmer'):
111 chercheur.actif = False
112 chercheur.save()
113 request.flash['message'] = "Vous avez été désinscrit du répertoire des chercheurs."
114 return HttpResponseRedirect(url('django.contrib.auth.views.logout'))
115 else:
116 request.flash['message'] = "Opération annulée."
117 return HttpResponseRedirect(url('chercheurs.views.perso'))
118 return render_to_response("chercheurs/desinscription.html", {},
119 context_instance=RequestContext(request))
120
121 @chercheur_required
122 @never_cache
123 def edit(request):
124 """Edition d'un chercheur"""
125 chercheur = request.chercheur
126 if request.method == 'POST':
127 forms = ChercheurFormGroup(request.POST, chercheur=chercheur)
128 if forms.is_valid():
129 forms.save()
130 request.flash['message'] = "Votre fiche a bien été enregistrée."
131 return HttpResponseRedirect(url('chercheurs.views.perso'))
132 else:
133 forms = ChercheurFormGroup(chercheur=chercheur)
134
135 return render_to_response("chercheurs/edit.html",
136 dict(forms=forms, chercheur=chercheur),
137 context_instance=RequestContext(request))
138
139 @chercheur_required
140 def perso(request):
141 """Espace chercheur (espace personnel du chercheur)"""
142 chercheur = request.chercheur
143 modification = request.GET.get('modification')
144 return render_to_response("chercheurs/perso.html",
145 dict(chercheur=chercheur, modification=modification),
146 context_instance=RequestContext(request))
147
148 def retrieve(request, id):
149 """Fiche du chercheur"""
150 chercheur = get_object_or_404(Chercheur, id=id)
151 return render_to_response("chercheurs/retrieve.html",
152 dict(chercheur=chercheur),
153 context_instance=RequestContext(request))
154
155 def conversion(request):
156 return render_to_response("chercheurs/conversion.html", {},
157 context_instance=RequestContext(request))
158
159 def etablissements_autocomplete(request, pays=None):
160 term = request.GET.get('term')
161 noms = Etablissement.objects.all().filter(membre=True, actif=True)
162 for word in term.split():
163 noms = noms.filter(nom__icontains=word)
164 if pays:
165 noms = noms.filter(pays=pays)
166 noms = list(noms.values_list('nom', flat=True)[:20])
167 json = simplejson.dumps(noms)
168 return HttpResponse(json, mimetype='application/json')
169
170 def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME):
171 "The Django login view, but using a custom form."
172 redirect_to = request.REQUEST.get(redirect_field_name, '')
173
174 if request.method == "POST":
175 form = AuthenticationForm(data=request.POST)
176 if form.is_valid():
177 # Light security check -- make sure redirect_to isn't garbage.
178 if not redirect_to or ' ' in redirect_to:
179 redirect_to = settings.LOGIN_REDIRECT_URL
180
181 # Heavier security check -- redirects to http://example.com should
182 # not be allowed, but things like /view/?param=http://example.com
183 # should be allowed. This regex checks if there is a '//' *before* a
184 # question mark.
185 elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
186 redirect_to = settings.LOGIN_REDIRECT_URL
187
188 # Okay, security checks complete. Log the user in.
189 auth_login(request, form.get_user())
190
191 if request.session.test_cookie_worked():
192 request.session.delete_test_cookie()
193
194 return HttpResponseRedirect(redirect_to)
195
196 else:
197 form = AuthenticationForm(request)
198 request.session.set_test_cookie()
199
200 if Site._meta.installed:
201 current_site = Site.objects.get_current()
202 else:
203 current_site = RequestSite(request)
204
205 return render_to_response(template_name, {
206 'form': form,
207 redirect_field_name: redirect_to,
208 'site': current_site,
209 'site_name': current_site.name,
210 }, context_instance=RequestContext(request))
211 login = never_cache(login)
212
213 # groupes
214 def groupe_index(request):
215 search_form = GroupeSearchForm(request.GET)
216 search = search_form.save(commit=False)
217 groupes = search.run()
218 nb_resultats = groupes.count()
219 try:
220 p = PageStatique.objects.get(id='groupes')
221 entete = p.contenu
222 except PageStatique.DoesNotExist:
223 entete = '<h1>Liste des groupes</h1>'
224
225 est_chercheur, mesgroupes, messages = False, None, None
226 if request.user.is_authenticated():
227 try:
228 chercheur = Chercheur.objects.get(courriel=request.user.email)
229 mesgroupes = chercheur.groupes.all().filter(membership__actif=1)
230 messages = Message.objects.all().filter(groupe__in=mesgroupes)[:10]
231 est_chercheur = True
232 except Chercheur.DoesNotExist:
233 pass
234
235 return render_to_response("chercheurs/groupe_index.html", {
236 'search_form': search_form,
237 'groupes': groupes.order_by('nom'),
238 'nb_resultats': nb_resultats,
239 'entete': entete,
240 'mesgroupes': mesgroupes,
241 'messages': messages,
242 'est_chercheur': est_chercheur,
243 }, context_instance=RequestContext(request))
244
245 def groupe_adhesion(request, id):
246 try:
247 groupe = get_object_or_404(Groupe, id=id)
248 chercheur = Chercheur.objects.get(courriel=request.user.email)
249 cg, created = ChercheurGroupe.objects.get_or_create(chercheur=chercheur, groupe=groupe)
250 if created:
251 cg.actif = 0
252 cg.save()
253 except:
254 pass
255
256 return HttpResponseRedirect(url('groupe_retrieve', kwargs={'id': id}))
257
258 def groupe_retrieve(request, id):
259 groupe = get_object_or_404(Groupe, id=id)
260 membres = groupe.membership.all().order_by('-date_modification')
261 messages = groupe.message_set.all()[:5]
262
263 est_chercheur, est_membre, est_membre_actif = False, False, False
264 if request.user.is_authenticated():
265 try:
266 chercheur = Chercheur.objects.get(courriel=request.user.email)
267 est_chercheur = True
268 est_membre = chercheur in groupe.membres.all()
269 est_membre_actif = bool(len(groupe.membership.filter(chercheur=chercheur, actif=True)))
270 except Chercheur.DoesNotExist:
271 pass
272
273 return render_to_response(
274 "chercheurs/groupe_retrieve.html", {
275 'groupe': groupe,
276 'membres': membres,
277 'messages': messages,
278 'est_chercheur': est_chercheur,
279 'est_membre': est_membre,
280 'est_membre_actif': est_membre_actif,
281 }, context_instance=RequestContext(request)
282 )
283
284 def groupe_messages(request, id):
285
286 groupe = get_object_or_404(Groupe, id=id)
287
288 if request.method == 'POST':
289 form = MessageForm(request.POST)
290 if form.is_valid():
291 chercheur = Chercheur.objects.get(courriel=request.user.email)
292 message = form.save(commit=False)
293 message.groupe = groupe
294 message.chercheur = chercheur
295 message.save()
296
297 form = MessageForm()
298
299 else:
300 form = MessageForm()
301
302 messages = groupe.message_set.all()
303
304 return render_to_response(
305 "chercheurs/groupe_message.html", {
306 'groupe': groupe,
307 'messages': messages,
308 'form': form,
309 }, context_instance=RequestContext(request)
310 )