Statistics
| Branch: | Tag: | Revision:

root / edumanage / views.py @ 27d6f3e2

History | View | Annotate | Download (63.9 kB)

1
# -*- coding: utf-8 -*- vim:encoding=utf-8:
2
# vim: tabstop=4:shiftwidth=4:softtabstop=4:expandtab
3

    
4
from django.shortcuts import render_to_response,get_object_or_404
5
from django.http import HttpResponse,HttpResponseRedirect,Http404
6
from django.template import RequestContext
7
from django.core.urlresolvers import reverse
8
from django.contrib.auth.decorators import login_required
9
from edumanage.models import *
10
from accounts.models import *
11
from edumanage.forms import *
12
from django import forms
13
from django.forms.models import modelformset_factory
14
from django.forms.models import inlineformset_factory
15
from django.contrib.contenttypes.generic import generic_inlineformset_factory
16
from django.core.mail.message import EmailMessage
17
from django.contrib.sites.models import Site
18
from django.template.loader import render_to_string
19
import json, bz2
20
import math, datetime
21
from xml.etree import ElementTree as ET
22

    
23
from django.conf import settings
24
from django.contrib import messages
25

    
26
from django.db.models import Max
27

    
28
from django.views.decorators.cache import never_cache
29
from django.utils.translation import ugettext as _
30
from django.contrib.auth import authenticate, login
31
from registration.models import RegistrationProfile
32
from django.core.cache import cache
33

    
34
@never_cache
35
def index(request):
36
    return render_to_response('front/index.html', context_instance=RequestContext(request))
37

    
38

    
39
@login_required
40
@never_cache
41
def manage(request):
42
    services_list = []
43
    servers_list = []
44
    user = request.user
45
    try:
46
        profile = user.get_profile()
47
        inst = profile.institution
48
    except UserProfile.DoesNotExist:
49
        return render_to_response('edumanage/welcome.html',
50
                              context_instance=RequestContext(request, base_response(request)))
51
        
52
    services = ServiceLoc.objects.filter(institutionid=inst)
53
    services_list.extend([s for s in services])
54
    servers = InstServer.objects.filter(instid=inst)
55
    servers_list.extend([s for s in servers])
56
    return render_to_response('edumanage/welcome.html', 
57
                              {
58
                               'institution': inst, 
59
                               'services': services_list,
60
                               'servers': servers_list
61
                               },  
62
                              context_instance=RequestContext(request, base_response(request)))
63

    
64
@login_required
65
@never_cache
66
def institutions(request):
67
    user = request.user
68
    dict = {}
69
    try:
70
        profile = user.get_profile()
71
        inst = profile.institution
72
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
73
    except UserProfile.DoesNotExist:
74
        return HttpResponseRedirect(reverse("manage"))
75
    dict['institution'] = inst.pk
76
    form = InstDetailsForm(initial=dict)
77
    form.fields['institution'].widget.attrs['readonly'] = True
78
    return render_to_response('edumanage/institution.html', 
79
                              {
80
                               'institution': inst,
81
                               'form': form, 
82
                               },  
83
                              context_instance=RequestContext(request, base_response(request)))
84

    
85

    
86

    
87
@login_required
88
@never_cache
89
def add_institution_details(request, institution_pk):
90
    user = request.user
91
    try:
92
        profile = user.get_profile()
93
        inst = profile.institution
94
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
95
    except UserProfile.DoesNotExist:
96
        return HttpResponseRedirect(reverse("manage"))
97
    
98
    if institution_pk and int(inst.pk) != int(institution_pk):
99
        messages.add_message(request, messages.ERROR, 'You have no rights on this Institution')
100
        return HttpResponseRedirect(reverse("institutions"))
101
    
102
    if request.method == "GET":
103
        request_data = request.POST.copy()
104
        try:         
105
            inst_details = InstitutionDetails.objects.get(institution=inst)
106
            form = InstDetailsForm(instance=inst_details)
107
            UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFactInst, can_delete=True)
108
            urls_form = UrlFormSet(prefix='urlsform', instance = inst_details) 
109
        except InstitutionDetails.DoesNotExist:
110
            form = InstDetailsForm()
111
            form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=institution_pk), empty_label=None)
112
            UrlFormSet =  generic_inlineformset_factory(URL_i18n, extra=2, can_delete=True)
113
            urls_form = UrlFormSet(prefix='urlsform')
114

    
115
        
116
        form.fields['contact'] = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(pk__in=getInstContacts(inst)))
117
        return render_to_response('edumanage/institution_edit.html', { 'institution': inst, 'form': form, 'urls_form':urls_form},
118
                                  context_instance=RequestContext(request, base_response(request)))
119
    elif request.method == 'POST':
120
        request_data = request.POST.copy()
121
        UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFactInst, can_delete=True)
122
        try:         
123
            inst_details = InstitutionDetails.objects.get(institution=inst)
124
            form = InstDetailsForm(request_data, instance=inst_details)
125
            urls_form = UrlFormSet(request_data, instance=inst_details, prefix='urlsform')
126
        except InstitutionDetails.DoesNotExist:
127
            form = InstDetailsForm(request_data)
128
            urls_form = UrlFormSet(request_data, prefix='urlsform')
129
        UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFactInst, can_delete=True)
130
        if form.is_valid() and urls_form.is_valid():
131
            instdets = form.save()
132
            urls_form.instance = instdets
133
            urls_inst = urls_form.save()
134
            return HttpResponseRedirect(reverse("institutions"))
135
        else:
136
            form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=institution_pk), empty_label=None)
137
            form.fields['contact'] = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(pk__in=getInstContacts(inst)))
138
            return render_to_response('edumanage/institution_edit.html', { 'institution': inst, 'form': form, 'urls_form': urls_form},
139
                                  context_instance=RequestContext(request, base_response(request)))
140

    
141

    
142
@login_required
143
@never_cache
144
def services(request, service_pk):
145
    user = request.user
146
    dict = {}
147
    try:
148
        profile = user.get_profile()
149
        inst = profile.institution
150
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
151
    except UserProfile.DoesNotExist:
152
        return HttpResponseRedirect(reverse("manage"))
153
    try:
154
        instdetails = inst.institutiondetails
155
    except InstitutionDetails.DoesNotExist:
156
        return HttpResponseRedirect(reverse("manage"))
157
    if inst.ertype not in [2,3]:
158
        messages.add_message(request, messages.ERROR, 'Cannot add/edit Location. Your institution should be either SP or IdP/SP')
159
        return render_to_response('edumanage/services.html', { 'institution': inst },
160
                              context_instance=RequestContext(request, base_response(request)))
161
    try:
162
        services = ServiceLoc.objects.filter(institutionid = inst)
163
    except ServiceLoc.DoesNotExist:
164
        services = False 
165
    
166
    if service_pk:
167
        try:
168
            services = services.get(pk=service_pk)
169
        except:
170
            messages.add_message(request, messages.ERROR, 'You have no rights to view this location')
171
            return HttpResponseRedirect(reverse("services"))
172
        return render_to_response('edumanage/service_details.html', 
173
                              {
174
                               'institution': inst,
175
                               'service': services,
176
                               },  
177
                              context_instance=RequestContext(request, base_response(request)))
178
    
179
    return render_to_response('edumanage/services.html', 
180
                              {
181
                               'institution': inst,
182
                               'services': services, 
183
                               },  
184
                              context_instance=RequestContext(request, base_response(request)))
185

    
186

    
187

    
188
@login_required
189
@never_cache
190
def add_services(request, service_pk):
191
    user = request.user
192
    service = False
193
    edit = False
194
    try:
195
        profile = user.get_profile()
196
        inst = profile.institution
197
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
198
    except UserProfile.DoesNotExist:
199
        return HttpResponseRedirect(reverse("manage"))
200
    try:
201
        instdetails = inst.institutiondetails
202
    except InstitutionDetails.DoesNotExist:
203
        return HttpResponseRedirect(reverse("manage"))
204
    if inst.ertype not in [2,3]:
205
        messages.add_message(request, messages.ERROR, 'Cannot add/edit Service. Your institution should be either SP or IdP/SP')
206
        return render_to_response('edumanage/services_edit.html', { 'edit': edit },
207
                                  context_instance=RequestContext(request, base_response(request)))
208
    if request.method == "GET":
209

    
210
        # Determine add or edit
211
        try:         
212
            service = ServiceLoc.objects.get(institutionid=inst, pk=service_pk)
213
            form = ServiceLocForm(instance=service)
214
        except ServiceLoc.DoesNotExist:
215
            form = ServiceLocForm()
216
            if service_pk:
217
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this location')
218
                return HttpResponseRedirect(reverse("services"))
219
        form.fields['institutionid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
220
        UrlFormSet =  generic_inlineformset_factory(URL_i18n, extra=2, can_delete=True)
221
        NameFormSet = generic_inlineformset_factory(Name_i18n, extra=2, can_delete=True)
222
        urls_form = UrlFormSet(prefix='urlsform')
223
        names_form = NameFormSet(prefix='namesform')
224
        if (service):
225
            NameFormSet = generic_inlineformset_factory(Name_i18n, extra=1, formset=NameFormSetFact, can_delete=True)
226
            names_form = NameFormSet(instance=service, prefix='namesform')
227
            UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFact, can_delete=True)
228
            urls_form = UrlFormSet(instance=service, prefix='urlsform')
229
        form.fields['contact'] = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(pk__in=getInstContacts(inst)))
230
        if service:
231
            edit = True
232
        for url_form in urls_form.forms:
233
            url_form.fields['urltype'] = forms.ChoiceField(choices=(('', '----------'),('info', 'Info'),))
234
        return render_to_response('edumanage/services_edit.html', { 'form': form, 'services_form':names_form, 'urls_form': urls_form, "edit": edit},
235
                                  context_instance=RequestContext(request, base_response(request)))
236
    elif request.method == 'POST':
237
        request_data = request.POST.copy()
238
        NameFormSet = generic_inlineformset_factory(Name_i18n, extra=1, formset=NameFormSetFact, can_delete=True)
239
        UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFact, can_delete=True)
240
        try:         
241
            service = ServiceLoc.objects.get(institutionid=inst, pk=service_pk)
242
            form = ServiceLocForm(request_data, instance=service)
243
            names_form = NameFormSet(request_data, instance=service, prefix='namesform')
244
            urls_form = UrlFormSet(request_data, instance=service, prefix='urlsform')
245
        except ServiceLoc.DoesNotExist:
246
            form = ServiceLocForm(request_data)
247
            names_form = NameFormSet(request_data, prefix='namesform')
248
            urls_form = UrlFormSet(request_data, prefix='urlsform')
249
            if service_pk:
250
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this location')
251
                return HttpResponseRedirect(reverse("services"))
252
        
253
        if form.is_valid() and names_form.is_valid() and urls_form.is_valid():
254
            serviceloc = form.save()
255
            service = serviceloc
256
            names_form.instance = service
257
            urls_form.instance = service
258
            names_inst = names_form.save()
259
            urls_inst = urls_form.save()
260
            return HttpResponseRedirect(reverse("services"))
261
        else:
262
            form.fields['institutionid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
263
            form.fields['contact'] = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(pk__in=getInstContacts(inst)))
264
        if service:
265
            edit = True
266
        for url_form in urls_form.forms:
267
            url_form.fields['urltype'] = forms.ChoiceField(choices=(('', '----------'),('info', 'Info'),))
268
        return render_to_response('edumanage/services_edit.html', { 'institution': inst, 'form': form, 'services_form':names_form, 'urls_form': urls_form, "edit": edit},
269
                                  context_instance=RequestContext(request, base_response(request)))
270

    
271

    
272
@login_required
273
@never_cache
274
def del_service(request):
275
    if request.method == 'GET':
276
        user = request.user
277
        req_data = request.GET.copy()
278
        service_pk = req_data['service_pk']
279
        try:
280
            profile = user.get_profile()
281
            institution = profile.institution
282
        except UserProfile.DoesNotExist:
283
            resp['error'] = "Could not delete service. Not enough rights"
284
            return HttpResponse(json.dumps(resp), mimetype='application/json')
285
        resp = {}
286
        try:
287
            service = ServiceLoc.objects.get(institutionid=institution, pk=service_pk)
288
        except ServiceLoc.DoesNotExist:
289
            resp['error'] = "Could not get service or you have no rights to delete"
290
            return HttpResponse(json.dumps(resp), mimetype='application/json')
291
        try:
292
            service.delete()
293
        except:
294
            resp['error'] = "Could not delete service"
295
            return HttpResponse(json.dumps(resp), mimetype='application/json')
296
        resp['success'] = "Service successfully deleted"
297
        return HttpResponse(json.dumps(resp), mimetype='application/json')
298

    
299

    
300
@login_required
301
@never_cache
302
def servers(request, server_pk):
303
    user = request.user
304
    servers = False
305
    try:
306
        profile = user.get_profile()
307
        inst = profile.institution
308
    except UserProfile.DoesNotExist:
309
        inst = False
310
        return HttpResponseRedirect(reverse("manage"))
311
    if inst:
312
        servers = InstServer.objects.filter(instid=inst)
313
    if server_pk:
314
        servers = servers.get(pk=server_pk)
315
        return render_to_response('edumanage/server_details.html', 
316
                              {
317
                               'institution': inst,
318
                               'server': servers,
319
                               },  
320
                              context_instance=RequestContext(request, base_response(request)))
321
    return render_to_response('edumanage/servers.html', { 'servers': servers},
322
                                  context_instance=RequestContext(request, base_response(request)))
323

    
324

    
325
@login_required
326
@never_cache
327
def add_server(request, server_pk):
328
    user = request.user
329
    server = False
330
    edit = False
331
    try:
332
        profile = user.get_profile()
333
        inst = profile.institution
334
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
335
    except UserProfile.DoesNotExist:
336
        return HttpResponseRedirect(reverse("manage"))
337
    try:
338
        instdetails = inst.institutiondetails
339
    except InstitutionDetails.DoesNotExist:
340
        return HttpResponseRedirect(reverse("manage"))
341
    if request.method == "GET":
342
        # Determine add or edit
343
        try:         
344
            server = InstServer.objects.get(instid=inst, pk=server_pk)
345
            form = InstServerForm(instance=server)
346
        except InstServer.DoesNotExist:
347
            form = InstServerForm()
348
            if server_pk:
349
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this server')
350
                return HttpResponseRedirect(reverse("servers"))  
351
        form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
352
        if server:
353
            edit = True
354
                      
355
        return render_to_response('edumanage/servers_edit.html', { 'form': form, 'edit': edit },
356
                                  context_instance=RequestContext(request, base_response(request)))
357
    elif request.method == 'POST':
358
        request_data = request.POST.copy()
359
        try:         
360
            server = InstServer.objects.get(instid=inst, pk=server_pk)
361
            form = InstServerForm(request_data, instance=server)
362
        except InstServer.DoesNotExist:
363
            form = InstServerForm(request_data)
364
            if server_pk:
365
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this server')
366
                return HttpResponseRedirect(reverse("servers")) 
367
        
368
        if form.is_valid():
369
            instserverf = form.save()
370
            return HttpResponseRedirect(reverse("servers"))
371
        else:
372
            form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
373
        if server:
374
            edit = True
375
        return render_to_response('edumanage/servers_edit.html', { 'institution': inst, 'form': form, 'edit': edit },
376
                                  context_instance=RequestContext(request, base_response(request)))
377

    
378

    
379
@login_required
380
@never_cache
381
def del_server(request):
382
    if request.method == 'GET':
383
        user = request.user
384
        req_data = request.GET.copy()
385
        server_pk = req_data['server_pk']
386
        try:
387
            profile = user.get_profile()
388
            institution = profile.institution
389
        except UserProfile.DoesNotExist:
390
            resp['error'] = "Could not delete server. Not enough rights"
391
            return HttpResponse(json.dumps(resp), mimetype='application/json')
392
        resp = {}
393
        try:
394
            server = InstServer.objects.get(instid=institution, pk=server_pk)
395
        except InstServer.DoesNotExist:
396
            resp['error'] = "Could not get server or you have no rights to delete"
397
            return HttpResponse(json.dumps(resp), mimetype='application/json')
398
        try:
399
            server.delete()
400
        except:
401
            resp['error'] = "Could not delete server"
402
            return HttpResponse(json.dumps(resp), mimetype='application/json')
403
        resp['success'] = "Server successfully deleted"
404
        return HttpResponse(json.dumps(resp), mimetype='application/json')
405

    
406

    
407
@login_required
408
@never_cache
409
def realms(request):
410
    user = request.user
411
    servers = False
412
    try:
413
        profile = user.get_profile()
414
        inst = profile.institution
415
    except UserProfile.DoesNotExist:
416
        return HttpResponseRedirect(reverse("manage"))
417
    if inst:
418
        realms = InstRealm.objects.filter(instid=inst)
419
    if inst.ertype not in [1,3]:
420
        messages.add_message(request, messages.ERROR, 'Cannot add/edit Realms. Your institution should be either IdP or IdP/SP')
421
    return render_to_response('edumanage/realms.html', { 'realms': realms },
422
                                  context_instance=RequestContext(request, base_response(request)))
423

    
424

    
425
@login_required
426
@never_cache
427
def add_realm(request, realm_pk):
428
    user = request.user
429
    server = False
430
    realm = False
431
    edit = False
432
    try:
433
        profile = user.get_profile()
434
        inst = profile.institution
435
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
436
    except UserProfile.DoesNotExist:
437
        return HttpResponseRedirect(reverse("manage"))
438
    try:
439
        instdetails = inst.institutiondetails
440
    except InstitutionDetails.DoesNotExist:
441
        return HttpResponseRedirect(reverse("manage"))
442
    if inst.ertype not in [1,3]:
443
        messages.add_message(request, messages.ERROR, 'Cannot add/edit Realm. Your institution should be either IdP or IdP/SP')
444
        return render_to_response('edumanage/realms_edit.html', { 'edit': edit },
445
                                  context_instance=RequestContext(request, base_response(request)))
446
    if request.method == "GET":
447

    
448
        # Determine add or edit
449
        try:         
450
            realm = InstRealm.objects.get(instid=inst, pk=realm_pk)
451
            form = InstRealmForm(instance=realm)
452
        except InstRealm.DoesNotExist:
453
            form = InstRealmForm()
454
            if realm_pk:
455
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this realm')
456
                return HttpResponseRedirect(reverse("realms"))
457
        form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
458
        form.fields['proxyto'] = forms.ModelMultipleChoiceField(queryset=InstServer.objects.filter(pk__in=getInstServers(inst)))
459
        if realm:
460
            edit = True
461
        return render_to_response('edumanage/realms_edit.html', { 'form': form, 'edit': edit },
462
                                  context_instance=RequestContext(request, base_response(request)))
463
    elif request.method == 'POST':
464
        request_data = request.POST.copy()
465
        try:         
466
            realm = InstRealm.objects.get(instid=inst, pk=realm_pk)
467
            form = InstRealmForm(request_data, instance=realm)
468
        except InstRealm.DoesNotExist:
469
            form = InstRealmForm(request_data)
470
            if realm_pk:
471
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this realm')
472
                return HttpResponseRedirect(reverse("realms")) 
473
        if form.is_valid():
474
            instserverf = form.save()
475
            return HttpResponseRedirect(reverse("realms"))
476
        else:
477
            form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
478
            form.fields['proxyto'] = forms.ModelMultipleChoiceField(queryset=InstServer.objects.filter(pk__in=getInstServers(inst)))
479
        if realm:
480
            edit = True
481
        return render_to_response('edumanage/realms_edit.html', { 'institution': inst, 'form': form, 'edit': edit },
482
                                  context_instance=RequestContext(request, base_response(request)))
483

    
484

    
485
@login_required
486
@never_cache
487
def del_realm(request):
488
    if request.method == 'GET':
489
        user = request.user
490
        req_data = request.GET.copy()
491
        realm_pk = req_data['realm_pk']
492
        try:
493
            profile = user.get_profile()
494
            institution = profile.institution
495
        except UserProfile.DoesNotExist:
496
            resp['error'] = "Not enough rights"
497
            return HttpResponse(json.dumps(resp), mimetype='application/json')
498
        resp = {}
499
        try:
500
            realm = InstRealm.objects.get(instid=institution, pk=realm_pk)
501
        except InstRealm.DoesNotExist:
502
            resp['error'] = "Could not get realm or you have no rights to delete"
503
            return HttpResponse(json.dumps(resp), mimetype='application/json')
504
        try:
505
            realm.delete()
506
        except:
507
            resp['error'] = "Could not delete realm"
508
            return HttpResponse(json.dumps(resp), mimetype='application/json')
509
        resp['success'] = "Realm successfully deleted"
510
        return HttpResponse(json.dumps(resp), mimetype='application/json')
511

    
512

    
513
@login_required
514
@never_cache
515
def contacts(request):
516
    user = request.user
517
    servers = False
518
    instcontacts = []
519
    try:
520
        profile = user.get_profile()
521
        inst = profile.institution
522
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
523
    except UserProfile.DoesNotExist:
524
        return HttpResponseRedirect(reverse("manage"))
525
    try:
526
        instdetails = inst.institutiondetails
527
    except InstitutionDetails.DoesNotExist:
528
        return HttpResponseRedirect(reverse("manage"))
529
    if inst:
530
        instcontacts.extend([x.contact.pk for x in InstitutionContactPool.objects.filter(institution=inst)])
531
        contacts = Contact.objects.filter(pk__in=instcontacts)
532
    return render_to_response('edumanage/contacts.html', { 'contacts': contacts},
533
                                  context_instance=RequestContext(request, base_response(request)))
534

    
535

    
536
@login_required
537
@never_cache
538
def add_contact(request, contact_pk):
539
    user = request.user
540
    server = False
541
    edit = False
542
    contact = False
543
    try:
544
        profile = user.get_profile()
545
        inst = profile.institution
546
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
547
    except UserProfile.DoesNotExist:
548
        return HttpResponseRedirect(reverse("manage"))
549
    try:
550
        instdetails = inst.institutiondetails
551
    except InstitutionDetails.DoesNotExist:
552
        return HttpResponseRedirect(reverse("manage"))
553
    if request.method == "GET":
554

    
555
        # Determine add or edit
556
        try:         
557
            contactinst = InstitutionContactPool.objects.get(institution=inst, contact__pk=contact_pk)
558
            contact = contactinst.contact
559
            form = ContactForm(instance=contact)
560
        except InstitutionContactPool.DoesNotExist:
561
            form = ContactForm()
562
            if contact_pk:
563
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this contact')
564
                return HttpResponseRedirect(reverse("contacts"))
565
        if contact:
566
            edit = True
567
        return render_to_response('edumanage/contacts_edit.html', { 'form': form, "edit" : edit},
568
                                  context_instance=RequestContext(request, base_response(request)))
569
    elif request.method == 'POST':
570
        request_data = request.POST.copy()
571
        try:         
572
            contactinst = InstitutionContactPool.objects.get(institution=inst, contact__pk=contact_pk)
573
            contact = contactinst.contact
574
            form = ContactForm(request_data, instance=contact)
575
        except InstitutionContactPool.DoesNotExist:
576
            form = ContactForm(request_data)
577
            if contact_pk:
578
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this contact')
579
                return HttpResponseRedirect(reverse("contacts"))
580
        
581
        if form.is_valid():
582
            contact = form.save()
583
            instContPool, created = InstitutionContactPool.objects.get_or_create(contact=contact, institution=inst)
584
            instContPool.save()
585
            return HttpResponseRedirect(reverse("contacts"))
586
        if contact:
587
            edit = True
588
        return render_to_response('edumanage/contacts_edit.html', { 'form': form, "edit": edit},
589
                                  context_instance=RequestContext(request, base_response(request)))
590

    
591

    
592
@login_required
593
@never_cache
594
def del_contact(request):
595
    if request.method == 'GET':
596
        user = request.user
597
        req_data = request.GET.copy()
598
        contact_pk = req_data['contact_pk']
599
        try:
600
            profile = user.get_profile()
601
            institution = profile.institution
602
        except UserProfile.DoesNotExist:
603
            resp['error'] = "Could not delete contact. Not enough rights"
604
            return HttpResponse(json.dumps(resp), mimetype='application/json')
605
        resp = {}
606
        try:
607
            contactinst = InstitutionContactPool.objects.get(institution=institution, contact__pk=contact_pk)
608
            contact = contactinst.contact
609
        except InstitutionContactPool.DoesNotExist:
610
            resp['error'] = "Could not get contact or you have no rights to delete"
611
            return HttpResponse(json.dumps(resp), mimetype='application/json')
612
        try:
613
            for service in ServiceLoc.objects.filter(institutionid=institution):
614
                if (contact in service.contact.all() and len(service.contact.all()) == 1):
615
                    resp['error'] = "Could not delete contact. It is the only contact in service <b>%s</b>.<br>Fix it and try again" %service.get_name(lang="en")
616
                    return HttpResponse(json.dumps(resp), mimetype='application/json')
617
            if (contact in institution.institutiondetails.contact.all() and len(institution.institutiondetails.contact.all()) == 1):
618
                    resp['error'] = "Could not delete contact. It is the only contact your institution.<br>Fix it and try again"
619
                    return HttpResponse(json.dumps(resp), mimetype='application/json')
620
            contact.delete()
621
        except Exception:
622
            resp['error'] = "Could not delete contact"
623
            return HttpResponse(json.dumps(resp), mimetype='application/json')
624
        resp['success'] = "Contact successfully deleted"
625
        return HttpResponse(json.dumps(resp), mimetype='application/json')
626

    
627

    
628
@login_required
629
@never_cache
630
def instrealmmon(request):
631
    user = request.user
632
    servers = False
633
    instcontacts = []
634
    try:
635
        profile = user.get_profile()
636
        inst = profile.institution
637
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
638
    except UserProfile.DoesNotExist:
639
        return HttpResponseRedirect(reverse("manage"))
640
    try:
641
        instdetails = inst.institutiondetails
642
    except InstitutionDetails.DoesNotExist:
643
        return HttpResponseRedirect(reverse("manage"))
644
    if inst:
645
        instrealmmons = InstRealmMon.objects.filter(realm__instid=inst)
646
    return render_to_response('edumanage/instrealmmons.html', { 'realms': instrealmmons},
647
                                  context_instance=RequestContext(request, base_response(request)))
648

    
649
@login_required
650
@never_cache
651
def add_instrealmmon(request, instrealmmon_pk):
652
    user = request.user
653
    instrealmmon = False
654
    edit = False
655
    try:
656
        profile = user.get_profile()
657
        inst = profile.institution
658
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
659
    except UserProfile.DoesNotExist:
660
        return HttpResponseRedirect(reverse("manage"))
661
    try:
662
        instdetails = inst.institutiondetails
663
    except InstitutionDetails.DoesNotExist:
664
        return HttpResponseRedirect(reverse("manage"))
665
    if request.method == "GET":
666
        # Determine add or edit
667
        try:         
668
            instrealmmon = InstRealmMon.objects.get(pk=instrealmmon_pk, realm__instid=inst)
669
            form = InstRealmMonForm(instance=instrealmmon)
670
        except InstRealmMon.DoesNotExist:
671
            form = InstRealmMonForm()
672
            if instrealmmon_pk:
673
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this Monitoring Realm')
674
                return HttpResponseRedirect(reverse("instrealmmon"))
675
        if instrealmmon:
676
            edit = True
677
        form.fields['realm'] = forms.ModelChoiceField(queryset=InstRealm.objects.filter(instid=inst.pk).exclude(realm__startswith="*"), empty_label=None)
678
        return render_to_response('edumanage/instrealmmon_edit.html', { 'form': form, "edit" : edit},
679
                                  context_instance=RequestContext(request, base_response(request)))
680
    elif request.method == 'POST':
681
        request_data = request.POST.copy()
682
        try:         
683
            instrealmmon = InstRealmMon.objects.get(pk=instrealmmon_pk, realm__instid=inst)
684
            form = InstRealmMonForm(request_data, instance=instrealmmon)
685
        except InstRealmMon.DoesNotExist:
686
            form = InstRealmMonForm(request_data)
687
            if instrealmmon_pk:
688
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this Monitoring Realm')
689
                return HttpResponseRedirect(reverse("instrealmmon"))
690
        if form.is_valid():
691
            instrealmmonobj = form.save()
692
            return HttpResponseRedirect(reverse("instrealmmon"))
693
        if instrealmmon:
694
            edit = True
695
        form.fields['realm'] = forms.ModelChoiceField(queryset=InstRealm.objects.filter(instid=inst.pk).exclude(realm__startswith="*"), empty_label=None)
696
        return render_to_response('edumanage/instrealmmon_edit.html', { 'form': form, "edit": edit},
697
                                  context_instance=RequestContext(request, base_response(request)))
698

    
699
@login_required
700
@never_cache
701
def del_instrealmmon(request):
702
    if request.method == 'GET':
703
        user = request.user
704
        req_data = request.GET.copy()
705
        instrealmmon_pk = req_data['instrealmmon_pk']
706
        try:
707
            profile = user.get_profile()
708
            institution = profile.institution
709
        except UserProfile.DoesNotExist:
710
            resp['error'] = "Could not delete monitored realm. Not enough rights"
711
            return HttpResponse(json.dumps(resp), mimetype='application/json')
712
        resp = {}
713
        try:
714
            instrealmmon = InstRealmMon.objects.get(pk=instrealmmon_pk, realm__instid=institution)
715
            instrealmmon.delete()
716
        except InstRealmMon.DoesNotExist:
717
            resp['error'] = "Could not get monitored realm or you have no rights to delete"
718
            return HttpResponse(json.dumps(resp), mimetype='application/json')
719
        resp['success'] = "Contact successfully deleted"
720
        return HttpResponse(json.dumps(resp), mimetype='application/json')
721

    
722
@login_required
723
@never_cache
724
def add_monlocauthpar(request, instrealmmon_pk, monlocauthpar_pk):
725
    user = request.user
726
    monlocauthpar = False
727
    edit = False
728
    try:
729
        profile = user.get_profile()
730
        inst = profile.institution
731
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
732
    except UserProfile.DoesNotExist:
733
        return HttpResponseRedirect(reverse("manage"))
734
    try:
735
        instdetails = inst.institutiondetails
736
    except InstitutionDetails.DoesNotExist:
737
        return HttpResponseRedirect(reverse("manage"))
738
    if request.method == "GET":
739
        # Determine add or edit
740
        try:
741
            instrealmmon = InstRealmMon.objects.get(pk=instrealmmon_pk, realm__instid=inst)
742
            monlocauthpar = MonLocalAuthnParam.objects.get(pk=monlocauthpar_pk, instrealmmonid__realm__instid=inst)
743
            form = MonLocalAuthnParamForm(instance=monlocauthpar)
744
        except MonLocalAuthnParam.DoesNotExist:
745
            form = MonLocalAuthnParamForm()
746
            if monlocauthpar_pk:
747
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this Monitoring Realm Parameters')
748
                return HttpResponseRedirect(reverse("instrealmmon"))
749
        except InstRealmMon.DoesNotExist:
750
            if instrealmmon_pk:
751
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this Monitoring Realm Parameters')
752
            return HttpResponseRedirect(reverse("instrealmmon"))
753
        if monlocauthpar:
754
            edit = True
755
        form.fields['instrealmmonid'] = forms.ModelChoiceField(queryset=InstRealmMon.objects.filter(pk=instrealmmon.pk), empty_label=None)
756
        return render_to_response('edumanage/monlocauthpar_edit.html', { 'form': form, "edit" : edit, "realm":instrealmmon },
757
                                  context_instance=RequestContext(request, base_response(request)))
758
    elif request.method == 'POST':
759
        request_data = request.POST.copy()
760
        try:         
761
            instrealmmon = InstRealmMon.objects.get(pk=instrealmmon_pk, realm__instid=inst)
762
            monlocauthpar = MonLocalAuthnParam.objects.get(pk=monlocauthpar_pk, instrealmmonid__realm__instid=inst)
763
            form = MonLocalAuthnParamForm(request_data, instance=monlocauthpar)
764
        except MonLocalAuthnParam.DoesNotExist:
765
            form = MonLocalAuthnParamForm(request_data)
766
            if monlocauthpar_pk:
767
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this Monitoring Realm Parameters')
768
                return HttpResponseRedirect(reverse("instrealmmon"))
769
        except InstRealmMon.DoesNotExist:
770
            if instrealmmon_pk:
771
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this Monitoring Realm Parameters')
772
            return HttpResponseRedirect(reverse("instrealmmon"))
773
        if form.is_valid():
774
            monlocauthparobj = form.save()
775
            return HttpResponseRedirect(reverse("instrealmmon"))
776
        if monlocauthpar:
777
            edit = True
778
        form.fields['instrealmmonid'] = forms.ModelChoiceField(queryset=InstRealmMon.objects.filter(pk=instrealmmon.pk), empty_label=None)
779
        return render_to_response('edumanage/monlocauthpar_edit.html', { 'form': form, "edit": edit, "realm":instrealmmon},
780
                                  context_instance=RequestContext(request, base_response(request)))
781

    
782
@login_required
783
@never_cache
784
def del_monlocauthpar(request):
785
    if request.method == 'GET':
786
        user = request.user
787
        req_data = request.GET.copy()
788
        monlocauthpar_pk = req_data['monlocauthpar_pk']
789
        try:
790
            profile = user.get_profile()
791
            institution = profile.institution
792
        except UserProfile.DoesNotExist:
793
            resp['error'] = "Could not delete realm monitoring parameters. Not enough rights"
794
            return HttpResponse(json.dumps(resp), mimetype='application/json')
795
        resp = {}
796
        try:
797
            monlocauthpar = MonLocalAuthnParam.objects.get(pk=monlocauthpar_pk, instrealmmonid__realm__instid=institution)
798
            monlocauthpar.delete()
799
        except MonLocalAuthnParam.DoesNotExist:
800
            resp['error'] = "Could not get realm monitoring parameters or you have no rights to delete"
801
            return HttpResponse(json.dumps(resp), mimetype='application/json')
802
        resp['success'] = "Contact successfully deleted"
803
        return HttpResponse(json.dumps(resp), mimetype='application/json')
804

    
805
@login_required
806
@never_cache
807
def adduser(request):
808
    user = request.user
809
    try:
810
        profile = user.get_profile()
811
        inst = profile.institution
812
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
813
    except UserProfile.DoesNotExist:
814
        return HttpResponseRedirect(reverse("manage"))
815

    
816
    if request.method == "GET":
817
        form = ContactForm()
818
        return render_to_response('edumanage/add_user.html', { 'form' : form },
819
                                  context_instance=RequestContext(request, base_response(request)))
820
    elif request.method == 'POST':
821
        request_data = request.POST.copy()
822
        form = ContactForm(request_data)
823
        if form.is_valid():
824
            contact = form.save()
825
            instContPool = InstitutionContactPool(contact=contact, institution=inst)
826
            instContPool.save()
827
            response_data = {}
828
            response_data['value'] = "%s" %contact.pk
829
            response_data['text'] = "%s" %contact
830
            return HttpResponse(json.dumps(response_data), mimetype='application/json')
831
        else:
832
            return render_to_response('edumanage/add_user.html', {'form': form,},
833
                                      context_instance=RequestContext(request, base_response(request)))
834

    
835

    
836
@login_required
837
def base_response(request):
838
    user = request.user
839
    inst = []
840
    server = []
841
    services = []
842
    instrealms = []
843
    instcontacts = []
844
    contacts = []
845
    institution = False
846
    institution_exists = False
847
    try:
848
        profile = user.get_profile()
849
        institution = profile.institution
850
        institution_exists = True
851
    except UserProfile.DoesNotExist:
852
        institution_exists = False
853
    try:
854
        inst.append(institution)
855
        server = InstServer.objects.filter(instid=institution)
856
        services = ServiceLoc.objects.filter(institutionid=institution)
857
        instrealms = InstRealm.objects.filter(instid=institution)
858
        instcontacts.extend([x.contact.pk for x in InstitutionContactPool.objects.filter(institution=institution)])
859
        contacts = Contact.objects.filter(pk__in=instcontacts)
860
        instrealmmons = InstRealmMon.objects.filter(realm__instid=institution)
861
    except:
862
        pass
863
    try:
864
        instututiondetails = institution.institutiondetails
865
    except:
866
        instututiondetails = False
867
    return { 
868
            'inst_num': len(inst),
869
            'servers_num': len(server),
870
            'services_num': len(services),
871
            'realms_num': len(instrealms),
872
            'contacts_num': len(contacts),
873
            'monrealms_num': len(instrealmmons),
874
            'institution': institution,
875
            'institutiondetails': instututiondetails,
876
            'institution_exists': institution_exists,
877
            
878
        }
879

    
880

    
881
@login_required
882
@never_cache
883
def get_service_points(request):
884
    if request.method == "GET":
885
        user = request.user
886
        try:
887
            profile = user.get_profile()
888
            inst = profile.institution
889
        except UserProfile.DoesNotExist:
890
            inst = False
891
            return HttpResponseNotFound('<h1>Something went really wrong</h1>')
892
        servicelocs = ServiceLoc.objects.filter(institutionid=inst)
893
        
894
        locs = []
895
        for sl in servicelocs:
896
            response_location = {}
897
            response_location['lat'] = u"%s"%sl.latitude
898
            response_location['lng'] = u"%s"%sl.longitude
899
            response_location['address'] = u"%s<br>%s"%(sl.address_street, sl.address_city)
900
            if len(sl.enc_level[0]) != 0:
901
                response_location['enc'] = u"%s"%(','.join(sl.enc_level))
902
            else:
903
                response_location['enc'] = u"-"
904
            response_location['AP_no'] = u"%s"%(sl.AP_no)
905
            response_location['name'] = sl.loc_name.get(lang='en').name
906
            response_location['port_restrict'] = u"%s"%(sl.port_restrict)
907
            response_location['transp_proxy'] = u"%s"%(sl.transp_proxy)
908
            response_location['IPv6'] = u"%s"%(sl.IPv6)
909
            response_location['NAT'] = u"%s"%(sl.NAT)
910
            response_location['wired'] = u"%s"%(sl.wired)
911
            response_location['SSID'] = u"%s"%(sl.SSID)
912
            response_location['key'] = u"%s"%sl.pk
913
            locs.append(response_location)
914
        return HttpResponse(json.dumps(locs), mimetype='application/json')
915
    else:
916
       return HttpResponseNotFound('<h1>Something went really wrong</h1>')
917

    
918
@never_cache
919
def get_all_services(request):
920
    lang = request.LANGUAGE_CODE
921
    servicelocs = ServiceLoc.objects.all()
922
    locs = []
923
    for sl in servicelocs:
924
        response_location = {}
925
        response_location['lat'] = u"%s"%sl.latitude
926
        response_location['lng'] = u"%s"%sl.longitude
927
        response_location['address'] = u"%s<br>%s"%(sl.address_street, sl.address_city)
928
        if len(sl.enc_level[0]) != 0:
929
            response_location['enc'] = u"%s"%(','.join(sl.enc_level))
930
        else:
931
            response_location['enc'] = u"-"
932
        response_location['AP_no'] = u"%s"%(sl.AP_no)
933
        try:
934
            response_location['inst'] = sl.institutionid.org_name.get(lang=lang).name
935
        except Name_i18n.DoesNotExist:
936
            response_location['inst'] = sl.institutionid.org_name.get(lang='en').name
937
        try:
938
            response_location['name'] = sl.loc_name.get(lang=lang).name
939
        except Name_i18n.DoesNotExist:
940
            response_location['name'] = sl.loc_name.get(lang='en').name
941
        response_location['port_restrict'] = u"%s"%(sl.port_restrict)
942
        response_location['transp_proxy'] = u"%s"%(sl.transp_proxy)
943
        response_location['IPv6'] = u"%s"%(sl.IPv6)
944
        response_location['NAT'] = u"%s"%(sl.NAT)
945
        response_location['wired'] = u"%s"%(sl.wired)
946
        response_location['SSID'] = u"%s"%(sl.SSID)
947
        response_location['key'] = u"%s"%sl.pk
948
        locs.append(response_location)
949
    return HttpResponse(json.dumps(locs), mimetype='application/json')
950

    
951
@never_cache
952
def user_login(request):
953
    try:
954
        error_username = False
955
        error_orgname = False
956
        error_entitlement = False
957
        error_mail = False
958
        has_entitlement = False
959
        error = ''
960
        username = request.META['HTTP_EPPN']
961
        if not username:
962
            error_username = True
963
        firstname = request.META['HTTP_SHIB_INETORGPERSON_GIVENNAME']
964
        lastname = request.META['HTTP_SHIB_PERSON_SURNAME']
965
        mail = request.META['HTTP_SHIB_INETORGPERSON_MAIL']
966
        #organization = request.META['HTTP_SHIB_HOMEORGANIZATION']
967
        entitlement = request.META['HTTP_SHIB_EP_ENTITLEMENT']
968
        if settings.SHIB_AUTH_ENTITLEMENT in entitlement.split(";"):
969
            has_entitlement = True
970
        if not has_entitlement:
971
            error_entitlement = True
972
#        if not organization:
973
#            error_orgname = True
974
        if not mail:
975
            error_mail = True
976
        if error_username:
977
            error = _("Your idP should release the eduPersonPrincipalName attribute towards this service<br>")
978
        if error_entitlement:
979
            error = error + _("Your idP should release an appropriate eduPersonEntitlement attribute towards this service<br>")
980
        if error_mail:
981
            error = error + _("Your idP should release the mail attribute towards this service")
982
        if error_username or error_orgname or error_entitlement or error_mail:
983
            return render_to_response('status.html', {'error': error, "missing_attributes": True},
984
                                  context_instance=RequestContext(request))
985
        try:
986
            user = User.objects.get(username__exact=username)
987
            user.email = mail
988
            user.first_name = firstname
989
            user.last_name = lastname
990
            user.save()
991
            user_exists = True
992
        except User.DoesNotExist:
993
            user_exists = False
994
        user = authenticate(username=username, firstname=firstname, lastname=lastname, mail=mail, authsource='shibboleth')
995
        if user is not None:
996
            try:
997
                profile = user.get_profile()
998
                inst = profile.institution
999
            except UserProfile.DoesNotExist:
1000
                form = UserProfileForm()
1001
                form.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(pk=user.pk), empty_label=None)
1002
                form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.all(), empty_label=None)
1003
                return render_to_response('registration/select_institution.html', {'form': form}, context_instance=RequestContext(request))
1004
            if user.is_active:
1005
               login(request, user)
1006
               return HttpResponseRedirect(reverse("manage"))
1007
            else:
1008
                status = _("User account <strong>%s</strong> is pending activation. Administrators have been notified and will activate this account within the next days. <br>If this account has remained inactive for a long time contact your technical coordinator or GRNET Helpdesk") %user.username
1009
                return render_to_response('status.html', {'status': status, 'inactive': True},
1010
                                  context_instance=RequestContext(request))
1011
        else:
1012
            error = _("Something went wrong during user authentication. Contact your administrator %s" %user)
1013
            return render_to_response('status.html', {'error': error,},
1014
                                  context_instance=RequestContext(request))
1015
    except Exception:
1016
        error = _("Invalid login procedure")
1017
        return render_to_response('status.html', {'error': error,},
1018
                                  context_instance=RequestContext(request))
1019

    
1020
@never_cache
1021
def geolocate(request):
1022
    return render_to_response('front/geolocate.html',
1023
                                  context_instance=RequestContext(request))
1024
@never_cache
1025
def participants(request):
1026
    institutions = Institution.objects.all()
1027
    dets = []
1028
    for i in institutions:
1029
        try:
1030
            dets.append(i.institutiondetails)
1031
        except InstitutionDetails.DoesNotExist:
1032
            pass
1033
    return render_to_response('front/participants.html', {'institutions': dets},
1034
                                  context_instance=RequestContext(request))
1035
@never_cache
1036
def selectinst(request):
1037
    if request.method == 'POST':
1038
        request_data = request.POST.copy()
1039
        user = request_data['user']
1040
        try:
1041
            existingProfile = UserProfile.objects.get(user=user)
1042
            error = _("Violation warning: User account is already associated with an institution.The event has been logged and our administrators will be notified about it")
1043
            return render_to_response('status.html', {'error': error, 'inactive': True},
1044
                                  context_instance=RequestContext(request))
1045
        except UserProfile.DoesNotExist:
1046
            pass
1047
            
1048
        form = UserProfileForm(request_data)
1049
        if form.is_valid():
1050
            userprofile = form.save()
1051
            user_activation_notify(userprofile)
1052
            error = _("User account <strong>%s</strong> is pending activation. Administrators have been notified and will activate this account within the next days. <br>If this account has remained inactive for a long time contact your technical coordinator or GRNET Helpdesk") %userprofile.user.username
1053
            return render_to_response('status.html', {'status': error, 'inactive': True},
1054
                                  context_instance=RequestContext(request))
1055
        else:
1056
            form.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(pk=user.pk), empty_label=None)
1057
            form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.all(), empty_label=None)
1058
            return render_to_response('registration/select_institution.html', {'form': form}, context_instance=RequestContext(request))
1059

    
1060

    
1061
def user_activation_notify(userprofile):
1062
    current_site = Site.objects.get_current()
1063
    subject = render_to_string('registration/activation_email_subject.txt',
1064
                                   { 'site': current_site })
1065
    # Email subject *must not* contain newlines
1066
    subject = ''.join(subject.splitlines())
1067
    registration_profile = RegistrationProfile.objects.create_profile(userprofile.user)
1068
    message = render_to_string('registration/activation_email.txt',
1069
                                   { 'activation_key': registration_profile.activation_key,
1070
                                     'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
1071
                                     'site': current_site,
1072
                                     'user': userprofile.user,
1073
                                     'institution': userprofile.institution })
1074
    send_new_mail(settings.EMAIL_SUBJECT_PREFIX + subject, 
1075
                              message, settings.SERVER_EMAIL,
1076
                             settings.NOTIFY_ADMIN_MAILS, [])
1077
@never_cache
1078
def closest(request):
1079
    if request.method == 'GET':
1080
        locs = []
1081
        request_data = request.GET.copy()
1082
        response_location = {}
1083
        if 'lat' in request.GET and 'lng' in request.GET:
1084
            response_location["lat"] = request_data['lat']
1085
            response_location["lng"] = request_data['lng']
1086
        else:
1087
            response = {"status":"Cannot parse a request without longitude or latitude. Use ?lng=<langitude>&lat=<latitude>&_=<random_num> in your query"}
1088
            return HttpResponse(json.dumps(response), mimetype='application/json')
1089
        lat = float(request_data['lat'])
1090
        lng = float(request_data['lng'])
1091
        R = 6371
1092
        distances = {}
1093
        closestMarker = {}
1094
        closest = -1
1095
        points = getPoints()
1096
        for (counter, i) in enumerate(points):
1097
            pointname = i['text']
1098
            pointlng = i['lng'] 
1099
            pointlat = i['lat']
1100
            pointtext = i['text']
1101
            dLat = rad(float(pointlat)-float(lat))
1102
            dLong = rad(float(pointlng)-float(lng))
1103
            a = math.sin(dLat/2) * math.sin(dLat/2) + math.cos(rad(lat)) * math.cos(rad(float(pointlat))) * math.sin(dLong/2) * math.sin(dLong/2) 
1104
            c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
1105
            d = R * c
1106
            distances[counter] = d
1107
            if (closest == -1 or d < distances[closest]):
1108
                closest = counter
1109
                closestMarker = {"name": pointname, "lat": pointlat, "lng": pointlng, "text": pointtext}
1110
        return HttpResponse(json.dumps(closestMarker), mimetype='application/json')
1111
    else:
1112
        response = {"status":"Use a GET method for your request"}
1113
        return HttpResponse(json.dumps(response), mimetype='application/json')
1114

    
1115
@never_cache
1116
def worldPoints(request):
1117
    if request.method == 'GET':
1118
        points = getPoints()
1119
        return HttpResponse(json.dumps(points), mimetype='application/json')
1120

    
1121
@never_cache
1122
def world(request):
1123
        return render_to_response('front/world.html',
1124
                                  context_instance=RequestContext(request))
1125

    
1126

    
1127
@never_cache
1128
def managementPage(request):
1129
    return render_to_response('front/management.html',
1130
                                  context_instance=RequestContext(request))
1131

    
1132
def getPoints():
1133
    points = cache.get('points')
1134
    if points:
1135
        points = bz2.decompress(points)
1136
        return json.loads(points)
1137
    else:
1138
        point_list = []
1139
        doc = ET.parse(settings.KML_FILE)
1140
        root = doc.getroot()
1141
        r = root.getchildren()[0]
1142
        for (counter, i) in enumerate(r.getchildren()):
1143
            if "id" in i.keys():
1144
                j = i.getchildren()
1145
                pointname = j[0].text
1146
                point = j[2].getchildren()[0].text
1147
                pointlng, pointlat, pointele = point.split(',')
1148
                Marker = {"name": pointname, "lat": pointlat, "lng": pointlng, "text": j[1].text}
1149
                point_list.append(Marker);
1150
        points = json.dumps(point_list)
1151
        cache.set('points', bz2.compress(points), 60 * 3600 * 24)
1152
        return json.loads(points)
1153

    
1154

    
1155
@never_cache
1156
def instxml(request):
1157
    ET._namespace_map["http://www.w3.org/2001/XMLSchema-instance"] = 'xsi'
1158
    root = ET.Element("institutions")
1159
    NS_XSI = "{http://www.w3.org/2001/XMLSchema-instance}"
1160
    root.set(NS_XSI + "noNamespaceSchemaLocation", "institution.xsd")
1161
    #root.attrib["xsi:noNamespaceSchemaLocation"] = "institution.xsd"
1162
    institutions = Institution.objects.all()
1163
    for institution in institutions:
1164
        try:
1165
            inst = institution.institutiondetails
1166
            if not inst:
1167
                pass
1168
        except InstitutionDetails.DoesNotExist:
1169
            pass
1170
        
1171
        instElement = ET.SubElement(root, "institution")
1172
        
1173
        instCountry = ET.SubElement(instElement, "country")
1174
        instCountry.text = ("%s" %inst.institution.realmid.country).upper()
1175
        
1176
        instType = ET.SubElement(instElement, "type")
1177
        instType.text = "%s" %inst.institution.ertype
1178
        
1179
        for realm in institution.instrealm_set.all():
1180
            instRealm = ET.SubElement(instElement, "inst_realm")
1181
            instRealm.text = realm.realm
1182
        
1183
        for name in inst.institution.org_name.all():
1184
            instOrgName = ET.SubElement(instElement, "org_name")
1185
            instOrgName.attrib["lang"] = name.lang
1186
            instOrgName.text = u"%s" %name.name
1187
        
1188
        instAddress = ET.SubElement(instElement, "address")
1189
        
1190
        instAddrStreet = ET.SubElement(instAddress, "street")
1191
        instAddrStreet.text = inst.address_street
1192
        
1193
        instAddrCity = ET.SubElement(instAddress, "city")
1194
        instAddrCity.text = inst.address_city
1195
        
1196
        for contact in inst.contact.all():
1197
            instContact = ET.SubElement(instElement, "contact")
1198
            
1199
            instContactName = ET.SubElement(instContact, "name")
1200
            instContactName.text = "%s" %(contact.name)
1201
            
1202
            instContactEmail = ET.SubElement(instContact, "email")
1203
            instContactEmail.text = contact.email
1204
            
1205
            instContactPhone = ET.SubElement(instContact, "phone")
1206
            instContactPhone.text = contact.phone
1207
        
1208
        for url in inst.url.all():
1209
            instUrl = ET.SubElement(instElement, "%s_URL"%(url.urltype))
1210
            instUrl.attrib["lang"] = url.lang
1211
            instUrl.text = url.url
1212
        
1213
        instTs = ET.SubElement(instElement, "ts")
1214
        instTs.text = "%s" %inst.ts.isoformat()
1215
        #Let's go to Institution Service Locations
1216

    
1217
        for serviceloc in inst.institution.serviceloc_set.all():
1218
            instLocation = ET.SubElement(instElement, "location")
1219
            
1220
            instLong = ET.SubElement(instLocation, "longitude")
1221
            instLong.text = "%s" %serviceloc.longitude
1222
            
1223
            instLat = ET.SubElement(instLocation, "latitude")
1224
            instLat.text = "%s" %serviceloc.latitude
1225
            
1226
            for instlocname in serviceloc.loc_name.all():
1227
                instLocName = ET.SubElement(instLocation, "loc_name")
1228
                instLocName.attrib["lang"] = instlocname.lang
1229
                instLocName.text = instlocname.name
1230
            
1231
            instLocAddress = ET.SubElement(instLocation, "address")
1232
        
1233
            instLocAddrStreet = ET.SubElement(instLocAddress, "street")
1234
            instLocAddrStreet.text = serviceloc.address_street
1235
        
1236
            instLocAddrCity = ET.SubElement(instLocAddress, "city")
1237
            instLocAddrCity.text = serviceloc.address_city
1238
            
1239
            for contact in serviceloc.contact.all():
1240
                instLocContact = ET.SubElement(instLocation, "contact")
1241
                
1242
                instLocContactName = ET.SubElement(instLocContact, "name")
1243
                instLocContactName.text = "%s" %(contact.name)
1244
                
1245
                instLocContactEmail = ET.SubElement(instLocContact, "email")
1246
                instLocContactEmail.text = contact.email
1247
                
1248
                instLocContactPhone = ET.SubElement(instLocContact, "phone")
1249
                instLocContactPhone.text = contact.phone
1250
            
1251
            instLocSSID = ET.SubElement(instLocation, "SSID")
1252
            instLocSSID.text = serviceloc.SSID
1253
            
1254
            instLocEncLevel = ET.SubElement(instLocation, "enc_level")
1255
            instLocEncLevel.text = ', '.join(serviceloc.enc_level)
1256
            
1257
            instLocPortRestrict = ET.SubElement(instLocation, "port_restrict")
1258
            instLocPortRestrict.text = ("%s" %serviceloc.port_restrict).lower()
1259
            
1260
            instLocTransProxy = ET.SubElement(instLocation, "transp_proxy")
1261
            instLocTransProxy.text = ("%s" %serviceloc.transp_proxy).lower()
1262
            
1263
            instLocIpv6 = ET.SubElement(instLocation, "IPv6")
1264
            instLocIpv6.text = ("%s" %serviceloc.IPv6).lower()
1265
            
1266
            instLocNAT = ET.SubElement(instLocation, "NAT")
1267
            instLocNAT.text = ("%s" %serviceloc.NAT).lower()
1268
            
1269
            instLocAP_no = ET.SubElement(instLocation, "AP_no")
1270
            instLocAP_no.text = "%s" %int(serviceloc.AP_no)
1271
            
1272
            instLocWired = ET.SubElement(instLocation, "wired")
1273
            instLocWired.text = ("%s" %serviceloc.wired).lower()
1274
            
1275
            for url in serviceloc.url.all():
1276
                instLocUrl = ET.SubElement(instLocation, "%s_URL"%(url.urltype))
1277
                instLocUrl.attrib["lang"] = url.lang
1278
                instLocUrl.text = url.url
1279
            
1280
    return render_to_response("general/institution.xml", {"xml":to_xml(root)},context_instance=RequestContext(request,), mimetype="application/xml")
1281
        
1282
@never_cache
1283
def realmxml(request):
1284
    realm = Realm.objects.all()[0]
1285
    ET._namespace_map["http://www.w3.org/2001/XMLSchema-instance"] = 'xsi'
1286
    root = ET.Element("realms")
1287
    NS_XSI = "{http://www.w3.org/2001/XMLSchema-instance}"
1288
    root.set(NS_XSI + "noNamespaceSchemaLocation", "realm.xsd")
1289
    #root.attrib["xsi:noNamespaceSchemaLocation"] = "institution.xsd"
1290
    realmElement = ET.SubElement(root, "realm")
1291
    
1292
    realmCountry = ET.SubElement(realmElement, "country")
1293
    realmCountry.text = realm.country.upper()
1294
        
1295
    realmStype = ET.SubElement(realmElement, "stype")
1296
    realmStype.text = "%s" %realm.stype
1297
    
1298
    for name in realm.org_name.all():
1299
        realmOrgName = ET.SubElement(realmElement, "org_name")
1300
        realmOrgName.attrib["lang"] = name.lang
1301
        realmOrgName.text = u"%s" %name.name
1302
    
1303
    realmAddress = ET.SubElement(realmElement, "address")
1304
        
1305
    realmAddrStreet = ET.SubElement(realmAddress, "street")
1306
    realmAddrStreet.text = realm.address_street
1307
    
1308
    realmAddrCity = ET.SubElement(realmAddress, "city")
1309
    realmAddrCity.text = realm.address_city
1310
    
1311
    for contact in realm.contact.all():
1312
        realmContact = ET.SubElement(realmElement, "contact")
1313
        
1314
        realmContactName = ET.SubElement(realmContact, "name")
1315
        realmContactName.text = "%s" %(contact.name)
1316
        
1317
        realmContactEmail = ET.SubElement(realmContact, "email")
1318
        realmContactEmail.text = contact.email
1319
        
1320
        realmContactPhone = ET.SubElement(realmContact, "phone")
1321
        realmContactPhone.text = contact.phone
1322
    
1323
    for url in realm.url.all():
1324
        realmUrl = ET.SubElement(realmElement, "%s_URL"%(url.urltype))
1325
        realmUrl.attrib["lang"] = url.lang
1326
        realmUrl.text = url.url
1327
    
1328
    instTs = ET.SubElement(realmElement, "ts")
1329
    instTs.text = "%s" %realm.ts.isoformat()
1330
    
1331
    return render_to_response("general/realm.xml", {"xml":to_xml(root)},context_instance=RequestContext(request,), mimetype="application/xml")
1332

    
1333
@never_cache
1334
def realmdataxml(request):
1335
    realm = Realm.objects.all()[0]
1336
    ET._namespace_map["http://www.w3.org/2001/XMLSchema-instance"] = 'xsi'
1337
    root = ET.Element("realm_data_root")
1338
    NS_XSI = "{http://www.w3.org/2001/XMLSchema-instance}"
1339
    root.set(NS_XSI + "noNamespaceSchemaLocation", "realm_data.xsd")
1340
    
1341
    realmdataElement = ET.SubElement(root, "realm_data")
1342
    
1343
    realmCountry = ET.SubElement(realmdataElement, "country")
1344
    realmCountry.text = realm.country.upper()
1345
    
1346
    nIdpCountry = ET.SubElement(realmdataElement, "number_IdP")
1347
    nIdpCountry.text = "%s" %len(realm.institution_set.filter(ertype=1))
1348
    
1349
    nSPCountry = ET.SubElement(realmdataElement, "number_SP")
1350
    nSPCountry.text = "%s" %len(realm.institution_set.filter(ertype=2))
1351
    
1352
    nSPIdpCountry = ET.SubElement(realmdataElement, "number_SPIdP")
1353
    nSPIdpCountry.text = "%s" %len(realm.institution_set.filter(ertype=3))
1354
    
1355
    ninstCountry = ET.SubElement(realmdataElement, "number_inst")
1356
    ninstCountry.text = "%s" %len(realm.institution_set.all())
1357
    
1358
    nuserCountry = ET.SubElement(realmdataElement, "number_user")
1359
    insts = realm.institution_set.all()
1360
    users = 0
1361
    for inst in insts:
1362
        try:
1363
            if inst.institutiondetails.number_user:
1364
                users = users + inst.institutiondetails.number_user
1365
        except InstitutionDetails.DoesNotExist:
1366
            pass
1367
    nuserCountry.text = "%s" %users
1368
    
1369
    nIdCountry = ET.SubElement(realmdataElement, "number_id")
1370
    insts = realm.institution_set.all()
1371
    ids = 0
1372
    for inst in insts:
1373
        try:
1374
            if inst.institutiondetails.number_id:
1375
                ids = ids + inst.institutiondetails.number_id
1376
        except InstitutionDetails.DoesNotExist:
1377
            pass
1378
    nIdCountry.text = "%s" %ids
1379
    
1380
    # Get the latest ts from all tables...
1381
    datetimes = []
1382
    if InstitutionDetails.objects.aggregate(Max('ts'))['ts__max']:
1383
        datetimes.append(InstitutionDetails.objects.aggregate(Max('ts'))['ts__max'])
1384
    if Realm.objects.aggregate(Max('ts'))['ts__max']:
1385
        datetimes.append(Realm.objects.aggregate(Max('ts'))['ts__max'])
1386
    if InstServer.objects.aggregate(Max('ts'))['ts__max']:
1387
        datetimes.append(InstServer.objects.aggregate(Max('ts'))['ts__max'])
1388
    if ServiceLoc.objects.aggregate(Max('ts'))['ts__max']:
1389
        datetimes.append(ServiceLoc.objects.aggregate(Max('ts'))['ts__max'])
1390
    if len(datetimes) == 0:
1391
        datetimes.append(datetime.datetime.now())
1392
    instTs = ET.SubElement(realmdataElement, "ts")
1393
    instTs.text = "%s" %max(datetimes).isoformat()
1394
    
1395
    
1396
    return render_to_response("general/realm_data.xml", {"xml":to_xml(root)},context_instance=RequestContext(request,), mimetype="application/xml")
1397

    
1398
def to_xml(ele, encoding="UTF-8"):
1399
    "Convert and return the XML for an *ele* (:class:`~xml.etree.ElementTree.Element`) with specified *encoding*."
1400
    xml = ET.tostring(ele, encoding)
1401
    return xml if xml.startswith('<?xml') else '<?xml version="1.0" encoding="%s"?>%s' % (encoding, xml)
1402
    
1403
def getInstContacts(inst):
1404
    contacts = InstitutionContactPool.objects.filter(institution=inst)
1405
    contact_pks = []
1406
    for contact in contacts:
1407
        contact_pks.append(contact.contact.pk)
1408
    return list(set(contact_pks))
1409

    
1410
def getInstServers(inst):
1411
    servers = InstServer.objects.filter(instid=inst)
1412
    server_pks = []
1413
    for server in servers:
1414
        server_pks.append(server.pk)
1415
    return list(set(server_pks))
1416

    
1417

    
1418
def rad(x):
1419
    return x*math.pi/180
1420

    
1421
def send_new_mail(subject, message, from_email, recipient_list, bcc_list):
1422
    return EmailMessage(subject, message, from_email, recipient_list, bcc_list).send()
1423