views.py 35.2 KB
Newer Older
1 2 3 4 5 6
# -*- coding: utf-8 -*- vim:encoding=utf-8:
# vim: tabstop=4:shiftwidth=4:softtabstop=4:expandtab

from django.shortcuts import render_to_response,get_object_or_404
from django.http import HttpResponse,HttpResponseRedirect,Http404
from django.template import RequestContext
7
from django.core.urlresolvers import reverse
8 9
from django.contrib.auth.decorators import login_required
from edumanage.models import *
10 11
from edumanage.forms import *
from django import forms
12 13 14 15
from django.forms.models import modelformset_factory
from django.forms.models import inlineformset_factory
from django.contrib.contenttypes.generic import generic_inlineformset_factory
import json 
16
import math
17
from xml.etree import ElementTree as ET
18 19

from django.conf import settings
20 21

def index(request):
22
    return render_to_response('front/index.html', context_instance=RequestContext(request, base_response(request)))
23 24 25 26 27

@login_required
def manage(request):
    services_list = []
    servers_list = []
28 29 30 31 32 33 34 35 36 37
    user = request.user
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
        inst = False
    services = ServiceLoc.objects.filter(institutionid=inst)
    services_list.extend([s for s in services])
    servers = InstServer.objects.filter(instid=inst)
    servers_list.extend([s for s in servers])
38 39
    return render_to_response('edumanage/welcome.html', 
                              {
40
                               'institution': inst, 
41 42 43
                               'services': services_list,
                               'servers': servers_list
                               },  
44
                              context_instance=RequestContext(request, base_response(request)))
45 46 47 48

@login_required
def institutions(request):
    user = request.user
49 50 51 52 53 54 55 56 57 58 59 60
    dict = {}
    
    try:
        profile = user.get_profile()
        inst = profile.institution
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
    except UserProfile.DoesNotExist:
        inst = False
    dict['institution'] = inst.pk
    form = InstDetailsForm(initial=dict)
    form.fields['institution'].widget.attrs['readonly'] = True
    return render_to_response('edumanage/institution.html', 
61
                              {
62 63
                               'institution': inst,
                               'form': form, 
64
                               },  
65
                              context_instance=RequestContext(request, base_response(request)))
66 67 68 69 70 71



@login_required
def add_institution_details(request, institution_pk):
    user = request.user
72 73 74 75 76 77 78 79 80 81
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
        inst = False
        
    if (not inst) or (int(inst.pk) != int(institution_pk)):
    #            messages.add_message(request, messages.WARNING,
    #                             _("Insufficient rights on Institution. Contact your administrator"))
        return HttpResponseRedirect(reverse("institutions"))
82 83
    if request.method == "GET":

84 85 86 87 88
        # Determine add or edit
        request_data = request.POST.copy()
        try:         
            inst_details = InstitutionDetails.objects.get(institution=inst)
            form = InstDetailsForm(instance=inst_details)
89
            UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFactInst, can_delete=True)
90 91 92
        except InstitutionDetails.DoesNotExist:
            form = InstDetailsForm()
            form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=institution_pk), empty_label=None)
93 94
            UrlFormSet =  generic_inlineformset_factory(URL_i18n, extra=2, can_delete=True)
        urls_form = UrlFormSet(prefix='urlsform') 
95
        form.fields['contact'] = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(pk__in=getInstContacts(inst)))
96
        return render_to_response('edumanage/institution_edit.html', { 'institution': inst, 'form': form, 'urls_form':urls_form},
97
                                  context_instance=RequestContext(request, base_response(request)))
98 99
    elif request.method == 'POST':
        request_data = request.POST.copy()
100
        UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFactInst, can_delete=True)
101 102 103
        try:         
            inst_details = InstitutionDetails.objects.get(institution=inst)
            form = InstDetailsForm(request_data, instance=inst_details)
104
            urls_form = UrlFormSet(request_data, instance=inst_details, prefix='urlsform')
105 106
        except InstitutionDetails.DoesNotExist:
            form = InstDetailsForm(request_data)
107 108 109
            urls_form = UrlFormSet(request_data, prefix='urlsform')
        UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFactInst, can_delete=True)
        if form.is_valid() and urls_form.is_valid():
110
            instdets = form.save()
111 112
            urls_form.instance = instdets
            urls_inst = urls_form.save()
113
            return HttpResponseRedirect(reverse("institutions"))
114 115 116 117 118 119
        else:
            try:
                profile = user.get_profile()
                inst = profile.institution
            except UserProfile.DoesNotExist:
                inst = False
120 121 122
            form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=institution_pk), empty_label=None)
            form.fields['contact'] = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(pk__in=getInstContacts(inst)))
            return render_to_response('edumanage/institution_edit.html', { 'institution': inst, 'form': form, 'urls_form': urls_form},
123
                                  context_instance=RequestContext(request, base_response(request)))
124

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146

@login_required
def services(request):
    user = request.user
    dict = {}
    
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
        inst = False
    try:
        services = ServiceLoc.objects.filter(institutionid = inst)
    except ServiceLoc.DoesNotExist:
        services = False 
        
    
    return render_to_response('edumanage/services.html', 
                              {
                               'institution': inst,
                               'services': services, 
                               },  
147
                              context_instance=RequestContext(request, base_response(request)))
148 149 150 151 152 153



@login_required
def add_services(request, service_pk):
    user = request.user
154
    service = False
155 156 157 158 159
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
        inst = False
160

161 162 163 164 165 166 167 168
    if request.method == "GET":

        # Determine add or edit
        try:         
            service = ServiceLoc.objects.get(institutionid=inst, pk=service_pk)
            form = ServiceLocForm(instance=service)
        except ServiceLoc.DoesNotExist:
            form = ServiceLocForm()
169
        form.fields['institutionid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
170 171 172 173
        UrlFormSet =  generic_inlineformset_factory(URL_i18n, extra=2, can_delete=True)
        NameFormSet = generic_inlineformset_factory(Name_i18n, extra=2, can_delete=True)
        urls_form = UrlFormSet(prefix='urlsform') 
        names_form = NameFormSet(prefix='namesform')
174
        if (service):
175 176 177 178
            NameFormSet = generic_inlineformset_factory(Name_i18n, extra=1, formset=NameFormSetFact, can_delete=True)
            names_form = NameFormSet(instance=service, prefix='namesform')
            UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFact, can_delete=True)
            urls_form = UrlFormSet(instance=service, prefix='urlsform')
179
        form.fields['contact'] = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(pk__in=getInstContacts(inst)))
180 181
        return render_to_response('edumanage/services_edit.html', { 'form': form, 'services_form':names_form, 'urls_form': urls_form},
                                  context_instance=RequestContext(request, base_response(request)))
182 183
    elif request.method == 'POST':
        request_data = request.POST.copy()
184 185
        NameFormSet = generic_inlineformset_factory(Name_i18n, extra=1, formset=NameFormSetFact, can_delete=True)
        UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFact, can_delete=True)
186 187 188
        try:         
            service = ServiceLoc.objects.get(institutionid=inst, pk=service_pk)
            form = ServiceLocForm(request_data, instance=service)
189 190
            names_form = NameFormSet(request_data, instance=service, prefix='namesform')
            urls_form = UrlFormSet(request_data, instance=service, prefix='urlsform')
191 192
        except ServiceLoc.DoesNotExist:
            form = ServiceLocForm(request_data)
193 194
            names_form = NameFormSet(request_data, prefix='namesform')
            urls_form = UrlFormSet(request_data, prefix='urlsform')
195
        
196
        if form.is_valid() and names_form.is_valid() and urls_form.is_valid():
197
            serviceloc = form.save()
198 199 200 201 202 203 204 205 206 207 208
            service = serviceloc
            names_form.instance = service
            urls_form.instance = service
            names_inst = names_form.save()
            urls_inst = urls_form.save()
#            for nform in names_inst:
#                nform.content_object = serviceloc
#                nform.save()
#            for uform in urls_inst:
#                uform.content_object = serviceloc
#                uform.save()
209 210
            return HttpResponseRedirect(reverse("services"))
        else:
211
            form.fields['institutionid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
212
            form.fields['contact'] = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(pk__in=getInstContacts(inst)))
213 214 215
        return render_to_response('edumanage/services_edit.html', { 'institution': inst, 'form': form, 'services_form':names_form, 'urls_form': urls_form},
                                  context_instance=RequestContext(request, base_response(request)))

216

217 218 219 220 221 222 223 224 225 226 227

@login_required
def get_service_points(request):
    if request.method == "GET":
        user = request.user
        try:
            profile = user.get_profile()
            inst = profile.institution
        except UserProfile.DoesNotExist:
            inst = False
        servicelocs = ServiceLoc.objects.filter(institutionid=inst)
228
        
229 230 231 232 233
        locs = []
        for sl in servicelocs:
            response_location = {}
            response_location['lat'] = u"%s"%sl.latitude
            response_location['lng'] = u"%s"%sl.longitude
Leonidas Poulopoulos's avatar
Leonidas Poulopoulos committed
234 235 236
            response_location['address'] = u"%s<br>%s"%(sl.address_street, sl.address_city)
            response_location['enc'] = u"%s"%(sl.enc_level)
            response_location['AP_no'] = u"%s"%(sl.AP_no)
237
            response_location['name'] = sl.loc_name.get(lang='en').name
Leonidas Poulopoulos's avatar
Leonidas Poulopoulos committed
238 239 240 241 242 243
            response_location['port_restrict'] = u"%s"%(sl.port_restrict)
            response_location['transp_proxy'] = u"%s"%(sl.transp_proxy)
            response_location['IPv6'] = u"%s"%(sl.IPv6)
            response_location['NAT'] = u"%s"%(sl.NAT)
            response_location['wired'] = u"%s"%(sl.wired)
            response_location['SSID'] = u"%s"%(sl.SSID)
244 245 246 247 248
            response_location['key'] = u"%s"%sl.pk
            locs.append(response_location)
        return HttpResponse(json.dumps(locs), mimetype='application/json')
    else:
       return HttpResponseNotFound('<h1>Something went really wrong</h1>')
249 250


251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
def get_all_services(request):
    servicelocs = ServiceLoc.objects.all()
    locs = []
    for sl in servicelocs:
        response_location = {}
        response_location['lat'] = u"%s"%sl.latitude
        response_location['lng'] = u"%s"%sl.longitude
        response_location['address'] = u"%s<br>%s"%(sl.address_street, sl.address_city)
        response_location['enc'] = u"%s"%(sl.enc_level)
        response_location['AP_no'] = u"%s"%(sl.AP_no)
        response_location['inst'] = sl.institutionid.org_name.get(lang='en').name
        response_location['name'] = sl.loc_name.get(lang='en').name
        response_location['port_restrict'] = u"%s"%(sl.port_restrict)
        response_location['transp_proxy'] = u"%s"%(sl.transp_proxy)
        response_location['IPv6'] = u"%s"%(sl.IPv6)
        response_location['NAT'] = u"%s"%(sl.NAT)
        response_location['wired'] = u"%s"%(sl.wired)
        response_location['SSID'] = u"%s"%(sl.SSID)
        response_location['key'] = u"%s"%sl.pk
        locs.append(response_location)
    return HttpResponse(json.dumps(locs), mimetype='application/json')



275
def servers(request):
276 277 278 279 280 281 282 283 284
    user = request.user
    servers = False
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
        inst = False
    if inst:
        servers = InstServer.objects.filter(instid=inst)
285
    return render_to_response('edumanage/servers.html', { 'servers': servers},
286 287
                                  context_instance=RequestContext(request, base_response(request)))

288 289


290 291
@login_required
def adduser(request):
292 293 294 295 296 297
    user = request.user
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
        inst = False
298 299
    if request.method == "GET":
        form = ContactForm()
300
        return render_to_response('edumanage/add_user.html', { 'form' : form },
301 302 303 304 305 306
                                  context_instance=RequestContext(request, base_response(request)))
    elif request.method == 'POST':
        request_data = request.POST.copy()
        form = ContactForm(request_data)
        if form.is_valid():
            contact = form.save()
307 308
            instContPool = InstitutionContactPool(contact=contact, institution=inst)
            instContPool.save()
309 310 311 312 313 314 315 316
            response_data = {}
            response_data['value'] = "%s" %contact.pk
            response_data['text'] = "%s" %contact
            return HttpResponse(json.dumps(response_data), mimetype='application/json')
        else:
            return render_to_response('edumanage/add_user.html', {'form': form,},
                                      context_instance=RequestContext(request, base_response(request)))

317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
@login_required
def add_server(request, server_pk):
    user = request.user
    server = False
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
        inst = False

    if request.method == "GET":

        # Determine add or edit
        try:         
            server = InstServer.objects.get(instid=inst, pk=server_pk)
            form = InstServerForm(instance=server)
        except InstServer.DoesNotExist:
            form = InstServerForm()
        form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
        
        return render_to_response('edumanage/servers_edit.html', { 'form': form},
338
                                  context_instance=RequestContext(request, base_response(request)))
339 340 341 342 343 344 345 346 347 348 349 350 351 352
    elif request.method == 'POST':
        request_data = request.POST.copy()
        try:         
            server = InstServer.objects.get(instid=inst, pk=server_pk)
            form = InstServerForm(request_data, instance=server)
        except InstServer.DoesNotExist:
            form = InstServerForm(request_data)
        
        if form.is_valid():
            instserverf = form.save()
            return HttpResponseRedirect(reverse("servers"))
        else:
            form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
        return render_to_response('edumanage/servers_edit.html', { 'institution': inst, 'form': form},
353 354
                                  context_instance=RequestContext(request, base_response(request)))

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
@login_required
def realms(request):
    user = request.user
    servers = False
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
        inst = False
    if inst:
        realms = InstRealm.objects.filter(instid=inst)
    return render_to_response('edumanage/realms.html', { 'realms': realms},
                                  context_instance=RequestContext(request, base_response(request)))

@login_required
def add_realm(request, realm_pk):
    user = request.user
    server = False
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
        inst = False

    if request.method == "GET":

        # Determine add or edit
        try:         
            realm = InstRealm.objects.get(instid=inst, pk=realm_pk)
            form = InstRealmForm(instance=realm)
        except InstRealm.DoesNotExist:
            form = InstRealmForm()
        form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
        form.fields['proxyto'] = forms.ModelMultipleChoiceField(queryset=InstServer.objects.filter(pk__in=getInstServers(inst)))
        return render_to_response('edumanage/realms_edit.html', { 'form': form},
                                  context_instance=RequestContext(request, base_response(request)))
    elif request.method == 'POST':
        request_data = request.POST.copy()
        try:         
            realm = InstRealm.objects.get(instid=inst, pk=realm_pk)
            form = InstRealmForm(request_data, instance=realm)
        except InstRealm.DoesNotExist:
            form = InstRealmForm(request_data)
        
        if form.is_valid():
            instserverf = form.save()
            return HttpResponseRedirect(reverse("realms"))
        else:
            form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
            form.fields['proxyto'] = forms.ModelMultipleChoiceField(queryset=InstServer.objects.filter(pk__in=getInstServers(inst)))
        return render_to_response('edumanage/realms_edit.html', { 'institution': inst, 'form': form},
                                  context_instance=RequestContext(request, base_response(request)))


@login_required
def del_realm(request):
    if request.method == 'GET':
        user = request.user
        req_data = request.GET.copy()
        realm_pk = req_data['realm_pk']
        profile = user.get_profile()
        institution = profile.institution
        resp = {}
        try:
            realm = InstRealm.objects.get(instid=institution, pk=realm_pk)
        except InstRealm.DoesNotExist:
            resp['error'] = "Could not get realm or you have no rights to delete"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        try:
            realm.delete()
        except:
            resp['error'] = "Could not delete realm"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        resp['success'] = "Realm successfully deleted"
        return HttpResponse(json.dumps(resp), mimetype='application/json')


432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522

@login_required
def contacts(request):
    user = request.user
    servers = False
    instcontacts = []
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
        inst = False
    if inst:
        instcontacts.extend([x.contact.pk for x in InstitutionContactPool.objects.filter(institution=inst)])
        print instcontacts
        contacts = Contact.objects.filter(pk__in=instcontacts)
        print contacts
    return render_to_response('edumanage/contacts.html', { 'contacts': contacts},
                                  context_instance=RequestContext(request, base_response(request)))

@login_required
def add_contact(request, contact_pk):
    user = request.user
    server = False
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
        inst = False

    if request.method == "GET":

        # Determine add or edit
        try:         
            contactinst = InstitutionContactPool.objects.get(institution=inst, contact__pk=contact_pk)
            contact = contactinst.contact
            form = ContactForm(instance=contact)
        except InstitutionContactPool.DoesNotExist:
            form = ContactForm()

        return render_to_response('edumanage/contacts_edit.html', { 'form': form},
                                  context_instance=RequestContext(request, base_response(request)))
    elif request.method == 'POST':
        request_data = request.POST.copy()
        try:         
            contactinst = InstitutionContactPool.objects.get(institution=inst, contact__pk=contact_pk)
            contact = contactinst.contact
            form = ContactForm(request_data, instance=contact)
        except InstitutionContactPool.DoesNotExist:
            form = ContactForm(request_data)
        
        if form.is_valid():
            contact = form.save()
            instContPool, created = InstitutionContactPool.objects.get_or_create(contact=contact, institution=inst)
            instContPool.save()
            return HttpResponseRedirect(reverse("contacts"))
        return render_to_response('edumanage/contacts_edit.html', { 'form': form},
                                  context_instance=RequestContext(request, base_response(request)))


@login_required
def del_contact(request):
    if request.method == 'GET':
        user = request.user
        req_data = request.GET.copy()
        contact_pk = req_data['contact_pk']
        profile = user.get_profile()
        institution = profile.institution
        resp = {}
        try:
            contactinst = InstitutionContactPool.objects.get(institution=institution, contact__pk=contact_pk)
            contact = contactinst.contact
        except InstitutionContactPool.DoesNotExist:
            resp['error'] = "Could not get contact or you have no rights to delete"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        try:
            for service in ServiceLoc.objects.filter(institutionid=institution):
                if (contact in service.contact.all() and len(service.contact.all()) == 1):
                    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")
                    return HttpResponse(json.dumps(resp), mimetype='application/json')
            if (contact in institution.institutiondetails.contact.all() and len(institution.institutiondetails.contact.all()) == 1):
                    resp['error'] = "Could not delete contact. It is the only contact your institution.<br>Fix it and try again"
                    return HttpResponse(json.dumps(resp), mimetype='application/json')
            contact.delete()
        except Exception:
            resp['error'] = "Could not delete contact"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        resp['success'] = "Contact successfully deleted"
        return HttpResponse(json.dumps(resp), mimetype='application/json')
    


523 524 525 526 527 528
@login_required
def base_response(request):
    user = request.user
    inst = []
    server = []
    services = []
529
    instrealms = []
530 531
    instcontacts = []
    contacts = []
532 533 534 535 536 537
    try:
        profile = user.get_profile()
        institution = profile.institution
        inst.append(institution)
        server = InstServer.objects.filter(instid=institution)
        services = ServiceLoc.objects.filter(institutionid=institution)
538
        instrealms = InstRealm.objects.filter(instid=institution)
539 540
        instcontacts.extend([x.contact.pk for x in InstitutionContactPool.objects.filter(institution=institution)])
        contacts = Contact.objects.filter(pk__in=instcontacts)
541 542 543 544 545 546 547
    except UserProfile.DoesNotExist:
        pass
        
    return { 
            'inst_num': len(inst),
            'servers_num': len(server),
            'services_num': len(services),
548
            'realms_num': len(instrealms),
549
            'contacts_num': len(contacts),
550 551 552
            
        }

553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
@login_required
def del_server(request):
    if request.method == 'GET':
        user = request.user
        req_data = request.GET.copy()
        server_pk = req_data['server_pk']
        profile = user.get_profile()
        institution = profile.institution
        resp = {}
        try:
            server = InstServer.objects.get(instid=institution, pk=server_pk)
        except InstServer.DoesNotExist:
            resp['error'] = "Could not get server or you have no rights to delete"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        try:
            server.delete()
        except:
            resp['error'] = "Could not delete server"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        resp['success'] = "Server successfully deleted"
        return HttpResponse(json.dumps(resp), mimetype='application/json')
    
    
@login_required
def del_service(request):
    if request.method == 'GET':
        user = request.user
        req_data = request.GET.copy()
        service_pk = req_data['service_pk']
        profile = user.get_profile()
        institution = profile.institution
        resp = {}
        try:
            service = ServiceLoc.objects.get(institutionid=institution, pk=service_pk)
        except ServiceLoc.DoesNotExist:
            resp['error'] = "Could not get service or you have no rights to delete"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        try:
            service.delete()
        except:
            resp['error'] = "Could not delete service"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        resp['success'] = "Service successfully deleted"
        return HttpResponse(json.dumps(resp), mimetype='application/json')
    


600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
def geolocate(request):
    return render_to_response('front/geolocate.html',
                                  context_instance=RequestContext(request))


def closest(request):
    if request.method == 'GET':
        locs = []
        request_data = request.GET.copy()
        response_location = {}
        response_location["lat"] = request_data['lat']
        response_location["lng"] = request_data['lng']
        lat = float(request_data['lat'])
        lng = float(request_data['lng'])
        R = 6371
        distances = {}
        closestMarker = {}
        closest = -1
        doc = ET.parse(settings.KML_FILE)
        root = doc.getroot()
        r = root.getchildren()[0]
        for (counter, i) in enumerate(r.getchildren()):
            if "id" in i.keys():
                j = i.getchildren()
                pointname = j[0].text
                point = j[2].getchildren()[0].text
                pointlng, pointlat, pointele = point.split(',')
                dLat = rad(float(pointlat)-float(lat))
                dLong = rad(float(pointlng)-float(lng))
                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) 
                c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
                d = R * c
                distances[counter] = d
                if (closest == -1 or d < distances[closest]):
                    closest = counter
                    closestMarker = {"name": pointname, "lat": pointlat, "lng": pointlng, "text": j[1].text}
        return HttpResponse(json.dumps(closestMarker), mimetype='application/json')
        
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689

def instxml(request):
    ET._namespace_map["http://www.w3.org/2001/XMLSchema-instance"] = 'xsi'
    root = ET.Element("institutions")
    NS_XSI = "{http://www.w3.org/2001/XMLSchema-instance}"
    root.set(NS_XSI + "noNamespaceSchemaLocation", "institutions.xsd")
    #root.attrib["xsi:noNamespaceSchemaLocation"] = "institution.xsd"
    institutions = Institution.objects.all()
    for institution in institutions:
        try:
            inst = institution.institutiondetails
            if not inst:
                pass
        except InstitutionDetails.DoesNotExist:
            pass
        
        instElement = ET.SubElement(root, "institution")
        
        instCountry = ET.SubElement(instElement, "country")
        instCountry.text = ("%s" %inst.institution.realmid.country).upper()
        
        instType = ET.SubElement(instElement, "type")
        instType.text = "%s" %inst.ertype
        
        for realm in institution.instrealm_set.all():
            instRealm = ET.SubElement(instElement, "inst_realm")
            instRealm.text = realm.realm
        
        for name in inst.institution.org_name.all():
            instOrgName = ET.SubElement(instElement, "org_name")
            instOrgName.attrib["lang"] = name.lang
            instOrgName.text = u"%s" %name.name
        
        instAddress = ET.SubElement(instElement, "address")
        
        instAddrStreet = ET.SubElement(instAddress, "street")
        instAddrStreet.text = inst.address_street
        
        instAddrCity = ET.SubElement(instAddress, "city")
        instAddrCity.text = inst.address_city
        
        for contact in inst.contact.all():
            instContact = ET.SubElement(instElement, "contact")
            
            instContactName = ET.SubElement(instContact, "name")
            instContactName.text = "%s %s" %(contact.firstname, contact.lastname)
            
            instContactEmail = ET.SubElement(instContact, "email")
            instContactEmail.text = contact.email
            
            instContactPhone = ET.SubElement(instContact, "phone")
            instContactPhone.text = contact.phone
690
        
691 692 693 694 695 696
        for url in inst.url.all():
            instUrl = ET.SubElement(instElement, "%s_URL"%(url.urltype))
            instUrl.attrib["lang"] = url.lang
            instUrl.text = url.url
        
        #Let's go to Institution Service Locations
697

698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
        for serviceloc in inst.institution.serviceloc_set.all():
            instLocation = ET.SubElement(instElement, "location")
            
            instLong = ET.SubElement(instLocation, "longitude")
            instLong.text = "%s" %serviceloc.longitude
            
            instLat = ET.SubElement(instLocation, "latitude")
            instLat.text = "%s" %serviceloc.latitude
            
            for instlocname in serviceloc.loc_name.all():
                instLocName = ET.SubElement(instLocation, "loc_name")
                instLocName.attrib["lang"] = instlocname.lang
                instLocName.text = instlocname.name
            
            instLocAddress = ET.SubElement(instLocation, "address")
        
            instLocAddrStreet = ET.SubElement(instLocAddress, "street")
            instLocAddrStreet.text = serviceloc.address_street
        
            instLocAddrCity = ET.SubElement(instLocAddress, "city")
            instLocAddrCity.text = serviceloc.address_city
            
            instLocSSID = ET.SubElement(instLocation, "SSID")
            instLocSSID.text = serviceloc.SSID
            
            instLocEncLevel = ET.SubElement(instLocation, "enc_level")
            instLocEncLevel.text = serviceloc.enc_level
            
            instLocPortRestrict = ET.SubElement(instLocation, "port_restrict")
            instLocPortRestrict.text = ("%s" %serviceloc.port_restrict).lower()
            
            instLocTransProxy = ET.SubElement(instLocation, "transp_proxy")
            instLocTransProxy.text = ("%s" %serviceloc.transp_proxy).lower()
            
            instLocIpv6 = ET.SubElement(instLocation, "IPv6")
            instLocIpv6.text = ("%s" %serviceloc.IPv6).lower()
            
            instLocNAT = ET.SubElement(instLocation, "NAT")
            instLocNAT.text = ("%s" %serviceloc.NAT).lower()
            
            instLocAP_no = ET.SubElement(instLocation, "AP_no")
            instLocAP_no.text = "%s" %int(serviceloc.AP_no)
            
            instLocWired = ET.SubElement(instLocation, "wired")
            instLocWired.text = ("%s" %serviceloc.wired).lower()
            
            for url in serviceloc.url.all():
                instLocUrl = ET.SubElement(instLocation, "%s_URL"%(url.urltype))
                instLocUrl.attrib["lang"] = url.lang
                instLocUrl.text = url.url

        instTs = ET.SubElement(instElement, "ts")
        instTs.text = "%s" %inst.ts.isoformat()
            
    return render_to_response("general/institution.xml", {"xml":to_xml(root)},context_instance=RequestContext(request,), mimetype="application/xml")
        

def realmxml(request):
    realm = Realm.objects.all()[0]
    ET._namespace_map["http://www.w3.org/2001/XMLSchema-instance"] = 'xsi'
    root = ET.Element("realms")
    NS_XSI = "{http://www.w3.org/2001/XMLSchema-instance}"
    root.set(NS_XSI + "noNamespaceSchemaLocation", "realm.xsd")
    #root.attrib["xsi:noNamespaceSchemaLocation"] = "institution.xsd"
    realmElement = ET.SubElement(root, "realm")
    
    realmCountry = ET.SubElement(realmElement, "country")
    realmCountry.text = realm.country
        
    realmStype = ET.SubElement(realmElement, "stype")
    realmStype.text = "%s" %realm.stype
    
    for name in realm.org_name.all():
        realmOrgName = ET.SubElement(realmElement, "org_name")
        realmOrgName.attrib["lang"] = name.lang
        realmOrgName.text = u"%s" %name.name
    
    realmAddress = ET.SubElement(realmElement, "address")
        
    realmAddrStreet = ET.SubElement(realmAddress, "street")
    realmAddrStreet.text = realm.address_street
    
    realmAddrCity = ET.SubElement(realmAddress, "city")
    realmAddrCity.text = realm.address_city
    
    for contact in realm.contact.all():
        realmContact = ET.SubElement(realmElement, "contact")
        
        realmContactName = ET.SubElement(realmContact, "name")
        realmContactName.text = "%s %s" %(contact.firstname, contact.lastname)
        
        realmContactEmail = ET.SubElement(realmContact, "email")
        realmContactEmail.text = contact.email
        
        realmContactPhone = ET.SubElement(realmContact, "phone")
        realmContactPhone.text = contact.phone
    
    for url in realm.url.all():
        realmUrl = ET.SubElement(realmElement, "%s_URL"%(url.urltype))
        realmUrl.attrib["lang"] = url.lang
        realmUrl.text = url.url
    
    return render_to_response("general/realm.xml", {"xml":to_xml(root)},context_instance=RequestContext(request,), mimetype="application/xml")

def realmdataxml(request):
    realm = Realm.objects.all()[0]
    ET._namespace_map["http://www.w3.org/2001/XMLSchema-instance"] = 'xsi'
    root = ET.Element("realm-data")
    NS_XSI = "{http://www.w3.org/2001/XMLSchema-instance}"
    root.set(NS_XSI + "noNamespaceSchemaLocation", "realm-data.xsd")
    
    return render_to_response("general/realm_data.xml", {"xml":to_xml(root)},context_instance=RequestContext(request,), mimetype="application/xml")

def to_xml(ele, encoding="UTF-8"):
    "Convert and return the XML for an *ele* (:class:`~xml.etree.ElementTree.Element`) with specified *encoding*."
    xml = ET.tostring(ele, encoding)
    return xml if xml.startswith('<?xml') else '<?xml version="1.0" encoding="%s"?>%s' % (encoding, xml)
    
    
817 818 819 820 821 822 823
def getInstContacts(inst):
    contacts = InstitutionContactPool.objects.filter(institution=inst)
    contact_pks = []
    for contact in contacts:
        contact_pks.append(contact.contact.pk)
    return list(set(contact_pks))

824 825 826 827 828 829 830 831
def getInstServers(inst):
    servers = InstServer.objects.filter(instid=inst)
    server_pks = []
    for server in servers:
        server_pks.append(server.pk)
    return list(set(server_pks))


832
def rad(x):
833
    return x*math.pi/180