Statistics
| Branch: | Tag: | Revision:

root / edumanage / views.py @ 20802476

History | View | Annotate | Download (63.1 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
            response_location['enc'] = u"%s"%(','.join(sl.enc_level))
901
            response_location['AP_no'] = u"%s"%(sl.AP_no)
902
            response_location['name'] = sl.loc_name.get(lang='en').name
903
            response_location['port_restrict'] = u"%s"%(sl.port_restrict)
904
            response_location['transp_proxy'] = u"%s"%(sl.transp_proxy)
905
            response_location['IPv6'] = u"%s"%(sl.IPv6)
906
            response_location['NAT'] = u"%s"%(sl.NAT)
907
            response_location['wired'] = u"%s"%(sl.wired)
908
            response_location['SSID'] = u"%s"%(sl.SSID)
909
            response_location['key'] = u"%s"%sl.pk
910
            locs.append(response_location)
911
        return HttpResponse(json.dumps(locs), mimetype='application/json')
912
    else:
913
       return HttpResponseNotFound('<h1>Something went really wrong</h1>')
914

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

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

    
1016
@never_cache
1017
def geolocate(request):
1018
    return render_to_response('front/geolocate.html',
1019
                                  context_instance=RequestContext(request))
1020
@never_cache
1021
def participants(request):
1022
    institutions = Institution.objects.all()
1023
    dets = []
1024
    for i in institutions:
1025
        try:
1026
            dets.append(i.institutiondetails)
1027
        except InstitutionDetails.DoesNotExist:
1028
            pass
1029
    return render_to_response('front/participants.html', {'institutions': dets},
1030
                                  context_instance=RequestContext(request))
1031
@never_cache
1032
def selectinst(request):
1033
    if request.method == 'POST':
1034
        request_data = request.POST.copy()
1035
        user = request_data['user']
1036
        try:
1037
            existingProfile = UserProfile.objects.get(user=user)
1038
            error = _("Violation warning: User account is already associated with an institution.The event has been logged and our administrators will be notified about it")
1039
            return render_to_response('status.html', {'error': error, 'inactive': True},
1040
                                  context_instance=RequestContext(request))
1041
        except UserProfile.DoesNotExist:
1042
            pass
1043
            
1044
        form = UserProfileForm(request_data)
1045
        if form.is_valid():
1046
            userprofile = form.save()
1047
            user_activation_notify(userprofile)
1048
            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
1049
            return render_to_response('status.html', {'status': error, 'inactive': True},
1050
                                  context_instance=RequestContext(request))
1051
        else:
1052
            form.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(pk=user.pk), empty_label=None)
1053
            form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.all(), empty_label=None)
1054
            return render_to_response('registration/select_institution.html', {'form': form}, context_instance=RequestContext(request))
1055

    
1056

    
1057
def user_activation_notify(userprofile):
1058
    current_site = Site.objects.get_current()
1059
    subject = render_to_string('registration/activation_email_subject.txt',
1060
                                   { 'site': current_site })
1061
    # Email subject *must not* contain newlines
1062
    subject = ''.join(subject.splitlines())
1063
    registration_profile = RegistrationProfile.objects.create_profile(userprofile.user)
1064
    message = render_to_string('registration/activation_email.txt',
1065
                                   { 'activation_key': registration_profile.activation_key,
1066
                                     'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
1067
                                     'site': current_site,
1068
                                     'user': userprofile.user,
1069
                                     'institution': userprofile.institution })
1070
    send_new_mail(settings.EMAIL_SUBJECT_PREFIX + subject, 
1071
                              message, settings.SERVER_EMAIL,
1072
                             settings.NOTIFY_ADMIN_MAILS, [])
1073
@never_cache
1074
def closest(request):
1075
    if request.method == 'GET':
1076
        locs = []
1077
        request_data = request.GET.copy()
1078
        response_location = {}
1079
        response_location["lat"] = request_data['lat']
1080
        response_location["lng"] = request_data['lng']
1081
        lat = float(request_data['lat'])
1082
        lng = float(request_data['lng'])
1083
        R = 6371
1084
        distances = {}
1085
        closestMarker = {}
1086
        closest = -1
1087
        points = getPoints()
1088
        for (counter, i) in enumerate(points):
1089
            pointname = i['text']
1090
            pointlng = i['lng'] 
1091
            pointlat = i['lat']
1092
            pointtext = i['text']
1093
            dLat = rad(float(pointlat)-float(lat))
1094
            dLong = rad(float(pointlng)-float(lng))
1095
            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) 
1096
            c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
1097
            d = R * c
1098
            distances[counter] = d
1099
            if (closest == -1 or d < distances[closest]):
1100
                closest = counter
1101
                closestMarker = {"name": pointname, "lat": pointlat, "lng": pointlng, "text": pointtext}
1102
        return HttpResponse(json.dumps(closestMarker), mimetype='application/json')
1103

    
1104
@never_cache
1105
def worldPoints(request):
1106
    if request.method == 'GET':
1107
        points = getPoints()
1108
        return HttpResponse(json.dumps(points), mimetype='application/json')
1109

    
1110
@never_cache
1111
def world(request):
1112
        return render_to_response('front/world.html',
1113
                                  context_instance=RequestContext(request))
1114

    
1115
def getPoints():
1116
    points = cache.get('points')
1117
    if points:
1118
        points = bz2.decompress(points)
1119
        return json.loads(points)
1120
    else:
1121
        point_list = []
1122
        doc = ET.parse(settings.KML_FILE)
1123
        root = doc.getroot()
1124
        r = root.getchildren()[0]
1125
        for (counter, i) in enumerate(r.getchildren()):
1126
            if "id" in i.keys():
1127
                j = i.getchildren()
1128
                pointname = j[0].text
1129
                point = j[2].getchildren()[0].text
1130
                pointlng, pointlat, pointele = point.split(',')
1131
                Marker = {"name": pointname, "lat": pointlat, "lng": pointlng, "text": j[1].text}
1132
                point_list.append(Marker);
1133
        points = json.dumps(point_list)
1134
        cache.set('points', bz2.compress(points), 60 * 3600 * 24)
1135
        return json.loads(points)
1136

    
1137

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

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

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

    
1380
def to_xml(ele, encoding="UTF-8"):
1381
    "Convert and return the XML for an *ele* (:class:`~xml.etree.ElementTree.Element`) with specified *encoding*."
1382
    xml = ET.tostring(ele, encoding)
1383
    return xml if xml.startswith('<?xml') else '<?xml version="1.0" encoding="%s"?>%s' % (encoding, xml)
1384
    
1385
def getInstContacts(inst):
1386
    contacts = InstitutionContactPool.objects.filter(institution=inst)
1387
    contact_pks = []
1388
    for contact in contacts:
1389
        contact_pks.append(contact.contact.pk)
1390
    return list(set(contact_pks))
1391

    
1392
def getInstServers(inst):
1393
    servers = InstServer.objects.filter(instid=inst)
1394
    server_pks = []
1395
    for server in servers:
1396
        server_pks.append(server.pk)
1397
    return list(set(server_pks))
1398

    
1399

    
1400
def rad(x):
1401
    return x*math.pi/180
1402

    
1403
def send_new_mail(subject, message, from_email, recipient_list, bcc_list):
1404
    return EmailMessage(subject, message, from_email, recipient_list, bcc_list).send()
1405