Statistics
| Branch: | Tag: | Revision:

root / edumanage / views.py @ 10e9ee83

History | View | Annotate | Download (52 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
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 request.method == "GET":
99
        request_data = request.POST.copy()
100
        try:         
101
            inst_details = InstitutionDetails.objects.get(institution=inst)
102
            form = InstDetailsForm(instance=inst_details)
103
            UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFactInst, can_delete=True)
104
            urls_form = UrlFormSet(prefix='urlsform', instance = inst_details) 
105
        except InstitutionDetails.DoesNotExist:
106
            form = InstDetailsForm()
107
            form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=institution_pk), empty_label=None)
108
            UrlFormSet =  generic_inlineformset_factory(URL_i18n, extra=2, can_delete=True)
109
            urls_form = UrlFormSet(prefix='urlsform')
110
        
111
        form.fields['contact'] = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(pk__in=getInstContacts(inst)))
112
        return render_to_response('edumanage/institution_edit.html', { 'institution': inst, 'form': form, 'urls_form':urls_form},
113
                                  context_instance=RequestContext(request, base_response(request)))
114
    elif request.method == 'POST':
115
        request_data = request.POST.copy()
116
        UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFactInst, can_delete=True)
117
        try:         
118
            inst_details = InstitutionDetails.objects.get(institution=inst)
119
            form = InstDetailsForm(request_data, instance=inst_details)
120
            urls_form = UrlFormSet(request_data, instance=inst_details, prefix='urlsform')
121
        except InstitutionDetails.DoesNotExist:
122
            form = InstDetailsForm(request_data)
123
            urls_form = UrlFormSet(request_data, prefix='urlsform')
124
        UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFactInst, can_delete=True)
125
        if form.is_valid() and urls_form.is_valid():
126
            instdets = form.save()
127
            urls_form.instance = instdets
128
            urls_inst = urls_form.save()
129
            return HttpResponseRedirect(reverse("institutions"))
130
        else:
131
            form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=institution_pk), empty_label=None)
132
            form.fields['contact'] = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(pk__in=getInstContacts(inst)))
133
            return render_to_response('edumanage/institution_edit.html', { 'institution': inst, 'form': form, 'urls_form': urls_form},
134
                                  context_instance=RequestContext(request, base_response(request)))
135

    
136

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

    
177

    
178

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

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

    
257

    
258
@login_required
259
@never_cache
260
def del_service(request):
261
    if request.method == 'GET':
262
        user = request.user
263
        req_data = request.GET.copy()
264
        service_pk = req_data['service_pk']
265
        try:
266
            profile = user.get_profile()
267
            institution = profile.institution
268
        except UserProfile.DoesNotExist:
269
            resp['error'] = "Could not delete service. Not enough rights"
270
            return HttpResponse(json.dumps(resp), mimetype='application/json')
271
        resp = {}
272
        try:
273
            service = ServiceLoc.objects.get(institutionid=institution, pk=service_pk)
274
        except ServiceLoc.DoesNotExist:
275
            resp['error'] = "Could not get service or you have no rights to delete"
276
            return HttpResponse(json.dumps(resp), mimetype='application/json')
277
        try:
278
            service.delete()
279
        except:
280
            resp['error'] = "Could not delete service"
281
            return HttpResponse(json.dumps(resp), mimetype='application/json')
282
        resp['success'] = "Service successfully deleted"
283
        return HttpResponse(json.dumps(resp), mimetype='application/json')
284

    
285

    
286
@login_required
287
@never_cache
288
def servers(request, server_pk):
289
    user = request.user
290
    servers = False
291
    try:
292
        profile = user.get_profile()
293
        inst = profile.institution
294
    except UserProfile.DoesNotExist:
295
        inst = False
296
        return HttpResponseRedirect(reverse("manage"))
297
    if inst:
298
        servers = InstServer.objects.filter(instid=inst)
299
    if server_pk:
300
        servers = servers.get(pk=server_pk)
301
        return render_to_response('edumanage/server_details.html', 
302
                              {
303
                               'institution': inst,
304
                               'server': servers,
305
                               },  
306
                              context_instance=RequestContext(request, base_response(request)))
307
    return render_to_response('edumanage/servers.html', { 'servers': servers},
308
                                  context_instance=RequestContext(request, base_response(request)))
309

    
310

    
311
@login_required
312
@never_cache
313
def add_server(request, server_pk):
314
    user = request.user
315
    server = False
316
    edit = False
317
    try:
318
        profile = user.get_profile()
319
        inst = profile.institution
320
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
321
    except UserProfile.DoesNotExist:
322
        return HttpResponseRedirect(reverse("manage"))
323
    try:
324
        instdetails = inst.institutiondetails
325
    except InstitutionDetails.DoesNotExist:
326
        return HttpResponseRedirect(reverse("manage"))
327
    if request.method == "GET":
328
        # Determine add or edit
329
        try:         
330
            server = InstServer.objects.get(instid=inst, pk=server_pk)
331
            form = InstServerForm(instance=server)
332
        except InstServer.DoesNotExist:
333
            form = InstServerForm()
334
        form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
335
        if server:
336
            edit = True
337
        return render_to_response('edumanage/servers_edit.html', { 'form': form, 'edit': edit },
338
                                  context_instance=RequestContext(request, base_response(request)))
339
    elif request.method == 'POST':
340
        request_data = request.POST.copy()
341
        try:         
342
            server = InstServer.objects.get(instid=inst, pk=server_pk)
343
            form = InstServerForm(request_data, instance=server)
344
        except InstServer.DoesNotExist:
345
            form = InstServerForm(request_data)
346
        
347
        if form.is_valid():
348
            instserverf = form.save()
349
            return HttpResponseRedirect(reverse("servers"))
350
        else:
351
            form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
352
        if server:
353
            edit = True
354
        return render_to_response('edumanage/servers_edit.html', { 'institution': inst, 'form': form, 'edit': edit },
355
                                  context_instance=RequestContext(request, base_response(request)))
356

    
357

    
358
@login_required
359
@never_cache
360
def del_server(request):
361
    if request.method == 'GET':
362
        user = request.user
363
        req_data = request.GET.copy()
364
        server_pk = req_data['server_pk']
365
        try:
366
            profile = user.get_profile()
367
            institution = profile.institution
368
        except UserProfile.DoesNotExist:
369
            resp['error'] = "Could not delete server. Not enough rights"
370
            return HttpResponse(json.dumps(resp), mimetype='application/json')
371
        resp = {}
372
        try:
373
            server = InstServer.objects.get(instid=institution, pk=server_pk)
374
        except InstServer.DoesNotExist:
375
            resp['error'] = "Could not get server or you have no rights to delete"
376
            return HttpResponse(json.dumps(resp), mimetype='application/json')
377
        try:
378
            server.delete()
379
        except:
380
            resp['error'] = "Could not delete server"
381
            return HttpResponse(json.dumps(resp), mimetype='application/json')
382
        resp['success'] = "Server successfully deleted"
383
        return HttpResponse(json.dumps(resp), mimetype='application/json')
384

    
385

    
386
@login_required
387
@never_cache
388
def realms(request):
389
    user = request.user
390
    servers = False
391
    try:
392
        profile = user.get_profile()
393
        inst = profile.institution
394
    except UserProfile.DoesNotExist:
395
        return HttpResponseRedirect(reverse("manage"))
396
    if inst:
397
        realms = InstRealm.objects.filter(instid=inst)
398
    if inst.ertype not in [1,3]:
399
        messages.add_message(request, messages.ERROR, 'Cannot add/edit Realms. Your institution should be either IdP or IdP/SP')
400
    return render_to_response('edumanage/realms.html', { 'realms': realms },
401
                                  context_instance=RequestContext(request, base_response(request)))
402

    
403

    
404
@login_required
405
@never_cache
406
def add_realm(request, realm_pk):
407
    user = request.user
408
    server = False
409
    realm = False
410
    edit = False
411
    try:
412
        profile = user.get_profile()
413
        inst = profile.institution
414
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
415
    except UserProfile.DoesNotExist:
416
        return HttpResponseRedirect(reverse("manage"))
417
    try:
418
        instdetails = inst.institutiondetails
419
    except InstitutionDetails.DoesNotExist:
420
        return HttpResponseRedirect(reverse("manage"))
421
    if inst.ertype not in [1,3]:
422
        messages.add_message(request, messages.ERROR, 'Cannot add/edit Realm. Your institution should be either IdP or IdP/SP')
423
        return render_to_response('edumanage/realms_edit.html', { 'edit': edit },
424
                                  context_instance=RequestContext(request, base_response(request)))
425
    if request.method == "GET":
426

    
427
        # Determine add or edit
428
        try:         
429
            realm = InstRealm.objects.get(instid=inst, pk=realm_pk)
430
            form = InstRealmForm(instance=realm)
431
        except InstRealm.DoesNotExist:
432
            form = InstRealmForm()
433
        form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
434
        form.fields['proxyto'] = forms.ModelMultipleChoiceField(queryset=InstServer.objects.filter(pk__in=getInstServers(inst)))
435
        if realm:
436
            edit = True
437
        return render_to_response('edumanage/realms_edit.html', { 'form': form, 'edit': edit },
438
                                  context_instance=RequestContext(request, base_response(request)))
439
    elif request.method == 'POST':
440
        request_data = request.POST.copy()
441
        try:         
442
            realm = InstRealm.objects.get(instid=inst, pk=realm_pk)
443
            form = InstRealmForm(request_data, instance=realm)
444
        except InstRealm.DoesNotExist:
445
            form = InstRealmForm(request_data)
446
        
447
        if form.is_valid():
448
            instserverf = form.save()
449
            return HttpResponseRedirect(reverse("realms"))
450
        else:
451
            form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
452
            form.fields['proxyto'] = forms.ModelMultipleChoiceField(queryset=InstServer.objects.filter(pk__in=getInstServers(inst)))
453
        if realm:
454
            edit = True
455
        return render_to_response('edumanage/realms_edit.html', { 'institution': inst, 'form': form, 'edit': edit },
456
                                  context_instance=RequestContext(request, base_response(request)))
457

    
458

    
459
@login_required
460
@never_cache
461
def del_realm(request):
462
    if request.method == 'GET':
463
        user = request.user
464
        req_data = request.GET.copy()
465
        realm_pk = req_data['realm_pk']
466
        try:
467
            profile = user.get_profile()
468
            institution = profile.institution
469
        except UserProfile.DoesNotExist:
470
            resp['error'] = "Not enough rights"
471
            return HttpResponse(json.dumps(resp), mimetype='application/json')
472
        resp = {}
473
        try:
474
            realm = InstRealm.objects.get(instid=institution, pk=realm_pk)
475
        except InstRealm.DoesNotExist:
476
            resp['error'] = "Could not get realm or you have no rights to delete"
477
            return HttpResponse(json.dumps(resp), mimetype='application/json')
478
        try:
479
            realm.delete()
480
        except:
481
            resp['error'] = "Could not delete realm"
482
            return HttpResponse(json.dumps(resp), mimetype='application/json')
483
        resp['success'] = "Realm successfully deleted"
484
        return HttpResponse(json.dumps(resp), mimetype='application/json')
485

    
486

    
487
@login_required
488
@never_cache
489
def contacts(request):
490
    user = request.user
491
    servers = False
492
    instcontacts = []
493
    try:
494
        profile = user.get_profile()
495
        inst = profile.institution
496
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
497
    except UserProfile.DoesNotExist:
498
        return HttpResponseRedirect(reverse("manage"))
499
    try:
500
        instdetails = inst.institutiondetails
501
    except InstitutionDetails.DoesNotExist:
502
        return HttpResponseRedirect(reverse("manage"))
503
    if inst:
504
        instcontacts.extend([x.contact.pk for x in InstitutionContactPool.objects.filter(institution=inst)])
505
        contacts = Contact.objects.filter(pk__in=instcontacts)
506
    return render_to_response('edumanage/contacts.html', { 'contacts': contacts},
507
                                  context_instance=RequestContext(request, base_response(request)))
508

    
509

    
510
@login_required
511
@never_cache
512
def add_contact(request, contact_pk):
513
    user = request.user
514
    server = False
515
    edit = False
516
    contact = False
517
    try:
518
        profile = user.get_profile()
519
        inst = profile.institution
520
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
521
    except UserProfile.DoesNotExist:
522
        return HttpResponseRedirect(reverse("manage"))
523
    try:
524
        instdetails = inst.institutiondetails
525
    except InstitutionDetails.DoesNotExist:
526
        return HttpResponseRedirect(reverse("manage"))
527
    if request.method == "GET":
528

    
529
        # Determine add or edit
530
        try:         
531
            contactinst = InstitutionContactPool.objects.get(institution=inst, contact__pk=contact_pk)
532
            contact = contactinst.contact
533
            form = ContactForm(instance=contact)
534
        except InstitutionContactPool.DoesNotExist:
535
            form = ContactForm()
536
        if contact:
537
            edit = True
538
        return render_to_response('edumanage/contacts_edit.html', { 'form': form, "edit" : edit},
539
                                  context_instance=RequestContext(request, base_response(request)))
540
    elif request.method == 'POST':
541
        request_data = request.POST.copy()
542
        try:         
543
            contactinst = InstitutionContactPool.objects.get(institution=inst, contact__pk=contact_pk)
544
            contact = contactinst.contact
545
            form = ContactForm(request_data, instance=contact)
546
        except InstitutionContactPool.DoesNotExist:
547
            form = ContactForm(request_data)
548
        
549
        if form.is_valid():
550
            contact = form.save()
551
            instContPool, created = InstitutionContactPool.objects.get_or_create(contact=contact, institution=inst)
552
            instContPool.save()
553
            return HttpResponseRedirect(reverse("contacts"))
554
        if contact:
555
            edit = True
556
        return render_to_response('edumanage/contacts_edit.html', { 'form': form, "edit": edit},
557
                                  context_instance=RequestContext(request, base_response(request)))
558

    
559

    
560
@login_required
561
@never_cache
562
def del_contact(request):
563
    if request.method == 'GET':
564
        user = request.user
565
        req_data = request.GET.copy()
566
        contact_pk = req_data['contact_pk']
567
        try:
568
            profile = user.get_profile()
569
            institution = profile.institution
570
        except UserProfile.DoesNotExist:
571
            resp['error'] = "Could not delete contact. Not enough rights"
572
            return HttpResponse(json.dumps(resp), mimetype='application/json')
573
        resp = {}
574
        try:
575
            contactinst = InstitutionContactPool.objects.get(institution=institution, contact__pk=contact_pk)
576
            contact = contactinst.contact
577
        except InstitutionContactPool.DoesNotExist:
578
            resp['error'] = "Could not get contact or you have no rights to delete"
579
            return HttpResponse(json.dumps(resp), mimetype='application/json')
580
        try:
581
            for service in ServiceLoc.objects.filter(institutionid=institution):
582
                if (contact in service.contact.all() and len(service.contact.all()) == 1):
583
                    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")
584
                    return HttpResponse(json.dumps(resp), mimetype='application/json')
585
            if (contact in institution.institutiondetails.contact.all() and len(institution.institutiondetails.contact.all()) == 1):
586
                    resp['error'] = "Could not delete contact. It is the only contact your institution.<br>Fix it and try again"
587
                    return HttpResponse(json.dumps(resp), mimetype='application/json')
588
            contact.delete()
589
        except Exception:
590
            resp['error'] = "Could not delete contact"
591
            return HttpResponse(json.dumps(resp), mimetype='application/json')
592
        resp['success'] = "Contact successfully deleted"
593
        return HttpResponse(json.dumps(resp), mimetype='application/json')
594

    
595

    
596
@login_required
597
@never_cache
598
def adduser(request):
599
    user = request.user
600
    try:
601
        profile = user.get_profile()
602
        inst = profile.institution
603
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
604
    except UserProfile.DoesNotExist:
605
        return HttpResponseRedirect(reverse("manage"))
606

    
607
    if request.method == "GET":
608
        form = ContactForm()
609
        return render_to_response('edumanage/add_user.html', { 'form' : form },
610
                                  context_instance=RequestContext(request, base_response(request)))
611
    elif request.method == 'POST':
612
        request_data = request.POST.copy()
613
        form = ContactForm(request_data)
614
        if form.is_valid():
615
            contact = form.save()
616
            instContPool = InstitutionContactPool(contact=contact, institution=inst)
617
            instContPool.save()
618
            response_data = {}
619
            response_data['value'] = "%s" %contact.pk
620
            response_data['text'] = "%s" %contact
621
            return HttpResponse(json.dumps(response_data), mimetype='application/json')
622
        else:
623
            return render_to_response('edumanage/add_user.html', {'form': form,},
624
                                      context_instance=RequestContext(request, base_response(request)))
625

    
626

    
627
@login_required
628
def base_response(request):
629
    user = request.user
630
    inst = []
631
    server = []
632
    services = []
633
    instrealms = []
634
    instcontacts = []
635
    contacts = []
636
    institution = False
637
    institution_exists = False
638
    try:
639
        profile = user.get_profile()
640
        institution = profile.institution
641
        institution_exists = True
642
    except UserProfile.DoesNotExist:
643
        institution_exists = False
644
    try:
645
        inst.append(institution)
646
        server = InstServer.objects.filter(instid=institution)
647
        services = ServiceLoc.objects.filter(institutionid=institution)
648
        instrealms = InstRealm.objects.filter(instid=institution)
649
        instcontacts.extend([x.contact.pk for x in InstitutionContactPool.objects.filter(institution=institution)])
650
        contacts = Contact.objects.filter(pk__in=instcontacts)
651
    except:
652
        pass
653
    try:
654
        instututiondetails = institution.institutiondetails
655
    except:
656
        instututiondetails = False
657
    return { 
658
            'inst_num': len(inst),
659
            'servers_num': len(server),
660
            'services_num': len(services),
661
            'realms_num': len(instrealms),
662
            'contacts_num': len(contacts),
663
            'institution': institution,
664
            'institutiondetails': instututiondetails,
665
            'institution_exists': institution_exists,
666
            
667
        }
668

    
669

    
670
@login_required
671
@never_cache
672
def get_service_points(request):
673
    if request.method == "GET":
674
        user = request.user
675
        try:
676
            profile = user.get_profile()
677
            inst = profile.institution
678
        except UserProfile.DoesNotExist:
679
            inst = False
680
            return HttpResponseNotFound('<h1>Something went really wrong</h1>')
681
        servicelocs = ServiceLoc.objects.filter(institutionid=inst)
682
        
683
        locs = []
684
        for sl in servicelocs:
685
            response_location = {}
686
            response_location['lat'] = u"%s"%sl.latitude
687
            response_location['lng'] = u"%s"%sl.longitude
688
            response_location['address'] = u"%s<br>%s"%(sl.address_street, sl.address_city)
689
            response_location['enc'] = u"%s"%(','.join(sl.enc_level))
690
            response_location['AP_no'] = u"%s"%(sl.AP_no)
691
            response_location['name'] = sl.loc_name.get(lang='en').name
692
            response_location['port_restrict'] = u"%s"%(sl.port_restrict)
693
            response_location['transp_proxy'] = u"%s"%(sl.transp_proxy)
694
            response_location['IPv6'] = u"%s"%(sl.IPv6)
695
            response_location['NAT'] = u"%s"%(sl.NAT)
696
            response_location['wired'] = u"%s"%(sl.wired)
697
            response_location['SSID'] = u"%s"%(sl.SSID)
698
            response_location['key'] = u"%s"%sl.pk
699
            locs.append(response_location)
700
        return HttpResponse(json.dumps(locs), mimetype='application/json')
701
    else:
702
       return HttpResponseNotFound('<h1>Something went really wrong</h1>')
703

    
704
@never_cache
705
def get_all_services(request):
706
    lang = request.LANGUAGE_CODE
707
    servicelocs = ServiceLoc.objects.all()
708
    locs = []
709
    for sl in servicelocs:
710
        response_location = {}
711
        response_location['lat'] = u"%s"%sl.latitude
712
        response_location['lng'] = u"%s"%sl.longitude
713
        response_location['address'] = u"%s<br>%s"%(sl.address_street, sl.address_city)
714
        response_location['enc'] = u"%s"%(','.join(sl.enc_level))
715
        response_location['AP_no'] = u"%s"%(sl.AP_no)
716
        try:
717
            response_location['inst'] = sl.institutionid.org_name.get(lang=lang).name
718
        except Name_i18n.DoesNotExist:
719
            response_location['inst'] = sl.institutionid.org_name.get(lang='en').name
720
        try:
721
            response_location['name'] = sl.loc_name.get(lang=lang).name
722
        except Name_i18n.DoesNotExist:
723
            response_location['name'] = sl.loc_name.get(lang='en').name
724
        response_location['port_restrict'] = u"%s"%(sl.port_restrict)
725
        response_location['transp_proxy'] = u"%s"%(sl.transp_proxy)
726
        response_location['IPv6'] = u"%s"%(sl.IPv6)
727
        response_location['NAT'] = u"%s"%(sl.NAT)
728
        response_location['wired'] = u"%s"%(sl.wired)
729
        response_location['SSID'] = u"%s"%(sl.SSID)
730
        response_location['key'] = u"%s"%sl.pk
731
        locs.append(response_location)
732
    return HttpResponse(json.dumps(locs), mimetype='application/json')
733

    
734
@never_cache
735
def user_login(request):
736
    try:
737
        error_username = False
738
        error_orgname = False
739
        error_entitlement = False
740
        error_mail = False
741
        has_entitlement = False
742
        error = ''
743
        username = request.META['HTTP_EPPN']
744
        if not username:
745
            error_username = True
746
        firstname = request.META['HTTP_SHIB_INETORGPERSON_GIVENNAME']
747
        lastname = request.META['HTTP_SHIB_PERSON_SURNAME']
748
        mail = request.META['HTTP_SHIB_INETORGPERSON_MAIL']
749
        #organization = request.META['HTTP_SHIB_HOMEORGANIZATION']
750
        entitlement = request.META['HTTP_SHIB_EP_ENTITLEMENT']
751
        if settings.SHIB_AUTH_ENTITLEMENT in entitlement.split(";"):
752
            has_entitlement = True
753
        if not has_entitlement:
754
            error_entitlement = True
755
#        if not organization:
756
#            error_orgname = True
757
        if not mail:
758
            error_mail = True
759
        if error_username:
760
            error = _("Your idP should release the HTTP_EPPN attribute towards this service<br>")
761
        if error_orgname:
762
            error = error + _("Your idP should release the HTTP_SHIB_HOMEORGANIZATION attribute towards this service<br>")
763
        if error_entitlement:
764
            error = error + _("Your idP should release an appropriate HTTP_SHIB_EP_ENTITLEMENT attribute towards this service<br>")
765
        if error_mail:
766
            error = error + _("Your idP should release the HTTP_SHIB_INETORGPERSON_MAIL attribute towards this service")
767
        if error_username or error_orgname or error_entitlement or error_mail:
768
            return render_to_response('status.html', {'error': error, "missing_attributes": True},
769
                                  context_instance=RequestContext(request))
770
        try:
771
            user = User.objects.get(username__exact=username)
772
            user.email = mail
773
            user.first_name = firstname
774
            user.last_name = lastname
775
            user.save()
776
            user_exists = True
777
        except User.DoesNotExist:
778
            user_exists = False
779
        user = authenticate(username=username, firstname=firstname, lastname=lastname, mail=mail, authsource='shibboleth')
780
        if user is not None:
781
            try:
782
                profile = user.get_profile()
783
                inst = profile.institution
784
            except UserProfile.DoesNotExist:
785
                form = UserProfileForm()
786
                form.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(pk=user.pk), empty_label=None)
787
                form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.all(), empty_label=None)
788
                return render_to_response('registration/select_institution.html', {'form': form}, context_instance=RequestContext(request))
789
            if user.is_active:
790
               login(request, user)
791
               return HttpResponseRedirect(reverse("manage"))
792
            else:
793
                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
794
                return render_to_response('status.html', {'status': status, 'inactive': True},
795
                                  context_instance=RequestContext(request))
796
        else:
797
            error = _("Something went wrong during user authentication. Contact your administrator %s" %user)
798
            return render_to_response('status.html', {'error': error,},
799
                                  context_instance=RequestContext(request))
800
    except Exception:
801
        error = _("Invalid login procedure")
802
        return render_to_response('status.html', {'error': error,},
803
                                  context_instance=RequestContext(request))
804

    
805
@never_cache
806
def geolocate(request):
807
    return render_to_response('front/geolocate.html',
808
                                  context_instance=RequestContext(request))
809
@never_cache
810
def participants(request):
811
    institutions = Institution.objects.all()
812
    dets = []
813
    for i in institutions:
814
        try:
815
            dets.append(i.institutiondetails)
816
        except InstitutionDetails.DoesNotExist:
817
            pass
818
    return render_to_response('front/participants.html', {'institutions': dets},
819
                                  context_instance=RequestContext(request))
820
@never_cache
821
def selectinst(request):
822
    if request.method == 'POST':
823
        request_data = request.POST.copy()
824
        user = request_data['user']
825
        try:
826
            existingProfile = UserProfile.objects.get(user=user)
827
            error = _("Violation warning: User account is already associated with an institution.The event has been logged and our administrators will be notified about it")
828
            return render_to_response('status.html', {'error': error, 'inactive': True},
829
                                  context_instance=RequestContext(request))
830
        except UserProfile.DoesNotExist:
831
            pass
832
            
833
        form = UserProfileForm(request_data)
834
        if form.is_valid():
835
            userprofile = form.save()
836
            user_activation_notify(userprofile)
837
            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
838
            return render_to_response('status.html', {'status': error, 'inactive': True},
839
                                  context_instance=RequestContext(request))
840
        else:
841
            form.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(pk=user.pk), empty_label=None)
842
            form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.all(), empty_label=None)
843
            return render_to_response('registration/select_institution.html', {'form': form}, context_instance=RequestContext(request))
844

    
845

    
846
def user_activation_notify(userprofile):
847
    current_site = Site.objects.get_current()
848
    subject = render_to_string('registration/activation_email_subject.txt',
849
                                   { 'site': current_site })
850
    # Email subject *must not* contain newlines
851
    subject = ''.join(subject.splitlines())
852
    registration_profile = RegistrationProfile.objects.create_profile(userprofile.user)
853
    message = render_to_string('registration/activation_email.txt',
854
                                   { 'activation_key': registration_profile.activation_key,
855
                                     'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
856
                                     'site': current_site,
857
                                     'user': userprofile.user,
858
                                     'institution': userprofile.institution })
859
    send_new_mail(settings.EMAIL_SUBJECT_PREFIX + subject, 
860
                              message, settings.SERVER_EMAIL,
861
                             settings.NOTIFY_ADMIN_MAILS, [])
862
@never_cache
863
def closest(request):
864
    if request.method == 'GET':
865
        locs = []
866
        request_data = request.GET.copy()
867
        response_location = {}
868
        response_location["lat"] = request_data['lat']
869
        response_location["lng"] = request_data['lng']
870
        lat = float(request_data['lat'])
871
        lng = float(request_data['lng'])
872
        R = 6371
873
        distances = {}
874
        closestMarker = {}
875
        closest = -1
876
        points = getPoints()
877
        for (counter, i) in enumerate(points):
878
            pointname = i['text']
879
            pointlng = i['lng'] 
880
            pointlat = i['lat']
881
            pointtext = i['text']
882
            dLat = rad(float(pointlat)-float(lat))
883
            dLong = rad(float(pointlng)-float(lng))
884
            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) 
885
            c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
886
            d = R * c
887
            distances[counter] = d
888
            if (closest == -1 or d < distances[closest]):
889
                closest = counter
890
                closestMarker = {"name": pointname, "lat": pointlat, "lng": pointlng, "text": pointtext}
891
        return HttpResponse(json.dumps(closestMarker), mimetype='application/json')
892

    
893
@never_cache
894
def worldPoints(request):
895
    if request.method == 'GET':
896
        points = getPoints()
897
        return HttpResponse(json.dumps(points), mimetype='application/json')
898

    
899
@never_cache
900
def world(request):
901
        return render_to_response('front/world.html',
902
                                  context_instance=RequestContext(request))
903

    
904
def getPoints():
905
    points = cache.get('points')
906
    if points:
907
        points = bz2.decompress(points)
908
        return json.loads(points)
909
    else:
910
        point_list = []
911
        doc = ET.parse(settings.KML_FILE)
912
        root = doc.getroot()
913
        r = root.getchildren()[0]
914
        for (counter, i) in enumerate(r.getchildren()):
915
            if "id" in i.keys():
916
                j = i.getchildren()
917
                pointname = j[0].text
918
                point = j[2].getchildren()[0].text
919
                pointlng, pointlat, pointele = point.split(',')
920
                Marker = {"name": pointname, "lat": pointlat, "lng": pointlng, "text": j[1].text}
921
                point_list.append(Marker);
922
        points = json.dumps(point_list)
923
        cache.set('points', bz2.compress(points), 60 * 3600 * 24)
924
        return json.loads(points)
925

    
926

    
927
@never_cache
928
def instxml(request):
929
    ET._namespace_map["http://www.w3.org/2001/XMLSchema-instance"] = 'xsi'
930
    root = ET.Element("institutions")
931
    NS_XSI = "{http://www.w3.org/2001/XMLSchema-instance}"
932
    root.set(NS_XSI + "noNamespaceSchemaLocation", "institution.xsd")
933
    #root.attrib["xsi:noNamespaceSchemaLocation"] = "institution.xsd"
934
    institutions = Institution.objects.all()
935
    for institution in institutions:
936
        try:
937
            inst = institution.institutiondetails
938
            if not inst:
939
                pass
940
        except InstitutionDetails.DoesNotExist:
941
            pass
942
        
943
        instElement = ET.SubElement(root, "institution")
944
        
945
        instCountry = ET.SubElement(instElement, "country")
946
        instCountry.text = ("%s" %inst.institution.realmid.country).upper()
947
        
948
        instType = ET.SubElement(instElement, "type")
949
        instType.text = "%s" %inst.institution.ertype
950
        
951
        for realm in institution.instrealm_set.all():
952
            instRealm = ET.SubElement(instElement, "inst_realm")
953
            instRealm.text = realm.realm
954
        
955
        for name in inst.institution.org_name.all():
956
            instOrgName = ET.SubElement(instElement, "org_name")
957
            instOrgName.attrib["lang"] = name.lang
958
            instOrgName.text = u"%s" %name.name
959
        
960
        instAddress = ET.SubElement(instElement, "address")
961
        
962
        instAddrStreet = ET.SubElement(instAddress, "street")
963
        instAddrStreet.text = inst.address_street
964
        
965
        instAddrCity = ET.SubElement(instAddress, "city")
966
        instAddrCity.text = inst.address_city
967
        
968
        for contact in inst.contact.all():
969
            instContact = ET.SubElement(instElement, "contact")
970
            
971
            instContactName = ET.SubElement(instContact, "name")
972
            instContactName.text = "%s" %(contact.name)
973
            
974
            instContactEmail = ET.SubElement(instContact, "email")
975
            instContactEmail.text = contact.email
976
            
977
            instContactPhone = ET.SubElement(instContact, "phone")
978
            instContactPhone.text = contact.phone
979
        
980
        for url in inst.url.all():
981
            instUrl = ET.SubElement(instElement, "%s_URL"%(url.urltype))
982
            instUrl.attrib["lang"] = url.lang
983
            instUrl.text = url.url
984
        
985
        instTs = ET.SubElement(instElement, "ts")
986
        instTs.text = "%s" %inst.ts.isoformat()
987
        #Let's go to Institution Service Locations
988

    
989
        for serviceloc in inst.institution.serviceloc_set.all():
990
            instLocation = ET.SubElement(instElement, "location")
991
            
992
            instLong = ET.SubElement(instLocation, "longitude")
993
            instLong.text = "%s" %serviceloc.longitude
994
            
995
            instLat = ET.SubElement(instLocation, "latitude")
996
            instLat.text = "%s" %serviceloc.latitude
997
            
998
            for instlocname in serviceloc.loc_name.all():
999
                instLocName = ET.SubElement(instLocation, "loc_name")
1000
                instLocName.attrib["lang"] = instlocname.lang
1001
                instLocName.text = instlocname.name
1002
            
1003
            instLocAddress = ET.SubElement(instLocation, "address")
1004
        
1005
            instLocAddrStreet = ET.SubElement(instLocAddress, "street")
1006
            instLocAddrStreet.text = serviceloc.address_street
1007
        
1008
            instLocAddrCity = ET.SubElement(instLocAddress, "city")
1009
            instLocAddrCity.text = serviceloc.address_city
1010
            
1011
            for contact in serviceloc.contact.all():
1012
                instLocContact = ET.SubElement(instLocation, "contact")
1013
                
1014
                instLocContactName = ET.SubElement(instLocContact, "name")
1015
                instLocContactName.text = "%s" %(contact.name)
1016
                
1017
                instLocContactEmail = ET.SubElement(instLocContact, "email")
1018
                instLocContactEmail.text = contact.email
1019
                
1020
                instLocContactPhone = ET.SubElement(instLocContact, "phone")
1021
                instLocContactPhone.text = contact.phone
1022
            
1023
            instLocSSID = ET.SubElement(instLocation, "SSID")
1024
            instLocSSID.text = serviceloc.SSID
1025
            
1026
            instLocEncLevel = ET.SubElement(instLocation, "enc_level")
1027
            instLocEncLevel.text = ', '.join(serviceloc.enc_level)
1028
            
1029
            instLocPortRestrict = ET.SubElement(instLocation, "port_restrict")
1030
            instLocPortRestrict.text = ("%s" %serviceloc.port_restrict).lower()
1031
            
1032
            instLocTransProxy = ET.SubElement(instLocation, "transp_proxy")
1033
            instLocTransProxy.text = ("%s" %serviceloc.transp_proxy).lower()
1034
            
1035
            instLocIpv6 = ET.SubElement(instLocation, "IPv6")
1036
            instLocIpv6.text = ("%s" %serviceloc.IPv6).lower()
1037
            
1038
            instLocNAT = ET.SubElement(instLocation, "NAT")
1039
            instLocNAT.text = ("%s" %serviceloc.NAT).lower()
1040
            
1041
            instLocAP_no = ET.SubElement(instLocation, "AP_no")
1042
            instLocAP_no.text = "%s" %int(serviceloc.AP_no)
1043
            
1044
            instLocWired = ET.SubElement(instLocation, "wired")
1045
            instLocWired.text = ("%s" %serviceloc.wired).lower()
1046
            
1047
            for url in serviceloc.url.all():
1048
                instLocUrl = ET.SubElement(instLocation, "%s_URL"%(url.urltype))
1049
                instLocUrl.attrib["lang"] = url.lang
1050
                instLocUrl.text = url.url
1051
            
1052
    return render_to_response("general/institution.xml", {"xml":to_xml(root)},context_instance=RequestContext(request,), mimetype="application/xml")
1053
        
1054
@never_cache
1055
def realmxml(request):
1056
    realm = Realm.objects.all()[0]
1057
    ET._namespace_map["http://www.w3.org/2001/XMLSchema-instance"] = 'xsi'
1058
    root = ET.Element("realms")
1059
    NS_XSI = "{http://www.w3.org/2001/XMLSchema-instance}"
1060
    root.set(NS_XSI + "noNamespaceSchemaLocation", "realm.xsd")
1061
    #root.attrib["xsi:noNamespaceSchemaLocation"] = "institution.xsd"
1062
    realmElement = ET.SubElement(root, "realm")
1063
    
1064
    realmCountry = ET.SubElement(realmElement, "country")
1065
    realmCountry.text = realm.country.upper()
1066
        
1067
    realmStype = ET.SubElement(realmElement, "stype")
1068
    realmStype.text = "%s" %realm.stype
1069
    
1070
    for name in realm.org_name.all():
1071
        realmOrgName = ET.SubElement(realmElement, "org_name")
1072
        realmOrgName.attrib["lang"] = name.lang
1073
        realmOrgName.text = u"%s" %name.name
1074
    
1075
    realmAddress = ET.SubElement(realmElement, "address")
1076
        
1077
    realmAddrStreet = ET.SubElement(realmAddress, "street")
1078
    realmAddrStreet.text = realm.address_street
1079
    
1080
    realmAddrCity = ET.SubElement(realmAddress, "city")
1081
    realmAddrCity.text = realm.address_city
1082
    
1083
    for contact in realm.contact.all():
1084
        realmContact = ET.SubElement(realmElement, "contact")
1085
        
1086
        realmContactName = ET.SubElement(realmContact, "name")
1087
        realmContactName.text = "%s" %(contact.name)
1088
        
1089
        realmContactEmail = ET.SubElement(realmContact, "email")
1090
        realmContactEmail.text = contact.email
1091
        
1092
        realmContactPhone = ET.SubElement(realmContact, "phone")
1093
        realmContactPhone.text = contact.phone
1094
    
1095
    for url in realm.url.all():
1096
        realmUrl = ET.SubElement(realmElement, "%s_URL"%(url.urltype))
1097
        realmUrl.attrib["lang"] = url.lang
1098
        realmUrl.text = url.url
1099
    
1100
    instTs = ET.SubElement(realmElement, "ts")
1101
    instTs.text = "%s" %realm.ts.isoformat()
1102
    
1103
    return render_to_response("general/realm.xml", {"xml":to_xml(root)},context_instance=RequestContext(request,), mimetype="application/xml")
1104

    
1105
@never_cache
1106
def realmdataxml(request):
1107
    realm = Realm.objects.all()[0]
1108
    ET._namespace_map["http://www.w3.org/2001/XMLSchema-instance"] = 'xsi'
1109
    root = ET.Element("realm_data_root")
1110
    NS_XSI = "{http://www.w3.org/2001/XMLSchema-instance}"
1111
    root.set(NS_XSI + "noNamespaceSchemaLocation", "realm-data.xsd")
1112
    
1113
    realmdataElement = ET.SubElement(root, "realm_data")
1114
    
1115
    realmCountry = ET.SubElement(realmdataElement, "country")
1116
    realmCountry.text = realm.country.upper()
1117
    
1118
    nIdpCountry = ET.SubElement(realmdataElement, "number_Idp")
1119
    nIdpCountry.text = "%s" %len(realm.institution_set.filter(ertype=1))
1120
    
1121
    nSPCountry = ET.SubElement(realmdataElement, "number_SP")
1122
    nSPCountry.text = "%s" %len(realm.institution_set.filter(ertype=2))
1123
    
1124
    nSPIdpCountry = ET.SubElement(realmdataElement, "number_SPIdP")
1125
    nSPIdpCountry.text = "%s" %len(realm.institution_set.filter(ertype=3))
1126
    
1127
    ninstCountry = ET.SubElement(realmdataElement, "number_inst")
1128
    ninstCountry.text = "%s" %len(realm.institution_set.all())
1129
    
1130
    nuserCountry = ET.SubElement(realmdataElement, "number_user")
1131
    insts = realm.institution_set.all()
1132
    users = 0
1133
    for inst in insts:
1134
        try:
1135
            users = users + inst.institutiondetails.number_user
1136
        except InstitutionDetails.DoesNotExist:
1137
            pass
1138
    nuserCountry.text = "%s" %users
1139
    
1140
    nIdCountry = ET.SubElement(realmdataElement, "number_id")
1141
    insts = realm.institution_set.all()
1142
    ids = 0
1143
    for inst in insts:
1144
        try:
1145
            ids = ids + inst.institutiondetails.number_id
1146
        except InstitutionDetails.DoesNotExist:
1147
            pass
1148
    nIdCountry.text = "%s" %ids
1149
    
1150
    # Get the latest ts from all tables...
1151
    datetimes = []
1152
    datetimes.append(InstitutionDetails.objects.aggregate(Max('ts'))['ts__max'])
1153
    datetimes.append(Realm.objects.aggregate(Max('ts'))['ts__max'])
1154
    datetimes.append(InstServer.objects.aggregate(Max('ts'))['ts__max'])
1155
    datetimes.append(ServiceLoc.objects.aggregate(Max('ts'))['ts__max'])
1156
    
1157
    instTs = ET.SubElement(realmdataElement, "ts")
1158
    instTs.text = "%s" %max(datetimes).isoformat()
1159
    
1160
    
1161
    return render_to_response("general/realm_data.xml", {"xml":to_xml(root)},context_instance=RequestContext(request,), mimetype="application/xml")
1162

    
1163
def to_xml(ele, encoding="UTF-8"):
1164
    "Convert and return the XML for an *ele* (:class:`~xml.etree.ElementTree.Element`) with specified *encoding*."
1165
    xml = ET.tostring(ele, encoding)
1166
    return xml if xml.startswith('<?xml') else '<?xml version="1.0" encoding="%s"?>%s' % (encoding, xml)
1167
    
1168
def getInstContacts(inst):
1169
    contacts = InstitutionContactPool.objects.filter(institution=inst)
1170
    contact_pks = []
1171
    for contact in contacts:
1172
        contact_pks.append(contact.contact.pk)
1173
    return list(set(contact_pks))
1174

    
1175
def getInstServers(inst):
1176
    servers = InstServer.objects.filter(instid=inst)
1177
    server_pks = []
1178
    for server in servers:
1179
        server_pks.append(server.pk)
1180
    return list(set(server_pks))
1181

    
1182

    
1183
def rad(x):
1184
    return x*math.pi/180
1185

    
1186
def send_new_mail(subject, message, from_email, recipient_list, bcc_list):
1187
    return EmailMessage(subject, message, from_email, recipient_list, bcc_list).send()
1188