Statistics
| Branch: | Tag: | Revision:

root / edumanage / views.py @ cca6833d

History | View | Annotate | Download (76.7 kB)

1 a3923fe7 Leonidas Poulopoulos
# -*- coding: utf-8 -*- vim:encoding=utf-8:
2 a3923fe7 Leonidas Poulopoulos
# vim: tabstop=4:shiftwidth=4:softtabstop=4:expandtab
3 a3923fe7 Leonidas Poulopoulos
4 dc16526f Leonidas Poulopoulos
from django.shortcuts import render_to_response,get_object_or_404,redirect
5 a3923fe7 Leonidas Poulopoulos
from django.http import HttpResponse,HttpResponseRedirect,Http404
6 a3923fe7 Leonidas Poulopoulos
from django.template import RequestContext
7 f60df981 Leonidas Poulopoulos
from django.core.urlresolvers import reverse
8 a3923fe7 Leonidas Poulopoulos
from django.contrib.auth.decorators import login_required
9 dc16526f Leonidas Poulopoulos
from django.contrib.auth import logout
10 a3923fe7 Leonidas Poulopoulos
from edumanage.models import *
11 244d3095 Leonidas Poulopoulos
from accounts.models import *
12 fa8b2f7d Leonidas Poulopoulos
from edumanage.forms import *
13 fa8b2f7d Leonidas Poulopoulos
from django import forms
14 02f2ae43 Leonidas Poulopoulos
from django.forms.models import modelformset_factory
15 02f2ae43 Leonidas Poulopoulos
from django.forms.models import inlineformset_factory
16 02f2ae43 Leonidas Poulopoulos
from django.contrib.contenttypes.generic import generic_inlineformset_factory
17 7973b176 Leonidas Poulopoulos
from django.core.mail.message import EmailMessage
18 7973b176 Leonidas Poulopoulos
from django.contrib.sites.models import Site
19 7973b176 Leonidas Poulopoulos
from django.template.loader import render_to_string
20 d163b72b Leonidas Poulopoulos
import json, bz2
21 20802476 Leonidas Poulopoulos
import math, datetime
22 c2b3014a Leonidas Poulopoulos
from xml.etree import ElementTree as ET
23 af9d484b Leonidas Poulopoulos
24 af9d484b Leonidas Poulopoulos
from django.conf import settings
25 fa2f119d Leonidas Poulopoulos
from django.contrib import messages
26 a3923fe7 Leonidas Poulopoulos
27 0790d933 Leonidas Poulopoulos
from django.db.models import Max
28 0790d933 Leonidas Poulopoulos
29 62d0c01e Leonidas Poulopoulos
from django.views.decorators.cache import never_cache
30 62d0c01e Leonidas Poulopoulos
from django.utils.translation import ugettext as _
31 62d0c01e Leonidas Poulopoulos
from django.contrib.auth import authenticate, login
32 7973b176 Leonidas Poulopoulos
from registration.models import RegistrationProfile
33 d163b72b Leonidas Poulopoulos
from django.core.cache import cache
34 d163b72b Leonidas Poulopoulos
35 c666e0f0 Leonidas Poulopoulos
from edumanage.decorators import social_active_required
36 04cbcb1e Leonidas Poulopoulos
from utils.cat_helper import *
37 c666e0f0 Leonidas Poulopoulos
38 bcebee6b Leonidas Poulopoulos
@never_cache
39 a3923fe7 Leonidas Poulopoulos
def index(request):
40 8a177e59 Leonidas Poulopoulos
    return render_to_response('front/index.html', context_instance=RequestContext(request))
41 a3923fe7 Leonidas Poulopoulos
42 dc16526f Leonidas Poulopoulos
@never_cache
43 dc16526f Leonidas Poulopoulos
def manage_login_front(request):
44 dc16526f Leonidas Poulopoulos
    user = request.user
45 dc16526f Leonidas Poulopoulos
    try:
46 dc16526f Leonidas Poulopoulos
        profile = user.get_profile()
47 dc16526f Leonidas Poulopoulos
    except UserProfile.DoesNotExist:
48 dc16526f Leonidas Poulopoulos
        return render_to_response('edumanage/welcome_manage.html',
49 dc16526f Leonidas Poulopoulos
                              context_instance=RequestContext(request, base_response(request)))
50 dc16526f Leonidas Poulopoulos
    except AttributeError:
51 dc16526f Leonidas Poulopoulos
        return render_to_response('edumanage/welcome_manage.html',
52 dc16526f Leonidas Poulopoulos
                              context_instance=RequestContext(request, base_response(request)))
53 dc16526f Leonidas Poulopoulos
    if user.is_authenticated() and user.is_active and profile.is_social_active:
54 dc16526f Leonidas Poulopoulos
        return redirect(reverse('manage'))
55 dc16526f Leonidas Poulopoulos
    else:
56 dc16526f Leonidas Poulopoulos
        return render_to_response('edumanage/welcome_manage.html',
57 dc16526f Leonidas Poulopoulos
                              context_instance=RequestContext(request, base_response(request)))
58 d163b72b Leonidas Poulopoulos
59 a3923fe7 Leonidas Poulopoulos
@login_required
60 c666e0f0 Leonidas Poulopoulos
@social_active_required
61 d163b72b Leonidas Poulopoulos
@never_cache
62 a3923fe7 Leonidas Poulopoulos
def manage(request):
63 a3923fe7 Leonidas Poulopoulos
    services_list = []
64 a3923fe7 Leonidas Poulopoulos
    servers_list = []
65 fa8b2f7d Leonidas Poulopoulos
    user = request.user
66 fa8b2f7d Leonidas Poulopoulos
    try:
67 fa8b2f7d Leonidas Poulopoulos
        profile = user.get_profile()
68 fa8b2f7d Leonidas Poulopoulos
        inst = profile.institution
69 fa8b2f7d Leonidas Poulopoulos
    except UserProfile.DoesNotExist:
70 244d3095 Leonidas Poulopoulos
        return render_to_response('edumanage/welcome.html',
71 244d3095 Leonidas Poulopoulos
                              context_instance=RequestContext(request, base_response(request)))
72 244d3095 Leonidas Poulopoulos
        
73 fa8b2f7d Leonidas Poulopoulos
    services = ServiceLoc.objects.filter(institutionid=inst)
74 fa8b2f7d Leonidas Poulopoulos
    services_list.extend([s for s in services])
75 fa8b2f7d Leonidas Poulopoulos
    servers = InstServer.objects.filter(instid=inst)
76 fa8b2f7d Leonidas Poulopoulos
    servers_list.extend([s for s in servers])
77 a3923fe7 Leonidas Poulopoulos
    return render_to_response('edumanage/welcome.html', 
78 a3923fe7 Leonidas Poulopoulos
                              {
79 fa8b2f7d Leonidas Poulopoulos
                               'institution': inst, 
80 a3923fe7 Leonidas Poulopoulos
                               'services': services_list,
81 8a177e59 Leonidas Poulopoulos
                               'servers': servers_list,                               
82 a3923fe7 Leonidas Poulopoulos
                               },  
83 af9d484b Leonidas Poulopoulos
                              context_instance=RequestContext(request, base_response(request)))
84 a3923fe7 Leonidas Poulopoulos
85 a3923fe7 Leonidas Poulopoulos
@login_required
86 c666e0f0 Leonidas Poulopoulos
@social_active_required
87 d163b72b Leonidas Poulopoulos
@never_cache
88 a3923fe7 Leonidas Poulopoulos
def institutions(request):
89 a3923fe7 Leonidas Poulopoulos
    user = request.user
90 fa8b2f7d Leonidas Poulopoulos
    dict = {}
91 fa8b2f7d Leonidas Poulopoulos
    try:
92 fa8b2f7d Leonidas Poulopoulos
        profile = user.get_profile()
93 fa8b2f7d Leonidas Poulopoulos
        inst = profile.institution
94 fa8b2f7d Leonidas Poulopoulos
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
95 fa8b2f7d Leonidas Poulopoulos
    except UserProfile.DoesNotExist:
96 244d3095 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
97 fa8b2f7d Leonidas Poulopoulos
    dict['institution'] = inst.pk
98 fa8b2f7d Leonidas Poulopoulos
    form = InstDetailsForm(initial=dict)
99 fa8b2f7d Leonidas Poulopoulos
    form.fields['institution'].widget.attrs['readonly'] = True
100 fa8b2f7d Leonidas Poulopoulos
    return render_to_response('edumanage/institution.html', 
101 a3923fe7 Leonidas Poulopoulos
                              {
102 fa8b2f7d Leonidas Poulopoulos
                               'institution': inst,
103 fa8b2f7d Leonidas Poulopoulos
                               'form': form, 
104 a3923fe7 Leonidas Poulopoulos
                               },  
105 af9d484b Leonidas Poulopoulos
                              context_instance=RequestContext(request, base_response(request)))
106 fa8b2f7d Leonidas Poulopoulos
107 fa8b2f7d Leonidas Poulopoulos
108 fa8b2f7d Leonidas Poulopoulos
109 fa8b2f7d Leonidas Poulopoulos
@login_required
110 c666e0f0 Leonidas Poulopoulos
@social_active_required
111 d163b72b Leonidas Poulopoulos
@never_cache
112 fa8b2f7d Leonidas Poulopoulos
def add_institution_details(request, institution_pk):
113 fa8b2f7d Leonidas Poulopoulos
    user = request.user
114 f60df981 Leonidas Poulopoulos
    try:
115 f60df981 Leonidas Poulopoulos
        profile = user.get_profile()
116 f60df981 Leonidas Poulopoulos
        inst = profile.institution
117 7973b176 Leonidas Poulopoulos
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
118 f60df981 Leonidas Poulopoulos
    except UserProfile.DoesNotExist:
119 244d3095 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
120 244d3095 Leonidas Poulopoulos
    
121 f3bca340 Leonidas Poulopoulos
    if institution_pk and int(inst.pk) != int(institution_pk):
122 f3bca340 Leonidas Poulopoulos
        messages.add_message(request, messages.ERROR, 'You have no rights on this Institution')
123 f3bca340 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("institutions"))
124 f3bca340 Leonidas Poulopoulos
    
125 fa8b2f7d Leonidas Poulopoulos
    if request.method == "GET":
126 f60df981 Leonidas Poulopoulos
        try:         
127 f60df981 Leonidas Poulopoulos
            inst_details = InstitutionDetails.objects.get(institution=inst)
128 f60df981 Leonidas Poulopoulos
            form = InstDetailsForm(instance=inst_details)
129 b9e65644 Leonidas Poulopoulos
            UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFactInst, can_delete=True)
130 0f9fca26 Leonidas Poulopoulos
            urls_form = UrlFormSet(prefix='urlsform', instance = inst_details) 
131 f60df981 Leonidas Poulopoulos
        except InstitutionDetails.DoesNotExist:
132 f60df981 Leonidas Poulopoulos
            form = InstDetailsForm()
133 f60df981 Leonidas Poulopoulos
            form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=institution_pk), empty_label=None)
134 b9e65644 Leonidas Poulopoulos
            UrlFormSet =  generic_inlineformset_factory(URL_i18n, extra=2, can_delete=True)
135 0f9fca26 Leonidas Poulopoulos
            urls_form = UrlFormSet(prefix='urlsform')
136 f3bca340 Leonidas Poulopoulos
137 0f9fca26 Leonidas Poulopoulos
        
138 38f2278d Leonidas Poulopoulos
        form.fields['contact'] = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(pk__in=getInstContacts(inst)))
139 b9e65644 Leonidas Poulopoulos
        return render_to_response('edumanage/institution_edit.html', { 'institution': inst, 'form': form, 'urls_form':urls_form},
140 af9d484b Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
141 fa8b2f7d Leonidas Poulopoulos
    elif request.method == 'POST':
142 fa8b2f7d Leonidas Poulopoulos
        request_data = request.POST.copy()
143 b9e65644 Leonidas Poulopoulos
        UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFactInst, can_delete=True)
144 f60df981 Leonidas Poulopoulos
        try:         
145 f60df981 Leonidas Poulopoulos
            inst_details = InstitutionDetails.objects.get(institution=inst)
146 f60df981 Leonidas Poulopoulos
            form = InstDetailsForm(request_data, instance=inst_details)
147 b9e65644 Leonidas Poulopoulos
            urls_form = UrlFormSet(request_data, instance=inst_details, prefix='urlsform')
148 f60df981 Leonidas Poulopoulos
        except InstitutionDetails.DoesNotExist:
149 f60df981 Leonidas Poulopoulos
            form = InstDetailsForm(request_data)
150 b9e65644 Leonidas Poulopoulos
            urls_form = UrlFormSet(request_data, prefix='urlsform')
151 b9e65644 Leonidas Poulopoulos
        UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFactInst, can_delete=True)
152 b9e65644 Leonidas Poulopoulos
        if form.is_valid() and urls_form.is_valid():
153 f60df981 Leonidas Poulopoulos
            instdets = form.save()
154 b9e65644 Leonidas Poulopoulos
            urls_form.instance = instdets
155 b9e65644 Leonidas Poulopoulos
            urls_inst = urls_form.save()
156 f60df981 Leonidas Poulopoulos
            return HttpResponseRedirect(reverse("institutions"))
157 fa8b2f7d Leonidas Poulopoulos
        else:
158 b9e65644 Leonidas Poulopoulos
            form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=institution_pk), empty_label=None)
159 b9e65644 Leonidas Poulopoulos
            form.fields['contact'] = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(pk__in=getInstContacts(inst)))
160 b9e65644 Leonidas Poulopoulos
            return render_to_response('edumanage/institution_edit.html', { 'institution': inst, 'form': form, 'urls_form': urls_form},
161 af9d484b Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
162 fa8b2f7d Leonidas Poulopoulos
163 f60df981 Leonidas Poulopoulos
164 f60df981 Leonidas Poulopoulos
@login_required
165 c666e0f0 Leonidas Poulopoulos
@social_active_required
166 d163b72b Leonidas Poulopoulos
@never_cache
167 c01b785c Leonidas Poulopoulos
def services(request, service_pk):
168 f60df981 Leonidas Poulopoulos
    user = request.user
169 f60df981 Leonidas Poulopoulos
    dict = {}
170 f60df981 Leonidas Poulopoulos
    try:
171 f60df981 Leonidas Poulopoulos
        profile = user.get_profile()
172 f60df981 Leonidas Poulopoulos
        inst = profile.institution
173 7973b176 Leonidas Poulopoulos
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
174 f60df981 Leonidas Poulopoulos
    except UserProfile.DoesNotExist:
175 244d3095 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
176 7973b176 Leonidas Poulopoulos
    try:
177 7973b176 Leonidas Poulopoulos
        instdetails = inst.institutiondetails
178 7973b176 Leonidas Poulopoulos
    except InstitutionDetails.DoesNotExist:
179 7973b176 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
180 c2cca19e Leonidas Poulopoulos
    if inst.ertype not in [2,3]:
181 f3bca340 Leonidas Poulopoulos
        messages.add_message(request, messages.ERROR, 'Cannot add/edit Location. Your institution should be either SP or IdP/SP')
182 fa2f119d Leonidas Poulopoulos
        return render_to_response('edumanage/services.html', { 'institution': inst },
183 fa2f119d Leonidas Poulopoulos
                              context_instance=RequestContext(request, base_response(request)))
184 f60df981 Leonidas Poulopoulos
    try:
185 f60df981 Leonidas Poulopoulos
        services = ServiceLoc.objects.filter(institutionid = inst)
186 f60df981 Leonidas Poulopoulos
    except ServiceLoc.DoesNotExist:
187 f60df981 Leonidas Poulopoulos
        services = False 
188 c01b785c Leonidas Poulopoulos
    
189 c01b785c Leonidas Poulopoulos
    if service_pk:
190 f3bca340 Leonidas Poulopoulos
        try:
191 f3bca340 Leonidas Poulopoulos
            services = services.get(pk=service_pk)
192 f3bca340 Leonidas Poulopoulos
        except:
193 f3bca340 Leonidas Poulopoulos
            messages.add_message(request, messages.ERROR, 'You have no rights to view this location')
194 f3bca340 Leonidas Poulopoulos
            return HttpResponseRedirect(reverse("services"))
195 c01b785c Leonidas Poulopoulos
        return render_to_response('edumanage/service_details.html', 
196 c01b785c Leonidas Poulopoulos
                              {
197 c01b785c Leonidas Poulopoulos
                               'institution': inst,
198 0f9fca26 Leonidas Poulopoulos
                               'service': services,
199 c01b785c Leonidas Poulopoulos
                               },  
200 c01b785c Leonidas Poulopoulos
                              context_instance=RequestContext(request, base_response(request)))
201 f60df981 Leonidas Poulopoulos
    
202 f60df981 Leonidas Poulopoulos
    return render_to_response('edumanage/services.html', 
203 f60df981 Leonidas Poulopoulos
                              {
204 f60df981 Leonidas Poulopoulos
                               'institution': inst,
205 f60df981 Leonidas Poulopoulos
                               'services': services, 
206 f60df981 Leonidas Poulopoulos
                               },  
207 af9d484b Leonidas Poulopoulos
                              context_instance=RequestContext(request, base_response(request)))
208 f60df981 Leonidas Poulopoulos
209 f60df981 Leonidas Poulopoulos
210 f60df981 Leonidas Poulopoulos
211 f60df981 Leonidas Poulopoulos
@login_required
212 c666e0f0 Leonidas Poulopoulos
@social_active_required
213 d163b72b Leonidas Poulopoulos
@never_cache
214 f60df981 Leonidas Poulopoulos
def add_services(request, service_pk):
215 f60df981 Leonidas Poulopoulos
    user = request.user
216 02f2ae43 Leonidas Poulopoulos
    service = False
217 0f9fca26 Leonidas Poulopoulos
    edit = False
218 f60df981 Leonidas Poulopoulos
    try:
219 f60df981 Leonidas Poulopoulos
        profile = user.get_profile()
220 f60df981 Leonidas Poulopoulos
        inst = profile.institution
221 7973b176 Leonidas Poulopoulos
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
222 f60df981 Leonidas Poulopoulos
    except UserProfile.DoesNotExist:
223 244d3095 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
224 7973b176 Leonidas Poulopoulos
    try:
225 7973b176 Leonidas Poulopoulos
        instdetails = inst.institutiondetails
226 7973b176 Leonidas Poulopoulos
    except InstitutionDetails.DoesNotExist:
227 7973b176 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
228 c2cca19e Leonidas Poulopoulos
    if inst.ertype not in [2,3]:
229 fa2f119d Leonidas Poulopoulos
        messages.add_message(request, messages.ERROR, 'Cannot add/edit Service. Your institution should be either SP or IdP/SP')
230 fa2f119d Leonidas Poulopoulos
        return render_to_response('edumanage/services_edit.html', { 'edit': edit },
231 fa2f119d Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
232 f60df981 Leonidas Poulopoulos
    if request.method == "GET":
233 f60df981 Leonidas Poulopoulos
234 f60df981 Leonidas Poulopoulos
        # Determine add or edit
235 f60df981 Leonidas Poulopoulos
        try:         
236 f60df981 Leonidas Poulopoulos
            service = ServiceLoc.objects.get(institutionid=inst, pk=service_pk)
237 f60df981 Leonidas Poulopoulos
            form = ServiceLocForm(instance=service)
238 f60df981 Leonidas Poulopoulos
        except ServiceLoc.DoesNotExist:
239 f60df981 Leonidas Poulopoulos
            form = ServiceLocForm()
240 f3bca340 Leonidas Poulopoulos
            if service_pk:
241 f3bca340 Leonidas Poulopoulos
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this location')
242 f3bca340 Leonidas Poulopoulos
                return HttpResponseRedirect(reverse("services"))
243 02f2ae43 Leonidas Poulopoulos
        form.fields['institutionid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
244 af9d484b Leonidas Poulopoulos
        UrlFormSet =  generic_inlineformset_factory(URL_i18n, extra=2, can_delete=True)
245 af9d484b Leonidas Poulopoulos
        NameFormSet = generic_inlineformset_factory(Name_i18n, extra=2, can_delete=True)
246 c2cca19e Leonidas Poulopoulos
        urls_form = UrlFormSet(prefix='urlsform')
247 af9d484b Leonidas Poulopoulos
        names_form = NameFormSet(prefix='namesform')
248 02f2ae43 Leonidas Poulopoulos
        if (service):
249 af9d484b Leonidas Poulopoulos
            NameFormSet = generic_inlineformset_factory(Name_i18n, extra=1, formset=NameFormSetFact, can_delete=True)
250 af9d484b Leonidas Poulopoulos
            names_form = NameFormSet(instance=service, prefix='namesform')
251 af9d484b Leonidas Poulopoulos
            UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFact, can_delete=True)
252 af9d484b Leonidas Poulopoulos
            urls_form = UrlFormSet(instance=service, prefix='urlsform')
253 38f2278d Leonidas Poulopoulos
        form.fields['contact'] = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(pk__in=getInstContacts(inst)))
254 0f9fca26 Leonidas Poulopoulos
        if service:
255 0f9fca26 Leonidas Poulopoulos
            edit = True
256 c2cca19e Leonidas Poulopoulos
        for url_form in urls_form.forms:
257 c2cca19e Leonidas Poulopoulos
            url_form.fields['urltype'] = forms.ChoiceField(choices=(('', '----------'),('info', 'Info'),))
258 8a177e59 Leonidas Poulopoulos
        return render_to_response('edumanage/services_edit.html', { 'form': form, 'services_form':names_form, 'urls_form': urls_form, "edit": edit},
259 af9d484b Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
260 f60df981 Leonidas Poulopoulos
    elif request.method == 'POST':
261 f60df981 Leonidas Poulopoulos
        request_data = request.POST.copy()
262 af9d484b Leonidas Poulopoulos
        NameFormSet = generic_inlineformset_factory(Name_i18n, extra=1, formset=NameFormSetFact, can_delete=True)
263 af9d484b Leonidas Poulopoulos
        UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFact, can_delete=True)
264 f60df981 Leonidas Poulopoulos
        try:         
265 f60df981 Leonidas Poulopoulos
            service = ServiceLoc.objects.get(institutionid=inst, pk=service_pk)
266 f60df981 Leonidas Poulopoulos
            form = ServiceLocForm(request_data, instance=service)
267 af9d484b Leonidas Poulopoulos
            names_form = NameFormSet(request_data, instance=service, prefix='namesform')
268 af9d484b Leonidas Poulopoulos
            urls_form = UrlFormSet(request_data, instance=service, prefix='urlsform')
269 f60df981 Leonidas Poulopoulos
        except ServiceLoc.DoesNotExist:
270 f60df981 Leonidas Poulopoulos
            form = ServiceLocForm(request_data)
271 af9d484b Leonidas Poulopoulos
            names_form = NameFormSet(request_data, prefix='namesform')
272 af9d484b Leonidas Poulopoulos
            urls_form = UrlFormSet(request_data, prefix='urlsform')
273 f3bca340 Leonidas Poulopoulos
            if service_pk:
274 f3bca340 Leonidas Poulopoulos
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this location')
275 f3bca340 Leonidas Poulopoulos
                return HttpResponseRedirect(reverse("services"))
276 02f2ae43 Leonidas Poulopoulos
        
277 af9d484b Leonidas Poulopoulos
        if form.is_valid() and names_form.is_valid() and urls_form.is_valid():
278 02f2ae43 Leonidas Poulopoulos
            serviceloc = form.save()
279 af9d484b Leonidas Poulopoulos
            service = serviceloc
280 af9d484b Leonidas Poulopoulos
            names_form.instance = service
281 af9d484b Leonidas Poulopoulos
            urls_form.instance = service
282 af9d484b Leonidas Poulopoulos
            names_inst = names_form.save()
283 af9d484b Leonidas Poulopoulos
            urls_inst = urls_form.save()
284 f60df981 Leonidas Poulopoulos
            return HttpResponseRedirect(reverse("services"))
285 f60df981 Leonidas Poulopoulos
        else:
286 02f2ae43 Leonidas Poulopoulos
            form.fields['institutionid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
287 38f2278d Leonidas Poulopoulos
            form.fields['contact'] = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(pk__in=getInstContacts(inst)))
288 0f9fca26 Leonidas Poulopoulos
        if service:
289 0f9fca26 Leonidas Poulopoulos
            edit = True
290 c2cca19e Leonidas Poulopoulos
        for url_form in urls_form.forms:
291 c2cca19e Leonidas Poulopoulos
            url_form.fields['urltype'] = forms.ChoiceField(choices=(('', '----------'),('info', 'Info'),))
292 8a177e59 Leonidas Poulopoulos
        return render_to_response('edumanage/services_edit.html', { 'institution': inst, 'form': form, 'services_form':names_form, 'urls_form': urls_form, "edit": edit},
293 af9d484b Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
294 af9d484b Leonidas Poulopoulos
295 d163b72b Leonidas Poulopoulos
296 02f2ae43 Leonidas Poulopoulos
@login_required
297 c666e0f0 Leonidas Poulopoulos
@social_active_required
298 d163b72b Leonidas Poulopoulos
@never_cache
299 7973b176 Leonidas Poulopoulos
def del_service(request):
300 7973b176 Leonidas Poulopoulos
    if request.method == 'GET':
301 02f2ae43 Leonidas Poulopoulos
        user = request.user
302 7973b176 Leonidas Poulopoulos
        req_data = request.GET.copy()
303 7973b176 Leonidas Poulopoulos
        service_pk = req_data['service_pk']
304 02f2ae43 Leonidas Poulopoulos
        try:
305 02f2ae43 Leonidas Poulopoulos
            profile = user.get_profile()
306 7973b176 Leonidas Poulopoulos
            institution = profile.institution
307 02f2ae43 Leonidas Poulopoulos
        except UserProfile.DoesNotExist:
308 7973b176 Leonidas Poulopoulos
            resp['error'] = "Could not delete service. Not enough rights"
309 7973b176 Leonidas Poulopoulos
            return HttpResponse(json.dumps(resp), mimetype='application/json')
310 7973b176 Leonidas Poulopoulos
        resp = {}
311 7973b176 Leonidas Poulopoulos
        try:
312 7973b176 Leonidas Poulopoulos
            service = ServiceLoc.objects.get(institutionid=institution, pk=service_pk)
313 7973b176 Leonidas Poulopoulos
        except ServiceLoc.DoesNotExist:
314 7973b176 Leonidas Poulopoulos
            resp['error'] = "Could not get service or you have no rights to delete"
315 7973b176 Leonidas Poulopoulos
            return HttpResponse(json.dumps(resp), mimetype='application/json')
316 7973b176 Leonidas Poulopoulos
        try:
317 7973b176 Leonidas Poulopoulos
            service.delete()
318 7973b176 Leonidas Poulopoulos
        except:
319 7973b176 Leonidas Poulopoulos
            resp['error'] = "Could not delete service"
320 7973b176 Leonidas Poulopoulos
            return HttpResponse(json.dumps(resp), mimetype='application/json')
321 7973b176 Leonidas Poulopoulos
        resp['success'] = "Service successfully deleted"
322 7973b176 Leonidas Poulopoulos
        return HttpResponse(json.dumps(resp), mimetype='application/json')
323 af9d484b Leonidas Poulopoulos
324 d163b72b Leonidas Poulopoulos
325 0f9fca26 Leonidas Poulopoulos
@login_required
326 c666e0f0 Leonidas Poulopoulos
@social_active_required
327 d163b72b Leonidas Poulopoulos
@never_cache
328 0f9fca26 Leonidas Poulopoulos
def servers(request, server_pk):
329 af9d484b Leonidas Poulopoulos
    user = request.user
330 af9d484b Leonidas Poulopoulos
    servers = False
331 af9d484b Leonidas Poulopoulos
    try:
332 af9d484b Leonidas Poulopoulos
        profile = user.get_profile()
333 af9d484b Leonidas Poulopoulos
        inst = profile.institution
334 af9d484b Leonidas Poulopoulos
    except UserProfile.DoesNotExist:
335 af9d484b Leonidas Poulopoulos
        inst = False
336 244d3095 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
337 af9d484b Leonidas Poulopoulos
    if inst:
338 af9d484b Leonidas Poulopoulos
        servers = InstServer.objects.filter(instid=inst)
339 0f9fca26 Leonidas Poulopoulos
    if server_pk:
340 0f9fca26 Leonidas Poulopoulos
        servers = servers.get(pk=server_pk)
341 0f9fca26 Leonidas Poulopoulos
        return render_to_response('edumanage/server_details.html', 
342 0f9fca26 Leonidas Poulopoulos
                              {
343 0f9fca26 Leonidas Poulopoulos
                               'institution': inst,
344 0f9fca26 Leonidas Poulopoulos
                               'server': servers,
345 0f9fca26 Leonidas Poulopoulos
                               },  
346 0f9fca26 Leonidas Poulopoulos
                              context_instance=RequestContext(request, base_response(request)))
347 edac002f Leonidas Poulopoulos
    return render_to_response('edumanage/servers.html', { 'servers': servers},
348 af9d484b Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
349 af9d484b Leonidas Poulopoulos
350 d163b72b Leonidas Poulopoulos
351 af9d484b Leonidas Poulopoulos
@login_required
352 c666e0f0 Leonidas Poulopoulos
@social_active_required
353 d163b72b Leonidas Poulopoulos
@never_cache
354 edac002f Leonidas Poulopoulos
def add_server(request, server_pk):
355 edac002f Leonidas Poulopoulos
    user = request.user
356 edac002f Leonidas Poulopoulos
    server = False
357 0f9fca26 Leonidas Poulopoulos
    edit = False
358 edac002f Leonidas Poulopoulos
    try:
359 edac002f Leonidas Poulopoulos
        profile = user.get_profile()
360 edac002f Leonidas Poulopoulos
        inst = profile.institution
361 7973b176 Leonidas Poulopoulos
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
362 edac002f Leonidas Poulopoulos
    except UserProfile.DoesNotExist:
363 244d3095 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
364 7973b176 Leonidas Poulopoulos
    try:
365 7973b176 Leonidas Poulopoulos
        instdetails = inst.institutiondetails
366 7973b176 Leonidas Poulopoulos
    except InstitutionDetails.DoesNotExist:
367 7973b176 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
368 edac002f Leonidas Poulopoulos
    if request.method == "GET":
369 edac002f Leonidas Poulopoulos
        # Determine add or edit
370 edac002f Leonidas Poulopoulos
        try:         
371 edac002f Leonidas Poulopoulos
            server = InstServer.objects.get(instid=inst, pk=server_pk)
372 edac002f Leonidas Poulopoulos
            form = InstServerForm(instance=server)
373 edac002f Leonidas Poulopoulos
        except InstServer.DoesNotExist:
374 edac002f Leonidas Poulopoulos
            form = InstServerForm()
375 f3bca340 Leonidas Poulopoulos
            if server_pk:
376 f3bca340 Leonidas Poulopoulos
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this server')
377 f3bca340 Leonidas Poulopoulos
                return HttpResponseRedirect(reverse("servers"))  
378 edac002f Leonidas Poulopoulos
        form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
379 0f9fca26 Leonidas Poulopoulos
        if server:
380 0f9fca26 Leonidas Poulopoulos
            edit = True
381 f3bca340 Leonidas Poulopoulos
                      
382 0f9fca26 Leonidas Poulopoulos
        return render_to_response('edumanage/servers_edit.html', { 'form': form, 'edit': edit },
383 af9d484b Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
384 edac002f Leonidas Poulopoulos
    elif request.method == 'POST':
385 edac002f Leonidas Poulopoulos
        request_data = request.POST.copy()
386 edac002f Leonidas Poulopoulos
        try:         
387 edac002f Leonidas Poulopoulos
            server = InstServer.objects.get(instid=inst, pk=server_pk)
388 edac002f Leonidas Poulopoulos
            form = InstServerForm(request_data, instance=server)
389 edac002f Leonidas Poulopoulos
        except InstServer.DoesNotExist:
390 edac002f Leonidas Poulopoulos
            form = InstServerForm(request_data)
391 f3bca340 Leonidas Poulopoulos
            if server_pk:
392 f3bca340 Leonidas Poulopoulos
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this server')
393 f3bca340 Leonidas Poulopoulos
                return HttpResponseRedirect(reverse("servers")) 
394 edac002f Leonidas Poulopoulos
        
395 edac002f Leonidas Poulopoulos
        if form.is_valid():
396 edac002f Leonidas Poulopoulos
            instserverf = form.save()
397 edac002f Leonidas Poulopoulos
            return HttpResponseRedirect(reverse("servers"))
398 edac002f Leonidas Poulopoulos
        else:
399 edac002f Leonidas Poulopoulos
            form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
400 0f9fca26 Leonidas Poulopoulos
        if server:
401 0f9fca26 Leonidas Poulopoulos
            edit = True
402 0f9fca26 Leonidas Poulopoulos
        return render_to_response('edumanage/servers_edit.html', { 'institution': inst, 'form': form, 'edit': edit },
403 af9d484b Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
404 af9d484b Leonidas Poulopoulos
405 d163b72b Leonidas Poulopoulos
406 af9d484b Leonidas Poulopoulos
@login_required
407 c666e0f0 Leonidas Poulopoulos
@social_active_required
408 d163b72b Leonidas Poulopoulos
@never_cache
409 04cbcb1e Leonidas Poulopoulos
def cat_enroll(request):
410 04cbcb1e Leonidas Poulopoulos
    user = request.user
411 04cbcb1e Leonidas Poulopoulos
    edit = False
412 04cbcb1e Leonidas Poulopoulos
    cat_url = None
413 04cbcb1e Leonidas Poulopoulos
    inst_uid = None
414 04cbcb1e Leonidas Poulopoulos
    try:
415 04cbcb1e Leonidas Poulopoulos
        profile = user.get_profile()
416 04cbcb1e Leonidas Poulopoulos
        inst = profile.institution
417 04cbcb1e Leonidas Poulopoulos
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
418 04cbcb1e Leonidas Poulopoulos
    except UserProfile.DoesNotExist:
419 04cbcb1e Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
420 04cbcb1e Leonidas Poulopoulos
    try:
421 04cbcb1e Leonidas Poulopoulos
        instdetails = inst.institutiondetails
422 04cbcb1e Leonidas Poulopoulos
    except InstitutionDetails.DoesNotExist:
423 04cbcb1e Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
424 04cbcb1e Leonidas Poulopoulos
    if inst.ertype not in [1,3]:
425 04cbcb1e Leonidas Poulopoulos
        messages.add_message(request, messages.ERROR, 'Cannot add/edit Realms. Your institution should be either IdP or IdP/SP')
426 04cbcb1e Leonidas Poulopoulos
        return render_to_response('edumanage/catenroll.html', { 'status':False },
427 04cbcb1e Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
428 04cbcb1e Leonidas Poulopoulos
    if request.method == "GET":
429 04cbcb1e Leonidas Poulopoulos
        current_enrollments = inst.catenrollment_set.all()
430 04cbcb1e Leonidas Poulopoulos
        current_enrollments_list = current_enrollments.values_list('cat_instance', flat=True)
431 04cbcb1e Leonidas Poulopoulos
        available_enrollments = [(x[0], x[1]) for x in settings.CAT_INSTANCES if x[0] not in current_enrollments_list]
432 04cbcb1e Leonidas Poulopoulos
        if len(available_enrollments) == 0:
433 04cbcb1e Leonidas Poulopoulos
            messages.add_message(request, messages.ERROR, 'There are no available CAT instances for your institution enrollment')
434 04cbcb1e Leonidas Poulopoulos
            return render_to_response('edumanage/catenroll.html', { 'status': False, 'cat_instances': available_enrollments},
435 04cbcb1e Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
436 04cbcb1e Leonidas Poulopoulos
        return render_to_response('edumanage/catenroll.html', { 'status': True, 'current_enrollments': current_enrollments, 'cat_instances': available_enrollments},
437 04cbcb1e Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
438 04cbcb1e Leonidas Poulopoulos
    elif request.method == 'POST':
439 04cbcb1e Leonidas Poulopoulos
        request_data = request.POST.copy()
440 04cbcb1e Leonidas Poulopoulos
        instance = request_data['catinstance']
441 04cbcb1e Leonidas Poulopoulos
        #Check if cat enrollment exists. It should not! 
442 04cbcb1e Leonidas Poulopoulos
        if inst.catenrollment_set.filter(cat_instance=instance):
443 04cbcb1e Leonidas Poulopoulos
            messages.add_message(request, messages.ERROR, 'There is already and enrollment for this CAT instance')
444 04cbcb1e Leonidas Poulopoulos
            return HttpResponseRedirect(reverse("catenroll"))
445 04cbcb1e Leonidas Poulopoulos
        try:
446 04cbcb1e Leonidas Poulopoulos
            cat_instance = settings.CAT_AUTH[instance]
447 04cbcb1e Leonidas Poulopoulos
        except:
448 04cbcb1e Leonidas Poulopoulos
            messages.add_message(request, messages.ERROR, 'Invalid CAT instance')
449 04cbcb1e Leonidas Poulopoulos
            return HttpResponseRedirect(reverse("catenroll"))
450 04cbcb1e Leonidas Poulopoulos
        cat_api_key = cat_instance['CAT_API_KEY']
451 04cbcb1e Leonidas Poulopoulos
        cat_api_url = cat_instance['CAT_API_URL']
452 04cbcb1e Leonidas Poulopoulos
       
453 04cbcb1e Leonidas Poulopoulos
        enroll = CatQuery(cat_api_key, cat_api_url)
454 04cbcb1e Leonidas Poulopoulos
        params = {'NEWINST_PRIMARYADMIN': u"%s"%user.email,
455 04cbcb1e Leonidas Poulopoulos
                    'option[S1]': 'general:instname',
456 04cbcb1e Leonidas Poulopoulos
                    'value[S1-0]': u"%s"%inst.get_name('en'),
457 04cbcb1e Leonidas Poulopoulos
                    'value[S1-lang]': 'en'}
458 04cbcb1e Leonidas Poulopoulos
        newinst = enroll.newinst(params)
459 04cbcb1e Leonidas Poulopoulos
        cat_url = None
460 04cbcb1e Leonidas Poulopoulos
        inst_uid = None
461 04cbcb1e Leonidas Poulopoulos
        if newinst:
462 04cbcb1e Leonidas Poulopoulos
            # this should be True only for successful postings
463 04cbcb1e Leonidas Poulopoulos
            status = enroll.status
464 04cbcb1e Leonidas Poulopoulos
            response = enroll.response
465 04cbcb1e Leonidas Poulopoulos
            inst_uid = response['inst_unique_id']
466 04cbcb1e Leonidas Poulopoulos
            cat_url = response['enrollment_URL']
467 04cbcb1e Leonidas Poulopoulos
            catentry = CatEnrollment()
468 04cbcb1e Leonidas Poulopoulos
            catentry.cat_inst_id = inst_uid
469 04cbcb1e Leonidas Poulopoulos
            catentry.inst = inst
470 04cbcb1e Leonidas Poulopoulos
            catentry.url = cat_url
471 04cbcb1e Leonidas Poulopoulos
            catentry.applier = user
472 04cbcb1e Leonidas Poulopoulos
            catentry.cat_instance = instance
473 04cbcb1e Leonidas Poulopoulos
            catentry.save()
474 04cbcb1e Leonidas Poulopoulos
            # We should notify the user
475 04cbcb1e Leonidas Poulopoulos
        else:
476 04cbcb1e Leonidas Poulopoulos
            status = enroll.status
477 04cbcb1e Leonidas Poulopoulos
            response = enroll.response
478 04cbcb1e Leonidas Poulopoulos
        return render_to_response('edumanage/catenroll.html', { 'status': True, 'response_status': status, 'response': response, 'cat_url':cat_url, 'inst_uid': inst_uid},
479 04cbcb1e Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
480 04cbcb1e Leonidas Poulopoulos
481 04cbcb1e Leonidas Poulopoulos
482 04cbcb1e Leonidas Poulopoulos
483 04cbcb1e Leonidas Poulopoulos
484 04cbcb1e Leonidas Poulopoulos
@login_required
485 04cbcb1e Leonidas Poulopoulos
@social_active_required
486 04cbcb1e Leonidas Poulopoulos
@never_cache
487 7973b176 Leonidas Poulopoulos
def del_server(request):
488 7973b176 Leonidas Poulopoulos
    if request.method == 'GET':
489 7973b176 Leonidas Poulopoulos
        user = request.user
490 7973b176 Leonidas Poulopoulos
        req_data = request.GET.copy()
491 7973b176 Leonidas Poulopoulos
        server_pk = req_data['server_pk']
492 7973b176 Leonidas Poulopoulos
        try:
493 7973b176 Leonidas Poulopoulos
            profile = user.get_profile()
494 7973b176 Leonidas Poulopoulos
            institution = profile.institution
495 7973b176 Leonidas Poulopoulos
        except UserProfile.DoesNotExist:
496 7973b176 Leonidas Poulopoulos
            resp['error'] = "Could not delete server. Not enough rights"
497 7973b176 Leonidas Poulopoulos
            return HttpResponse(json.dumps(resp), mimetype='application/json')
498 7973b176 Leonidas Poulopoulos
        resp = {}
499 7973b176 Leonidas Poulopoulos
        try:
500 7973b176 Leonidas Poulopoulos
            server = InstServer.objects.get(instid=institution, pk=server_pk)
501 7973b176 Leonidas Poulopoulos
        except InstServer.DoesNotExist:
502 7973b176 Leonidas Poulopoulos
            resp['error'] = "Could not get server or you have no rights to delete"
503 7973b176 Leonidas Poulopoulos
            return HttpResponse(json.dumps(resp), mimetype='application/json')
504 7973b176 Leonidas Poulopoulos
        try:
505 7973b176 Leonidas Poulopoulos
            server.delete()
506 7973b176 Leonidas Poulopoulos
        except:
507 7973b176 Leonidas Poulopoulos
            resp['error'] = "Could not delete server"
508 7973b176 Leonidas Poulopoulos
            return HttpResponse(json.dumps(resp), mimetype='application/json')
509 7973b176 Leonidas Poulopoulos
        resp['success'] = "Server successfully deleted"
510 7973b176 Leonidas Poulopoulos
        return HttpResponse(json.dumps(resp), mimetype='application/json')
511 7973b176 Leonidas Poulopoulos
512 7973b176 Leonidas Poulopoulos
513 7973b176 Leonidas Poulopoulos
@login_required
514 c666e0f0 Leonidas Poulopoulos
@social_active_required
515 d163b72b Leonidas Poulopoulos
@never_cache
516 04df82f7 Leonidas Poulopoulos
def realms(request):
517 04df82f7 Leonidas Poulopoulos
    user = request.user
518 04df82f7 Leonidas Poulopoulos
    servers = False
519 04df82f7 Leonidas Poulopoulos
    try:
520 04df82f7 Leonidas Poulopoulos
        profile = user.get_profile()
521 04df82f7 Leonidas Poulopoulos
        inst = profile.institution
522 04df82f7 Leonidas Poulopoulos
    except UserProfile.DoesNotExist:
523 244d3095 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
524 04df82f7 Leonidas Poulopoulos
    if inst:
525 04df82f7 Leonidas Poulopoulos
        realms = InstRealm.objects.filter(instid=inst)
526 c2cca19e Leonidas Poulopoulos
    if inst.ertype not in [1,3]:
527 fa2f119d Leonidas Poulopoulos
        messages.add_message(request, messages.ERROR, 'Cannot add/edit Realms. Your institution should be either IdP or IdP/SP')
528 fa2f119d Leonidas Poulopoulos
    return render_to_response('edumanage/realms.html', { 'realms': realms },
529 04df82f7 Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
530 04df82f7 Leonidas Poulopoulos
531 d163b72b Leonidas Poulopoulos
532 04df82f7 Leonidas Poulopoulos
@login_required
533 c666e0f0 Leonidas Poulopoulos
@social_active_required
534 d163b72b Leonidas Poulopoulos
@never_cache
535 04df82f7 Leonidas Poulopoulos
def add_realm(request, realm_pk):
536 04df82f7 Leonidas Poulopoulos
    user = request.user
537 04df82f7 Leonidas Poulopoulos
    server = False
538 0f9fca26 Leonidas Poulopoulos
    realm = False
539 0f9fca26 Leonidas Poulopoulos
    edit = False
540 04df82f7 Leonidas Poulopoulos
    try:
541 04df82f7 Leonidas Poulopoulos
        profile = user.get_profile()
542 04df82f7 Leonidas Poulopoulos
        inst = profile.institution
543 7973b176 Leonidas Poulopoulos
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
544 04df82f7 Leonidas Poulopoulos
    except UserProfile.DoesNotExist:
545 244d3095 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
546 7973b176 Leonidas Poulopoulos
    try:
547 7973b176 Leonidas Poulopoulos
        instdetails = inst.institutiondetails
548 7973b176 Leonidas Poulopoulos
    except InstitutionDetails.DoesNotExist:
549 7973b176 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
550 c2cca19e Leonidas Poulopoulos
    if inst.ertype not in [1,3]:
551 fa2f119d Leonidas Poulopoulos
        messages.add_message(request, messages.ERROR, 'Cannot add/edit Realm. Your institution should be either IdP or IdP/SP')
552 fa2f119d Leonidas Poulopoulos
        return render_to_response('edumanage/realms_edit.html', { 'edit': edit },
553 fa2f119d Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
554 04df82f7 Leonidas Poulopoulos
    if request.method == "GET":
555 04df82f7 Leonidas Poulopoulos
556 04df82f7 Leonidas Poulopoulos
        # Determine add or edit
557 04df82f7 Leonidas Poulopoulos
        try:         
558 04df82f7 Leonidas Poulopoulos
            realm = InstRealm.objects.get(instid=inst, pk=realm_pk)
559 04df82f7 Leonidas Poulopoulos
            form = InstRealmForm(instance=realm)
560 04df82f7 Leonidas Poulopoulos
        except InstRealm.DoesNotExist:
561 04df82f7 Leonidas Poulopoulos
            form = InstRealmForm()
562 f3bca340 Leonidas Poulopoulos
            if realm_pk:
563 f3bca340 Leonidas Poulopoulos
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this realm')
564 f3bca340 Leonidas Poulopoulos
                return HttpResponseRedirect(reverse("realms"))
565 04df82f7 Leonidas Poulopoulos
        form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
566 41f67637 Leonidas Poulopoulos
        form.fields['proxyto'] = forms.ModelMultipleChoiceField(queryset=InstServer.objects.filter(pk__in=getInstServers(inst, True)))
567 0f9fca26 Leonidas Poulopoulos
        if realm:
568 0f9fca26 Leonidas Poulopoulos
            edit = True
569 0f9fca26 Leonidas Poulopoulos
        return render_to_response('edumanage/realms_edit.html', { 'form': form, 'edit': edit },
570 04df82f7 Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
571 04df82f7 Leonidas Poulopoulos
    elif request.method == 'POST':
572 04df82f7 Leonidas Poulopoulos
        request_data = request.POST.copy()
573 04df82f7 Leonidas Poulopoulos
        try:         
574 04df82f7 Leonidas Poulopoulos
            realm = InstRealm.objects.get(instid=inst, pk=realm_pk)
575 04df82f7 Leonidas Poulopoulos
            form = InstRealmForm(request_data, instance=realm)
576 04df82f7 Leonidas Poulopoulos
        except InstRealm.DoesNotExist:
577 04df82f7 Leonidas Poulopoulos
            form = InstRealmForm(request_data)
578 f3bca340 Leonidas Poulopoulos
            if realm_pk:
579 f3bca340 Leonidas Poulopoulos
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this realm')
580 f3bca340 Leonidas Poulopoulos
                return HttpResponseRedirect(reverse("realms")) 
581 04df82f7 Leonidas Poulopoulos
        if form.is_valid():
582 04df82f7 Leonidas Poulopoulos
            instserverf = form.save()
583 04df82f7 Leonidas Poulopoulos
            return HttpResponseRedirect(reverse("realms"))
584 04df82f7 Leonidas Poulopoulos
        else:
585 04df82f7 Leonidas Poulopoulos
            form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
586 41f67637 Leonidas Poulopoulos
            form.fields['proxyto'] = forms.ModelMultipleChoiceField(queryset=InstServer.objects.filter(pk__in=getInstServers(inst, True)))
587 0f9fca26 Leonidas Poulopoulos
        if realm:
588 0f9fca26 Leonidas Poulopoulos
            edit = True
589 0f9fca26 Leonidas Poulopoulos
        return render_to_response('edumanage/realms_edit.html', { 'institution': inst, 'form': form, 'edit': edit },
590 04df82f7 Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
591 04df82f7 Leonidas Poulopoulos
592 04df82f7 Leonidas Poulopoulos
593 04df82f7 Leonidas Poulopoulos
@login_required
594 c666e0f0 Leonidas Poulopoulos
@social_active_required
595 d163b72b Leonidas Poulopoulos
@never_cache
596 04df82f7 Leonidas Poulopoulos
def del_realm(request):
597 04df82f7 Leonidas Poulopoulos
    if request.method == 'GET':
598 04df82f7 Leonidas Poulopoulos
        user = request.user
599 04df82f7 Leonidas Poulopoulos
        req_data = request.GET.copy()
600 04df82f7 Leonidas Poulopoulos
        realm_pk = req_data['realm_pk']
601 244d3095 Leonidas Poulopoulos
        try:
602 244d3095 Leonidas Poulopoulos
            profile = user.get_profile()
603 244d3095 Leonidas Poulopoulos
            institution = profile.institution
604 244d3095 Leonidas Poulopoulos
        except UserProfile.DoesNotExist:
605 244d3095 Leonidas Poulopoulos
            resp['error'] = "Not enough rights"
606 244d3095 Leonidas Poulopoulos
            return HttpResponse(json.dumps(resp), mimetype='application/json')
607 04df82f7 Leonidas Poulopoulos
        resp = {}
608 04df82f7 Leonidas Poulopoulos
        try:
609 04df82f7 Leonidas Poulopoulos
            realm = InstRealm.objects.get(instid=institution, pk=realm_pk)
610 04df82f7 Leonidas Poulopoulos
        except InstRealm.DoesNotExist:
611 04df82f7 Leonidas Poulopoulos
            resp['error'] = "Could not get realm or you have no rights to delete"
612 04df82f7 Leonidas Poulopoulos
            return HttpResponse(json.dumps(resp), mimetype='application/json')
613 04df82f7 Leonidas Poulopoulos
        try:
614 04df82f7 Leonidas Poulopoulos
            realm.delete()
615 04df82f7 Leonidas Poulopoulos
        except:
616 04df82f7 Leonidas Poulopoulos
            resp['error'] = "Could not delete realm"
617 04df82f7 Leonidas Poulopoulos
            return HttpResponse(json.dumps(resp), mimetype='application/json')
618 04df82f7 Leonidas Poulopoulos
        resp['success'] = "Realm successfully deleted"
619 04df82f7 Leonidas Poulopoulos
        return HttpResponse(json.dumps(resp), mimetype='application/json')
620 04df82f7 Leonidas Poulopoulos
621 04df82f7 Leonidas Poulopoulos
622 c2b3014a Leonidas Poulopoulos
@login_required
623 c666e0f0 Leonidas Poulopoulos
@social_active_required
624 d163b72b Leonidas Poulopoulos
@never_cache
625 c2b3014a Leonidas Poulopoulos
def contacts(request):
626 c2b3014a Leonidas Poulopoulos
    user = request.user
627 c2b3014a Leonidas Poulopoulos
    servers = False
628 c2b3014a Leonidas Poulopoulos
    instcontacts = []
629 c2b3014a Leonidas Poulopoulos
    try:
630 c2b3014a Leonidas Poulopoulos
        profile = user.get_profile()
631 c2b3014a Leonidas Poulopoulos
        inst = profile.institution
632 7973b176 Leonidas Poulopoulos
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
633 c2b3014a Leonidas Poulopoulos
    except UserProfile.DoesNotExist:
634 244d3095 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
635 7973b176 Leonidas Poulopoulos
    try:
636 7973b176 Leonidas Poulopoulos
        instdetails = inst.institutiondetails
637 7973b176 Leonidas Poulopoulos
    except InstitutionDetails.DoesNotExist:
638 7973b176 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
639 c2b3014a Leonidas Poulopoulos
    if inst:
640 c2b3014a Leonidas Poulopoulos
        instcontacts.extend([x.contact.pk for x in InstitutionContactPool.objects.filter(institution=inst)])
641 c2b3014a Leonidas Poulopoulos
        contacts = Contact.objects.filter(pk__in=instcontacts)
642 c2b3014a Leonidas Poulopoulos
    return render_to_response('edumanage/contacts.html', { 'contacts': contacts},
643 c2b3014a Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
644 c2b3014a Leonidas Poulopoulos
645 d163b72b Leonidas Poulopoulos
646 c2b3014a Leonidas Poulopoulos
@login_required
647 c666e0f0 Leonidas Poulopoulos
@social_active_required
648 d163b72b Leonidas Poulopoulos
@never_cache
649 c2b3014a Leonidas Poulopoulos
def add_contact(request, contact_pk):
650 c2b3014a Leonidas Poulopoulos
    user = request.user
651 c2b3014a Leonidas Poulopoulos
    server = False
652 0f9fca26 Leonidas Poulopoulos
    edit = False
653 0f9fca26 Leonidas Poulopoulos
    contact = False
654 c2b3014a Leonidas Poulopoulos
    try:
655 c2b3014a Leonidas Poulopoulos
        profile = user.get_profile()
656 c2b3014a Leonidas Poulopoulos
        inst = profile.institution
657 7973b176 Leonidas Poulopoulos
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
658 c2b3014a Leonidas Poulopoulos
    except UserProfile.DoesNotExist:
659 7973b176 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
660 7973b176 Leonidas Poulopoulos
    try:
661 7973b176 Leonidas Poulopoulos
        instdetails = inst.institutiondetails
662 7973b176 Leonidas Poulopoulos
    except InstitutionDetails.DoesNotExist:
663 244d3095 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
664 c2b3014a Leonidas Poulopoulos
    if request.method == "GET":
665 c2b3014a Leonidas Poulopoulos
666 c2b3014a Leonidas Poulopoulos
        # Determine add or edit
667 c2b3014a Leonidas Poulopoulos
        try:         
668 c2b3014a Leonidas Poulopoulos
            contactinst = InstitutionContactPool.objects.get(institution=inst, contact__pk=contact_pk)
669 c2b3014a Leonidas Poulopoulos
            contact = contactinst.contact
670 c2b3014a Leonidas Poulopoulos
            form = ContactForm(instance=contact)
671 c2b3014a Leonidas Poulopoulos
        except InstitutionContactPool.DoesNotExist:
672 c2b3014a Leonidas Poulopoulos
            form = ContactForm()
673 f3bca340 Leonidas Poulopoulos
            if contact_pk:
674 f3bca340 Leonidas Poulopoulos
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this contact')
675 f3bca340 Leonidas Poulopoulos
                return HttpResponseRedirect(reverse("contacts"))
676 0f9fca26 Leonidas Poulopoulos
        if contact:
677 0f9fca26 Leonidas Poulopoulos
            edit = True
678 0f9fca26 Leonidas Poulopoulos
        return render_to_response('edumanage/contacts_edit.html', { 'form': form, "edit" : edit},
679 c2b3014a Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
680 c2b3014a Leonidas Poulopoulos
    elif request.method == 'POST':
681 c2b3014a Leonidas Poulopoulos
        request_data = request.POST.copy()
682 c2b3014a Leonidas Poulopoulos
        try:         
683 c2b3014a Leonidas Poulopoulos
            contactinst = InstitutionContactPool.objects.get(institution=inst, contact__pk=contact_pk)
684 c2b3014a Leonidas Poulopoulos
            contact = contactinst.contact
685 c2b3014a Leonidas Poulopoulos
            form = ContactForm(request_data, instance=contact)
686 c2b3014a Leonidas Poulopoulos
        except InstitutionContactPool.DoesNotExist:
687 c2b3014a Leonidas Poulopoulos
            form = ContactForm(request_data)
688 f3bca340 Leonidas Poulopoulos
            if contact_pk:
689 f3bca340 Leonidas Poulopoulos
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this contact')
690 f3bca340 Leonidas Poulopoulos
                return HttpResponseRedirect(reverse("contacts"))
691 c2b3014a Leonidas Poulopoulos
        
692 c2b3014a Leonidas Poulopoulos
        if form.is_valid():
693 c2b3014a Leonidas Poulopoulos
            contact = form.save()
694 c2b3014a Leonidas Poulopoulos
            instContPool, created = InstitutionContactPool.objects.get_or_create(contact=contact, institution=inst)
695 c2b3014a Leonidas Poulopoulos
            instContPool.save()
696 c2b3014a Leonidas Poulopoulos
            return HttpResponseRedirect(reverse("contacts"))
697 0f9fca26 Leonidas Poulopoulos
        if contact:
698 0f9fca26 Leonidas Poulopoulos
            edit = True
699 0f9fca26 Leonidas Poulopoulos
        return render_to_response('edumanage/contacts_edit.html', { 'form': form, "edit": edit},
700 c2b3014a Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
701 c2b3014a Leonidas Poulopoulos
702 c2b3014a Leonidas Poulopoulos
703 c2b3014a Leonidas Poulopoulos
@login_required
704 c666e0f0 Leonidas Poulopoulos
@social_active_required
705 d163b72b Leonidas Poulopoulos
@never_cache
706 c2b3014a Leonidas Poulopoulos
def del_contact(request):
707 c2b3014a Leonidas Poulopoulos
    if request.method == 'GET':
708 c2b3014a Leonidas Poulopoulos
        user = request.user
709 c2b3014a Leonidas Poulopoulos
        req_data = request.GET.copy()
710 c2b3014a Leonidas Poulopoulos
        contact_pk = req_data['contact_pk']
711 244d3095 Leonidas Poulopoulos
        try:
712 244d3095 Leonidas Poulopoulos
            profile = user.get_profile()
713 244d3095 Leonidas Poulopoulos
            institution = profile.institution
714 244d3095 Leonidas Poulopoulos
        except UserProfile.DoesNotExist:
715 244d3095 Leonidas Poulopoulos
            resp['error'] = "Could not delete contact. Not enough rights"
716 244d3095 Leonidas Poulopoulos
            return HttpResponse(json.dumps(resp), mimetype='application/json')
717 c2b3014a Leonidas Poulopoulos
        resp = {}
718 c2b3014a Leonidas Poulopoulos
        try:
719 c2b3014a Leonidas Poulopoulos
            contactinst = InstitutionContactPool.objects.get(institution=institution, contact__pk=contact_pk)
720 c2b3014a Leonidas Poulopoulos
            contact = contactinst.contact
721 c2b3014a Leonidas Poulopoulos
        except InstitutionContactPool.DoesNotExist:
722 c2b3014a Leonidas Poulopoulos
            resp['error'] = "Could not get contact or you have no rights to delete"
723 c2b3014a Leonidas Poulopoulos
            return HttpResponse(json.dumps(resp), mimetype='application/json')
724 c2b3014a Leonidas Poulopoulos
        try:
725 c2b3014a Leonidas Poulopoulos
            for service in ServiceLoc.objects.filter(institutionid=institution):
726 c2b3014a Leonidas Poulopoulos
                if (contact in service.contact.all() and len(service.contact.all()) == 1):
727 c2b3014a Leonidas Poulopoulos
                    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")
728 c2b3014a Leonidas Poulopoulos
                    return HttpResponse(json.dumps(resp), mimetype='application/json')
729 c2b3014a Leonidas Poulopoulos
            if (contact in institution.institutiondetails.contact.all() and len(institution.institutiondetails.contact.all()) == 1):
730 c2b3014a Leonidas Poulopoulos
                    resp['error'] = "Could not delete contact. It is the only contact your institution.<br>Fix it and try again"
731 c2b3014a Leonidas Poulopoulos
                    return HttpResponse(json.dumps(resp), mimetype='application/json')
732 c2b3014a Leonidas Poulopoulos
            contact.delete()
733 c2b3014a Leonidas Poulopoulos
        except Exception:
734 c2b3014a Leonidas Poulopoulos
            resp['error'] = "Could not delete contact"
735 c2b3014a Leonidas Poulopoulos
            return HttpResponse(json.dumps(resp), mimetype='application/json')
736 c2b3014a Leonidas Poulopoulos
        resp['success'] = "Contact successfully deleted"
737 c2b3014a Leonidas Poulopoulos
        return HttpResponse(json.dumps(resp), mimetype='application/json')
738 d163b72b Leonidas Poulopoulos
739 d163b72b Leonidas Poulopoulos
740 7973b176 Leonidas Poulopoulos
@login_required
741 c666e0f0 Leonidas Poulopoulos
@social_active_required
742 d163b72b Leonidas Poulopoulos
@never_cache
743 9db05e62 Leonidas Poulopoulos
def instrealmmon(request):
744 9db05e62 Leonidas Poulopoulos
    user = request.user
745 9db05e62 Leonidas Poulopoulos
    servers = False
746 9db05e62 Leonidas Poulopoulos
    instcontacts = []
747 9db05e62 Leonidas Poulopoulos
    try:
748 9db05e62 Leonidas Poulopoulos
        profile = user.get_profile()
749 9db05e62 Leonidas Poulopoulos
        inst = profile.institution
750 9db05e62 Leonidas Poulopoulos
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
751 9db05e62 Leonidas Poulopoulos
    except UserProfile.DoesNotExist:
752 9db05e62 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
753 9db05e62 Leonidas Poulopoulos
    try:
754 9db05e62 Leonidas Poulopoulos
        instdetails = inst.institutiondetails
755 9db05e62 Leonidas Poulopoulos
    except InstitutionDetails.DoesNotExist:
756 9db05e62 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
757 9db05e62 Leonidas Poulopoulos
    if inst:
758 9db05e62 Leonidas Poulopoulos
        instrealmmons = InstRealmMon.objects.filter(realm__instid=inst)
759 9db05e62 Leonidas Poulopoulos
    return render_to_response('edumanage/instrealmmons.html', { 'realms': instrealmmons},
760 9db05e62 Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
761 9db05e62 Leonidas Poulopoulos
762 9db05e62 Leonidas Poulopoulos
@login_required
763 c666e0f0 Leonidas Poulopoulos
@social_active_required
764 9db05e62 Leonidas Poulopoulos
@never_cache
765 9db05e62 Leonidas Poulopoulos
def add_instrealmmon(request, instrealmmon_pk):
766 9db05e62 Leonidas Poulopoulos
    user = request.user
767 9db05e62 Leonidas Poulopoulos
    instrealmmon = False
768 9db05e62 Leonidas Poulopoulos
    edit = False
769 9db05e62 Leonidas Poulopoulos
    try:
770 9db05e62 Leonidas Poulopoulos
        profile = user.get_profile()
771 9db05e62 Leonidas Poulopoulos
        inst = profile.institution
772 9db05e62 Leonidas Poulopoulos
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
773 9db05e62 Leonidas Poulopoulos
    except UserProfile.DoesNotExist:
774 9db05e62 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
775 9db05e62 Leonidas Poulopoulos
    try:
776 9db05e62 Leonidas Poulopoulos
        instdetails = inst.institutiondetails
777 9db05e62 Leonidas Poulopoulos
    except InstitutionDetails.DoesNotExist:
778 9db05e62 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
779 9db05e62 Leonidas Poulopoulos
    if request.method == "GET":
780 9db05e62 Leonidas Poulopoulos
        # Determine add or edit
781 9db05e62 Leonidas Poulopoulos
        try:         
782 9db05e62 Leonidas Poulopoulos
            instrealmmon = InstRealmMon.objects.get(pk=instrealmmon_pk, realm__instid=inst)
783 9db05e62 Leonidas Poulopoulos
            form = InstRealmMonForm(instance=instrealmmon)
784 9db05e62 Leonidas Poulopoulos
        except InstRealmMon.DoesNotExist:
785 9db05e62 Leonidas Poulopoulos
            form = InstRealmMonForm()
786 f3bca340 Leonidas Poulopoulos
            if instrealmmon_pk:
787 f3bca340 Leonidas Poulopoulos
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this Monitoring Realm')
788 f3bca340 Leonidas Poulopoulos
                return HttpResponseRedirect(reverse("instrealmmon"))
789 9db05e62 Leonidas Poulopoulos
        if instrealmmon:
790 9db05e62 Leonidas Poulopoulos
            edit = True
791 9db05e62 Leonidas Poulopoulos
        form.fields['realm'] = forms.ModelChoiceField(queryset=InstRealm.objects.filter(instid=inst.pk).exclude(realm__startswith="*"), empty_label=None)
792 9db05e62 Leonidas Poulopoulos
        return render_to_response('edumanage/instrealmmon_edit.html', { 'form': form, "edit" : edit},
793 9db05e62 Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
794 9db05e62 Leonidas Poulopoulos
    elif request.method == 'POST':
795 9db05e62 Leonidas Poulopoulos
        request_data = request.POST.copy()
796 9db05e62 Leonidas Poulopoulos
        try:         
797 9db05e62 Leonidas Poulopoulos
            instrealmmon = InstRealmMon.objects.get(pk=instrealmmon_pk, realm__instid=inst)
798 9db05e62 Leonidas Poulopoulos
            form = InstRealmMonForm(request_data, instance=instrealmmon)
799 9db05e62 Leonidas Poulopoulos
        except InstRealmMon.DoesNotExist:
800 9db05e62 Leonidas Poulopoulos
            form = InstRealmMonForm(request_data)
801 f3bca340 Leonidas Poulopoulos
            if instrealmmon_pk:
802 f3bca340 Leonidas Poulopoulos
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this Monitoring Realm')
803 f3bca340 Leonidas Poulopoulos
                return HttpResponseRedirect(reverse("instrealmmon"))
804 9db05e62 Leonidas Poulopoulos
        if form.is_valid():
805 9db05e62 Leonidas Poulopoulos
            instrealmmonobj = form.save()
806 9db05e62 Leonidas Poulopoulos
            return HttpResponseRedirect(reverse("instrealmmon"))
807 9db05e62 Leonidas Poulopoulos
        if instrealmmon:
808 9db05e62 Leonidas Poulopoulos
            edit = True
809 450099e1 Leonidas Poulopoulos
        form.fields['realm'] = forms.ModelChoiceField(queryset=InstRealm.objects.filter(instid=inst.pk).exclude(realm__startswith="*"), empty_label=None)
810 9db05e62 Leonidas Poulopoulos
        return render_to_response('edumanage/instrealmmon_edit.html', { 'form': form, "edit": edit},
811 9db05e62 Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
812 9db05e62 Leonidas Poulopoulos
813 450099e1 Leonidas Poulopoulos
@login_required
814 c666e0f0 Leonidas Poulopoulos
@social_active_required
815 450099e1 Leonidas Poulopoulos
@never_cache
816 450099e1 Leonidas Poulopoulos
def del_instrealmmon(request):
817 450099e1 Leonidas Poulopoulos
    if request.method == 'GET':
818 450099e1 Leonidas Poulopoulos
        user = request.user
819 450099e1 Leonidas Poulopoulos
        req_data = request.GET.copy()
820 450099e1 Leonidas Poulopoulos
        instrealmmon_pk = req_data['instrealmmon_pk']
821 450099e1 Leonidas Poulopoulos
        try:
822 450099e1 Leonidas Poulopoulos
            profile = user.get_profile()
823 450099e1 Leonidas Poulopoulos
            institution = profile.institution
824 450099e1 Leonidas Poulopoulos
        except UserProfile.DoesNotExist:
825 450099e1 Leonidas Poulopoulos
            resp['error'] = "Could not delete monitored realm. Not enough rights"
826 450099e1 Leonidas Poulopoulos
            return HttpResponse(json.dumps(resp), mimetype='application/json')
827 450099e1 Leonidas Poulopoulos
        resp = {}
828 450099e1 Leonidas Poulopoulos
        try:
829 450099e1 Leonidas Poulopoulos
            instrealmmon = InstRealmMon.objects.get(pk=instrealmmon_pk, realm__instid=institution)
830 450099e1 Leonidas Poulopoulos
            instrealmmon.delete()
831 450099e1 Leonidas Poulopoulos
        except InstRealmMon.DoesNotExist:
832 450099e1 Leonidas Poulopoulos
            resp['error'] = "Could not get monitored realm or you have no rights to delete"
833 450099e1 Leonidas Poulopoulos
            return HttpResponse(json.dumps(resp), mimetype='application/json')
834 450099e1 Leonidas Poulopoulos
        resp['success'] = "Contact successfully deleted"
835 450099e1 Leonidas Poulopoulos
        return HttpResponse(json.dumps(resp), mimetype='application/json')
836 9db05e62 Leonidas Poulopoulos
837 9db05e62 Leonidas Poulopoulos
@login_required
838 c666e0f0 Leonidas Poulopoulos
@social_active_required
839 9db05e62 Leonidas Poulopoulos
@never_cache
840 9db05e62 Leonidas Poulopoulos
def add_monlocauthpar(request, instrealmmon_pk, monlocauthpar_pk):
841 9db05e62 Leonidas Poulopoulos
    user = request.user
842 9db05e62 Leonidas Poulopoulos
    monlocauthpar = False
843 9db05e62 Leonidas Poulopoulos
    edit = False
844 9db05e62 Leonidas Poulopoulos
    try:
845 9db05e62 Leonidas Poulopoulos
        profile = user.get_profile()
846 9db05e62 Leonidas Poulopoulos
        inst = profile.institution
847 9db05e62 Leonidas Poulopoulos
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
848 9db05e62 Leonidas Poulopoulos
    except UserProfile.DoesNotExist:
849 9db05e62 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
850 9db05e62 Leonidas Poulopoulos
    try:
851 9db05e62 Leonidas Poulopoulos
        instdetails = inst.institutiondetails
852 9db05e62 Leonidas Poulopoulos
    except InstitutionDetails.DoesNotExist:
853 9db05e62 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
854 9db05e62 Leonidas Poulopoulos
    if request.method == "GET":
855 9db05e62 Leonidas Poulopoulos
        # Determine add or edit
856 9db05e62 Leonidas Poulopoulos
        try:
857 9db05e62 Leonidas Poulopoulos
            instrealmmon = InstRealmMon.objects.get(pk=instrealmmon_pk, realm__instid=inst)
858 9db05e62 Leonidas Poulopoulos
            monlocauthpar = MonLocalAuthnParam.objects.get(pk=monlocauthpar_pk, instrealmmonid__realm__instid=inst)
859 9db05e62 Leonidas Poulopoulos
            form = MonLocalAuthnParamForm(instance=monlocauthpar)
860 9db05e62 Leonidas Poulopoulos
        except MonLocalAuthnParam.DoesNotExist:
861 9db05e62 Leonidas Poulopoulos
            form = MonLocalAuthnParamForm()
862 f3bca340 Leonidas Poulopoulos
            if monlocauthpar_pk:
863 f3bca340 Leonidas Poulopoulos
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this Monitoring Realm Parameters')
864 f3bca340 Leonidas Poulopoulos
                return HttpResponseRedirect(reverse("instrealmmon"))
865 9db05e62 Leonidas Poulopoulos
        except InstRealmMon.DoesNotExist:
866 f3bca340 Leonidas Poulopoulos
            if instrealmmon_pk:
867 f3bca340 Leonidas Poulopoulos
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this Monitoring Realm Parameters')
868 f3bca340 Leonidas Poulopoulos
            return HttpResponseRedirect(reverse("instrealmmon"))
869 9db05e62 Leonidas Poulopoulos
        if monlocauthpar:
870 9db05e62 Leonidas Poulopoulos
            edit = True
871 9db05e62 Leonidas Poulopoulos
        form.fields['instrealmmonid'] = forms.ModelChoiceField(queryset=InstRealmMon.objects.filter(pk=instrealmmon.pk), empty_label=None)
872 9db05e62 Leonidas Poulopoulos
        return render_to_response('edumanage/monlocauthpar_edit.html', { 'form': form, "edit" : edit, "realm":instrealmmon },
873 9db05e62 Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
874 9db05e62 Leonidas Poulopoulos
    elif request.method == 'POST':
875 9db05e62 Leonidas Poulopoulos
        request_data = request.POST.copy()
876 9db05e62 Leonidas Poulopoulos
        try:         
877 9db05e62 Leonidas Poulopoulos
            instrealmmon = InstRealmMon.objects.get(pk=instrealmmon_pk, realm__instid=inst)
878 9db05e62 Leonidas Poulopoulos
            monlocauthpar = MonLocalAuthnParam.objects.get(pk=monlocauthpar_pk, instrealmmonid__realm__instid=inst)
879 9db05e62 Leonidas Poulopoulos
            form = MonLocalAuthnParamForm(request_data, instance=monlocauthpar)
880 9db05e62 Leonidas Poulopoulos
        except MonLocalAuthnParam.DoesNotExist:
881 9db05e62 Leonidas Poulopoulos
            form = MonLocalAuthnParamForm(request_data)
882 f3bca340 Leonidas Poulopoulos
            if monlocauthpar_pk:
883 f3bca340 Leonidas Poulopoulos
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this Monitoring Realm Parameters')
884 f3bca340 Leonidas Poulopoulos
                return HttpResponseRedirect(reverse("instrealmmon"))
885 9db05e62 Leonidas Poulopoulos
        except InstRealmMon.DoesNotExist:
886 f3bca340 Leonidas Poulopoulos
            if instrealmmon_pk:
887 f3bca340 Leonidas Poulopoulos
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this Monitoring Realm Parameters')
888 f3bca340 Leonidas Poulopoulos
            return HttpResponseRedirect(reverse("instrealmmon"))
889 9db05e62 Leonidas Poulopoulos
        if form.is_valid():
890 9db05e62 Leonidas Poulopoulos
            monlocauthparobj = form.save()
891 9db05e62 Leonidas Poulopoulos
            return HttpResponseRedirect(reverse("instrealmmon"))
892 9db05e62 Leonidas Poulopoulos
        if monlocauthpar:
893 9db05e62 Leonidas Poulopoulos
            edit = True
894 9db05e62 Leonidas Poulopoulos
        form.fields['instrealmmonid'] = forms.ModelChoiceField(queryset=InstRealmMon.objects.filter(pk=instrealmmon.pk), empty_label=None)
895 9db05e62 Leonidas Poulopoulos
        return render_to_response('edumanage/monlocauthpar_edit.html', { 'form': form, "edit": edit, "realm":instrealmmon},
896 9db05e62 Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
897 9db05e62 Leonidas Poulopoulos
898 9db05e62 Leonidas Poulopoulos
@login_required
899 c666e0f0 Leonidas Poulopoulos
@social_active_required
900 9db05e62 Leonidas Poulopoulos
@never_cache
901 450099e1 Leonidas Poulopoulos
def del_monlocauthpar(request):
902 450099e1 Leonidas Poulopoulos
    if request.method == 'GET':
903 450099e1 Leonidas Poulopoulos
        user = request.user
904 450099e1 Leonidas Poulopoulos
        req_data = request.GET.copy()
905 450099e1 Leonidas Poulopoulos
        monlocauthpar_pk = req_data['monlocauthpar_pk']
906 450099e1 Leonidas Poulopoulos
        try:
907 450099e1 Leonidas Poulopoulos
            profile = user.get_profile()
908 450099e1 Leonidas Poulopoulos
            institution = profile.institution
909 450099e1 Leonidas Poulopoulos
        except UserProfile.DoesNotExist:
910 450099e1 Leonidas Poulopoulos
            resp['error'] = "Could not delete realm monitoring parameters. Not enough rights"
911 450099e1 Leonidas Poulopoulos
            return HttpResponse(json.dumps(resp), mimetype='application/json')
912 450099e1 Leonidas Poulopoulos
        resp = {}
913 450099e1 Leonidas Poulopoulos
        try:
914 450099e1 Leonidas Poulopoulos
            monlocauthpar = MonLocalAuthnParam.objects.get(pk=monlocauthpar_pk, instrealmmonid__realm__instid=institution)
915 450099e1 Leonidas Poulopoulos
            monlocauthpar.delete()
916 450099e1 Leonidas Poulopoulos
        except MonLocalAuthnParam.DoesNotExist:
917 450099e1 Leonidas Poulopoulos
            resp['error'] = "Could not get realm monitoring parameters or you have no rights to delete"
918 450099e1 Leonidas Poulopoulos
            return HttpResponse(json.dumps(resp), mimetype='application/json')
919 450099e1 Leonidas Poulopoulos
        resp['success'] = "Contact successfully deleted"
920 450099e1 Leonidas Poulopoulos
        return HttpResponse(json.dumps(resp), mimetype='application/json')
921 450099e1 Leonidas Poulopoulos
922 450099e1 Leonidas Poulopoulos
@login_required
923 c666e0f0 Leonidas Poulopoulos
@social_active_required
924 450099e1 Leonidas Poulopoulos
@never_cache
925 7973b176 Leonidas Poulopoulos
def adduser(request):
926 7973b176 Leonidas Poulopoulos
    user = request.user
927 7973b176 Leonidas Poulopoulos
    try:
928 7973b176 Leonidas Poulopoulos
        profile = user.get_profile()
929 7973b176 Leonidas Poulopoulos
        inst = profile.institution
930 7973b176 Leonidas Poulopoulos
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
931 7973b176 Leonidas Poulopoulos
    except UserProfile.DoesNotExist:
932 7973b176 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("manage"))
933 c2b3014a Leonidas Poulopoulos
934 7973b176 Leonidas Poulopoulos
    if request.method == "GET":
935 7973b176 Leonidas Poulopoulos
        form = ContactForm()
936 7973b176 Leonidas Poulopoulos
        return render_to_response('edumanage/add_user.html', { 'form' : form },
937 7973b176 Leonidas Poulopoulos
                                  context_instance=RequestContext(request, base_response(request)))
938 7973b176 Leonidas Poulopoulos
    elif request.method == 'POST':
939 7973b176 Leonidas Poulopoulos
        request_data = request.POST.copy()
940 7973b176 Leonidas Poulopoulos
        form = ContactForm(request_data)
941 7973b176 Leonidas Poulopoulos
        if form.is_valid():
942 7973b176 Leonidas Poulopoulos
            contact = form.save()
943 7973b176 Leonidas Poulopoulos
            instContPool = InstitutionContactPool(contact=contact, institution=inst)
944 7973b176 Leonidas Poulopoulos
            instContPool.save()
945 7973b176 Leonidas Poulopoulos
            response_data = {}
946 7973b176 Leonidas Poulopoulos
            response_data['value'] = "%s" %contact.pk
947 7973b176 Leonidas Poulopoulos
            response_data['text'] = "%s" %contact
948 7973b176 Leonidas Poulopoulos
            return HttpResponse(json.dumps(response_data), mimetype='application/json')
949 7973b176 Leonidas Poulopoulos
        else:
950 7973b176 Leonidas Poulopoulos
            return render_to_response('edumanage/add_user.html', {'form': form,},
951 7973b176 Leonidas Poulopoulos
                                      context_instance=RequestContext(request, base_response(request)))
952 c2b3014a Leonidas Poulopoulos
953 d163b72b Leonidas Poulopoulos
954 04df82f7 Leonidas Poulopoulos
@login_required
955 c666e0f0 Leonidas Poulopoulos
@social_active_required
956 af9d484b Leonidas Poulopoulos
def base_response(request):
957 af9d484b Leonidas Poulopoulos
    user = request.user
958 af9d484b Leonidas Poulopoulos
    inst = []
959 af9d484b Leonidas Poulopoulos
    server = []
960 af9d484b Leonidas Poulopoulos
    services = []
961 04df82f7 Leonidas Poulopoulos
    instrealms = []
962 c2b3014a Leonidas Poulopoulos
    instcontacts = []
963 c2b3014a Leonidas Poulopoulos
    contacts = []
964 244d3095 Leonidas Poulopoulos
    institution = False
965 244d3095 Leonidas Poulopoulos
    institution_exists = False
966 af9d484b Leonidas Poulopoulos
    try:
967 af9d484b Leonidas Poulopoulos
        profile = user.get_profile()
968 af9d484b Leonidas Poulopoulos
        institution = profile.institution
969 244d3095 Leonidas Poulopoulos
        institution_exists = True
970 244d3095 Leonidas Poulopoulos
    except UserProfile.DoesNotExist:
971 244d3095 Leonidas Poulopoulos
        institution_exists = False
972 244d3095 Leonidas Poulopoulos
    try:
973 af9d484b Leonidas Poulopoulos
        inst.append(institution)
974 af9d484b Leonidas Poulopoulos
        server = InstServer.objects.filter(instid=institution)
975 af9d484b Leonidas Poulopoulos
        services = ServiceLoc.objects.filter(institutionid=institution)
976 04df82f7 Leonidas Poulopoulos
        instrealms = InstRealm.objects.filter(instid=institution)
977 c2b3014a Leonidas Poulopoulos
        instcontacts.extend([x.contact.pk for x in InstitutionContactPool.objects.filter(institution=institution)])
978 c2b3014a Leonidas Poulopoulos
        contacts = Contact.objects.filter(pk__in=instcontacts)
979 9db05e62 Leonidas Poulopoulos
        instrealmmons = InstRealmMon.objects.filter(realm__instid=institution)
980 244d3095 Leonidas Poulopoulos
    except:
981 af9d484b Leonidas Poulopoulos
        pass
982 7973b176 Leonidas Poulopoulos
    try:
983 7973b176 Leonidas Poulopoulos
        instututiondetails = institution.institutiondetails
984 7973b176 Leonidas Poulopoulos
    except:
985 7973b176 Leonidas Poulopoulos
        instututiondetails = False
986 af9d484b Leonidas Poulopoulos
    return { 
987 af9d484b Leonidas Poulopoulos
            'inst_num': len(inst),
988 af9d484b Leonidas Poulopoulos
            'servers_num': len(server),
989 af9d484b Leonidas Poulopoulos
            'services_num': len(services),
990 04df82f7 Leonidas Poulopoulos
            'realms_num': len(instrealms),
991 c2b3014a Leonidas Poulopoulos
            'contacts_num': len(contacts),
992 9db05e62 Leonidas Poulopoulos
            'monrealms_num': len(instrealmmons),
993 7973b176 Leonidas Poulopoulos
            'institution': institution,
994 7973b176 Leonidas Poulopoulos
            'institutiondetails': instututiondetails,
995 244d3095 Leonidas Poulopoulos
            'institution_exists': institution_exists,
996 af9d484b Leonidas Poulopoulos
            
997 af9d484b Leonidas Poulopoulos
        }
998 af9d484b Leonidas Poulopoulos
999 7973b176 Leonidas Poulopoulos
1000 2398cbad Leonidas Poulopoulos
@login_required
1001 c666e0f0 Leonidas Poulopoulos
@social_active_required
1002 d163b72b Leonidas Poulopoulos
@never_cache
1003 7973b176 Leonidas Poulopoulos
def get_service_points(request):
1004 7973b176 Leonidas Poulopoulos
    if request.method == "GET":
1005 2398cbad Leonidas Poulopoulos
        user = request.user
1006 244d3095 Leonidas Poulopoulos
        try:
1007 244d3095 Leonidas Poulopoulos
            profile = user.get_profile()
1008 7973b176 Leonidas Poulopoulos
            inst = profile.institution
1009 244d3095 Leonidas Poulopoulos
        except UserProfile.DoesNotExist:
1010 7973b176 Leonidas Poulopoulos
            inst = False
1011 7973b176 Leonidas Poulopoulos
            return HttpResponseNotFound('<h1>Something went really wrong</h1>')
1012 7973b176 Leonidas Poulopoulos
        servicelocs = ServiceLoc.objects.filter(institutionid=inst)
1013 7973b176 Leonidas Poulopoulos
        
1014 7973b176 Leonidas Poulopoulos
        locs = []
1015 7973b176 Leonidas Poulopoulos
        for sl in servicelocs:
1016 7973b176 Leonidas Poulopoulos
            response_location = {}
1017 7973b176 Leonidas Poulopoulos
            response_location['lat'] = u"%s"%sl.latitude
1018 7973b176 Leonidas Poulopoulos
            response_location['lng'] = u"%s"%sl.longitude
1019 7973b176 Leonidas Poulopoulos
            response_location['address'] = u"%s<br>%s"%(sl.address_street, sl.address_city)
1020 27d6f3e2 Leonidas Poulopoulos
            if len(sl.enc_level[0]) != 0:
1021 27d6f3e2 Leonidas Poulopoulos
                response_location['enc'] = u"%s"%(','.join(sl.enc_level))
1022 27d6f3e2 Leonidas Poulopoulos
            else:
1023 27d6f3e2 Leonidas Poulopoulos
                response_location['enc'] = u"-"
1024 7973b176 Leonidas Poulopoulos
            response_location['AP_no'] = u"%s"%(sl.AP_no)
1025 7973b176 Leonidas Poulopoulos
            response_location['name'] = sl.loc_name.get(lang='en').name
1026 7973b176 Leonidas Poulopoulos
            response_location['port_restrict'] = u"%s"%(sl.port_restrict)
1027 7973b176 Leonidas Poulopoulos
            response_location['transp_proxy'] = u"%s"%(sl.transp_proxy)
1028 7973b176 Leonidas Poulopoulos
            response_location['IPv6'] = u"%s"%(sl.IPv6)
1029 7973b176 Leonidas Poulopoulos
            response_location['NAT'] = u"%s"%(sl.NAT)
1030 7973b176 Leonidas Poulopoulos
            response_location['wired'] = u"%s"%(sl.wired)
1031 7973b176 Leonidas Poulopoulos
            response_location['SSID'] = u"%s"%(sl.SSID)
1032 7973b176 Leonidas Poulopoulos
            response_location['key'] = u"%s"%sl.pk
1033 7973b176 Leonidas Poulopoulos
            locs.append(response_location)
1034 7973b176 Leonidas Poulopoulos
        return HttpResponse(json.dumps(locs), mimetype='application/json')
1035 7973b176 Leonidas Poulopoulos
    else:
1036 7973b176 Leonidas Poulopoulos
       return HttpResponseNotFound('<h1>Something went really wrong</h1>')
1037 7973b176 Leonidas Poulopoulos
1038 d163b72b Leonidas Poulopoulos
@never_cache
1039 0f8d1e77 Leonidas Poulopoulos
def overview(request):
1040 0f8d1e77 Leonidas Poulopoulos
    user = request.user
1041 0f8d1e77 Leonidas Poulopoulos
    if user.is_authenticated():
1042 0f8d1e77 Leonidas Poulopoulos
        if user.has_perm('accounts.overview'):
1043 0f8d1e77 Leonidas Poulopoulos
            users = User.objects.all()
1044 0f8d1e77 Leonidas Poulopoulos
            institutions = Institution.objects.all()
1045 0f8d1e77 Leonidas Poulopoulos
            return render_to_response('overview/index.html', {'users': users, 'institutions': institutions},
1046 0f8d1e77 Leonidas Poulopoulos
                                  context_instance=RequestContext(request))
1047 0f8d1e77 Leonidas Poulopoulos
        else:
1048 0f8d1e77 Leonidas Poulopoulos
            violation=True
1049 0f8d1e77 Leonidas Poulopoulos
            return render_to_response('overview/index.html', {'violation': violation},
1050 0f8d1e77 Leonidas Poulopoulos
                                  context_instance=RequestContext(request))
1051 0f8d1e77 Leonidas Poulopoulos
    else:
1052 0f8d1e77 Leonidas Poulopoulos
        return HttpResponseRedirect(reverse("altlogin"))
1053 0f8d1e77 Leonidas Poulopoulos
    
1054 0f8d1e77 Leonidas Poulopoulos
1055 0f8d1e77 Leonidas Poulopoulos
1056 0f8d1e77 Leonidas Poulopoulos
@never_cache
1057 7973b176 Leonidas Poulopoulos
def get_all_services(request):
1058 d163b72b Leonidas Poulopoulos
    lang = request.LANGUAGE_CODE
1059 7973b176 Leonidas Poulopoulos
    servicelocs = ServiceLoc.objects.all()
1060 7973b176 Leonidas Poulopoulos
    locs = []
1061 7973b176 Leonidas Poulopoulos
    for sl in servicelocs:
1062 7973b176 Leonidas Poulopoulos
        response_location = {}
1063 7973b176 Leonidas Poulopoulos
        response_location['lat'] = u"%s"%sl.latitude
1064 7973b176 Leonidas Poulopoulos
        response_location['lng'] = u"%s"%sl.longitude
1065 7973b176 Leonidas Poulopoulos
        response_location['address'] = u"%s<br>%s"%(sl.address_street, sl.address_city)
1066 27d6f3e2 Leonidas Poulopoulos
        if len(sl.enc_level[0]) != 0:
1067 27d6f3e2 Leonidas Poulopoulos
            response_location['enc'] = u"%s"%(','.join(sl.enc_level))
1068 27d6f3e2 Leonidas Poulopoulos
        else:
1069 27d6f3e2 Leonidas Poulopoulos
            response_location['enc'] = u"-"
1070 7973b176 Leonidas Poulopoulos
        response_location['AP_no'] = u"%s"%(sl.AP_no)
1071 d163b72b Leonidas Poulopoulos
        try:
1072 d163b72b Leonidas Poulopoulos
            response_location['inst'] = sl.institutionid.org_name.get(lang=lang).name
1073 d163b72b Leonidas Poulopoulos
        except Name_i18n.DoesNotExist:
1074 d163b72b Leonidas Poulopoulos
            response_location['inst'] = sl.institutionid.org_name.get(lang='en').name
1075 d163b72b Leonidas Poulopoulos
        try:
1076 d163b72b Leonidas Poulopoulos
            response_location['name'] = sl.loc_name.get(lang=lang).name
1077 d163b72b Leonidas Poulopoulos
        except Name_i18n.DoesNotExist:
1078 d163b72b Leonidas Poulopoulos
            response_location['name'] = sl.loc_name.get(lang='en').name
1079 7973b176 Leonidas Poulopoulos
        response_location['port_restrict'] = u"%s"%(sl.port_restrict)
1080 7973b176 Leonidas Poulopoulos
        response_location['transp_proxy'] = u"%s"%(sl.transp_proxy)
1081 7973b176 Leonidas Poulopoulos
        response_location['IPv6'] = u"%s"%(sl.IPv6)
1082 7973b176 Leonidas Poulopoulos
        response_location['NAT'] = u"%s"%(sl.NAT)
1083 7973b176 Leonidas Poulopoulos
        response_location['wired'] = u"%s"%(sl.wired)
1084 7973b176 Leonidas Poulopoulos
        response_location['SSID'] = u"%s"%(sl.SSID)
1085 7973b176 Leonidas Poulopoulos
        response_location['key'] = u"%s"%sl.pk
1086 7973b176 Leonidas Poulopoulos
        locs.append(response_location)
1087 7973b176 Leonidas Poulopoulos
    return HttpResponse(json.dumps(locs), mimetype='application/json')
1088 7973b176 Leonidas Poulopoulos
1089 62d0c01e Leonidas Poulopoulos
@never_cache
1090 dc16526f Leonidas Poulopoulos
def manage_login(request,backend):
1091 dc16526f Leonidas Poulopoulos
    logout(request)
1092 dc16526f Leonidas Poulopoulos
    qs = request.GET.urlencode()
1093 dc16526f Leonidas Poulopoulos
    qs = '?%s' % qs if qs else ''
1094 dc16526f Leonidas Poulopoulos
    if backend == 'shibboleth':
1095 dc16526f Leonidas Poulopoulos
        return redirect(reverse('login'))
1096 dc16526f Leonidas Poulopoulos
    return redirect(reverse('socialauth_begin', args=[backend])+qs)
1097 dc16526f Leonidas Poulopoulos
1098 dc16526f Leonidas Poulopoulos
@never_cache
1099 62d0c01e Leonidas Poulopoulos
def user_login(request):
1100 62d0c01e Leonidas Poulopoulos
    try:
1101 62d0c01e Leonidas Poulopoulos
        error_username = False
1102 62d0c01e Leonidas Poulopoulos
        error_orgname = False
1103 62d0c01e Leonidas Poulopoulos
        error_entitlement = False
1104 62d0c01e Leonidas Poulopoulos
        error_mail = False
1105 62d0c01e Leonidas Poulopoulos
        has_entitlement = False
1106 62d0c01e Leonidas Poulopoulos
        error = ''
1107 62d0c01e Leonidas Poulopoulos
        username = request.META['HTTP_EPPN']
1108 62d0c01e Leonidas Poulopoulos
        if not username:
1109 62d0c01e Leonidas Poulopoulos
            error_username = True
1110 baa68271 Leonidas Poulopoulos
        firstname = lookupShibAttr(settings.SHIB_FIRSTNAME, request.META)
1111 baa68271 Leonidas Poulopoulos
        lastname = lookupShibAttr(settings.SHIB_LASTNAME, request.META)
1112 baa68271 Leonidas Poulopoulos
        mail = lookupShibAttr(settings.SHIB_MAIL, request.META)
1113 baa68271 Leonidas Poulopoulos
        entitlement = lookupShibAttr(settings.SHIB_ENTITLEMENT, request.META)
1114 1f83e8db Leonidas Poulopoulos
1115 62d0c01e Leonidas Poulopoulos
        #organization = request.META['HTTP_SHIB_HOMEORGANIZATION']
1116 62d0c01e Leonidas Poulopoulos
        entitlement = request.META['HTTP_SHIB_EP_ENTITLEMENT']
1117 62d0c01e Leonidas Poulopoulos
        if settings.SHIB_AUTH_ENTITLEMENT in entitlement.split(";"):
1118 62d0c01e Leonidas Poulopoulos
            has_entitlement = True
1119 62d0c01e Leonidas Poulopoulos
        if not has_entitlement:
1120 62d0c01e Leonidas Poulopoulos
            error_entitlement = True
1121 62d0c01e Leonidas Poulopoulos
#        if not organization:
1122 62d0c01e Leonidas Poulopoulos
#            error_orgname = True
1123 62d0c01e Leonidas Poulopoulos
        if not mail:
1124 62d0c01e Leonidas Poulopoulos
            error_mail = True
1125 62d0c01e Leonidas Poulopoulos
        if error_username:
1126 1c417c61 Leonidas Poulopoulos
            error = _("Your idP should release the eduPersonPrincipalName attribute towards this service<br>")
1127 62d0c01e Leonidas Poulopoulos
        if error_entitlement:
1128 1c417c61 Leonidas Poulopoulos
            error = error + _("Your idP should release an appropriate eduPersonEntitlement attribute towards this service<br>")
1129 62d0c01e Leonidas Poulopoulos
        if error_mail:
1130 1c417c61 Leonidas Poulopoulos
            error = error + _("Your idP should release the mail attribute towards this service")
1131 62d0c01e Leonidas Poulopoulos
        if error_username or error_orgname or error_entitlement or error_mail:
1132 7973b176 Leonidas Poulopoulos
            return render_to_response('status.html', {'error': error, "missing_attributes": True},
1133 62d0c01e Leonidas Poulopoulos
                                  context_instance=RequestContext(request))
1134 62d0c01e Leonidas Poulopoulos
        try:
1135 62d0c01e Leonidas Poulopoulos
            user = User.objects.get(username__exact=username)
1136 62d0c01e Leonidas Poulopoulos
            user.email = mail
1137 62d0c01e Leonidas Poulopoulos
            user.first_name = firstname
1138 62d0c01e Leonidas Poulopoulos
            user.last_name = lastname
1139 62d0c01e Leonidas Poulopoulos
            user.save()
1140 62d0c01e Leonidas Poulopoulos
            user_exists = True
1141 62d0c01e Leonidas Poulopoulos
        except User.DoesNotExist:
1142 62d0c01e Leonidas Poulopoulos
            user_exists = False
1143 62d0c01e Leonidas Poulopoulos
        user = authenticate(username=username, firstname=firstname, lastname=lastname, mail=mail, authsource='shibboleth')
1144 62d0c01e Leonidas Poulopoulos
        if user is not None:
1145 62d0c01e Leonidas Poulopoulos
            try:
1146 62d0c01e Leonidas Poulopoulos
                profile = user.get_profile()
1147 62d0c01e Leonidas Poulopoulos
                inst = profile.institution
1148 62d0c01e Leonidas Poulopoulos
            except UserProfile.DoesNotExist:
1149 62d0c01e Leonidas Poulopoulos
                form = UserProfileForm()
1150 62d0c01e Leonidas Poulopoulos
                form.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(pk=user.pk), empty_label=None)
1151 62d0c01e Leonidas Poulopoulos
                form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.all(), empty_label=None)
1152 efc4600b Leonidas Poulopoulos
                form.fields['email'] = forms.CharField(initial = user.email)
1153 62d0c01e Leonidas Poulopoulos
                return render_to_response('registration/select_institution.html', {'form': form}, context_instance=RequestContext(request))
1154 62d0c01e Leonidas Poulopoulos
            if user.is_active:
1155 62d0c01e Leonidas Poulopoulos
               login(request, user)
1156 62d0c01e Leonidas Poulopoulos
               return HttpResponseRedirect(reverse("manage"))
1157 62d0c01e Leonidas Poulopoulos
            else:
1158 7973b176 Leonidas Poulopoulos
                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
1159 7973b176 Leonidas Poulopoulos
                return render_to_response('status.html', {'status': status, 'inactive': True},
1160 62d0c01e Leonidas Poulopoulos
                                  context_instance=RequestContext(request))
1161 62d0c01e Leonidas Poulopoulos
        else:
1162 62d0c01e Leonidas Poulopoulos
            error = _("Something went wrong during user authentication. Contact your administrator %s" %user)
1163 7973b176 Leonidas Poulopoulos
            return render_to_response('status.html', {'error': error,},
1164 62d0c01e Leonidas Poulopoulos
                                  context_instance=RequestContext(request))
1165 b34d9c51 Leonidas Poulopoulos
    except Exception as e:
1166 1f83e8db Leonidas Poulopoulos
        error = _("Invalid login procedure. Error: %s"%e)
1167 7973b176 Leonidas Poulopoulos
        return render_to_response('status.html', {'error': error,},
1168 62d0c01e Leonidas Poulopoulos
                                  context_instance=RequestContext(request))
1169 7973b176 Leonidas Poulopoulos
1170 d163b72b Leonidas Poulopoulos
@never_cache
1171 efc4600b Leonidas Poulopoulos
def check_user_inst(request):
1172 c666e0f0 Leonidas Poulopoulos
    u = request.user.__dict__
1173 c666e0f0 Leonidas Poulopoulos
    s = request.session.keys()
1174 c666e0f0 Leonidas Poulopoulos
    raise Exception
1175 efc4600b Leonidas Poulopoulos
    try:
1176 efc4600b Leonidas Poulopoulos
        profile = user.get_profile()
1177 efc4600b Leonidas Poulopoulos
        inst = profile.institution
1178 efc4600b Leonidas Poulopoulos
        if user.is_active:
1179 efc4600b Leonidas Poulopoulos
            return HttpResponseRedirect(reverse("manage"))
1180 efc4600b Leonidas Poulopoulos
        else:
1181 efc4600b Leonidas Poulopoulos
           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
1182 efc4600b Leonidas Poulopoulos
           return render_to_response('status.html', {'status': status, 'inactive': True},
1183 efc4600b Leonidas Poulopoulos
                                  context_instance=RequestContext(request))
1184 efc4600b Leonidas Poulopoulos
    except UserProfile.DoesNotExist:
1185 efc4600b Leonidas Poulopoulos
        form = UserProfileForm()
1186 efc4600b Leonidas Poulopoulos
        form.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(pk=user.pk), empty_label=None)
1187 efc4600b Leonidas Poulopoulos
        nomail = False
1188 efc4600b Leonidas Poulopoulos
        if not user.email:
1189 efc4600b Leonidas Poulopoulos
            nomail = True
1190 efc4600b Leonidas Poulopoulos
            form.fields['email'] = forms.CharField()
1191 efc4600b Leonidas Poulopoulos
        else:
1192 efc4600b Leonidas Poulopoulos
            form.fields['email'] = forms.CharField(initial = user.email)
1193 efc4600b Leonidas Poulopoulos
        form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.all(), empty_label=None)
1194 efc4600b Leonidas Poulopoulos
        return render_to_response('registration/select_institution.html', {'form': form, 'nomail': nomail}, context_instance=RequestContext(request))
1195 efc4600b Leonidas Poulopoulos
1196 efc4600b Leonidas Poulopoulos
1197 d163b72b Leonidas Poulopoulos
@never_cache
1198 af9d484b Leonidas Poulopoulos
def geolocate(request):
1199 8a177e59 Leonidas Poulopoulos
    return render_to_response('front/geolocate.html', context_instance=RequestContext(request))
1200 d163b72b Leonidas Poulopoulos
@never_cache
1201 7b9cc79e Leonidas Poulopoulos
def participants(request):
1202 04cbcb1e Leonidas Poulopoulos
    institutions = Institution.objects.all().select_related('institutiondetails')
1203 7b9cc79e Leonidas Poulopoulos
    dets = []
1204 7b9cc79e Leonidas Poulopoulos
    for i in institutions:
1205 7b9cc79e Leonidas Poulopoulos
        try:
1206 7b9cc79e Leonidas Poulopoulos
            dets.append(i.institutiondetails)
1207 7b9cc79e Leonidas Poulopoulos
        except InstitutionDetails.DoesNotExist:
1208 7b9cc79e Leonidas Poulopoulos
            pass
1209 8a177e59 Leonidas Poulopoulos
    return render_to_response('front/participants.html', { 'institutions': dets } ,
1210 7b9cc79e Leonidas Poulopoulos
                                  context_instance=RequestContext(request))
1211 d163b72b Leonidas Poulopoulos
@never_cache
1212 62d0c01e Leonidas Poulopoulos
def selectinst(request):
1213 62d0c01e Leonidas Poulopoulos
    if request.method == 'POST':
1214 62d0c01e Leonidas Poulopoulos
        request_data = request.POST.copy()
1215 62d0c01e Leonidas Poulopoulos
        user = request_data['user']
1216 7973b176 Leonidas Poulopoulos
        try:
1217 7973b176 Leonidas Poulopoulos
            existingProfile = UserProfile.objects.get(user=user)
1218 7973b176 Leonidas Poulopoulos
            error = _("Violation warning: User account is already associated with an institution.The event has been logged and our administrators will be notified about it")
1219 7973b176 Leonidas Poulopoulos
            return render_to_response('status.html', {'error': error, 'inactive': True},
1220 7973b176 Leonidas Poulopoulos
                                  context_instance=RequestContext(request))
1221 7973b176 Leonidas Poulopoulos
        except UserProfile.DoesNotExist:
1222 7973b176 Leonidas Poulopoulos
            pass
1223 7973b176 Leonidas Poulopoulos
            
1224 62d0c01e Leonidas Poulopoulos
        form = UserProfileForm(request_data)
1225 62d0c01e Leonidas Poulopoulos
        if form.is_valid():
1226 efc4600b Leonidas Poulopoulos
            mailField = form.cleaned_data.pop('email')
1227 62d0c01e Leonidas Poulopoulos
            userprofile = form.save()
1228 efc4600b Leonidas Poulopoulos
            useradded = userprofile.user
1229 efc4600b Leonidas Poulopoulos
            useradded.email = mailField
1230 efc4600b Leonidas Poulopoulos
            useradded.save()
1231 7973b176 Leonidas Poulopoulos
            user_activation_notify(userprofile)
1232 62d0c01e Leonidas Poulopoulos
            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
1233 7973b176 Leonidas Poulopoulos
            return render_to_response('status.html', {'status': error, 'inactive': True},
1234 62d0c01e Leonidas Poulopoulos
                                  context_instance=RequestContext(request))
1235 62d0c01e Leonidas Poulopoulos
        else:
1236 efc4600b Leonidas Poulopoulos
            form.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(pk=user), empty_label=None)
1237 62d0c01e Leonidas Poulopoulos
            form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.all(), empty_label=None)
1238 efc4600b Leonidas Poulopoulos
            nomail = False
1239 efc4600b Leonidas Poulopoulos
            userObj = User.objects.get(pk=user)
1240 efc4600b Leonidas Poulopoulos
            if not userObj.email:
1241 efc4600b Leonidas Poulopoulos
                nomail = True
1242 efc4600b Leonidas Poulopoulos
                form.fields['email'] = forms.CharField()
1243 efc4600b Leonidas Poulopoulos
            else:
1244 efc4600b Leonidas Poulopoulos
                form.fields['email'] = forms.CharField(initial = userObj.email)
1245 efc4600b Leonidas Poulopoulos
            return render_to_response('registration/select_institution.html', {'form': form, 'nomail': nomail}, context_instance=RequestContext(request))
1246 62d0c01e Leonidas Poulopoulos
1247 af9d484b Leonidas Poulopoulos
1248 7973b176 Leonidas Poulopoulos
def user_activation_notify(userprofile):
1249 7973b176 Leonidas Poulopoulos
    current_site = Site.objects.get_current()
1250 7973b176 Leonidas Poulopoulos
    subject = render_to_string('registration/activation_email_subject.txt',
1251 7973b176 Leonidas Poulopoulos
                                   { 'site': current_site })
1252 7973b176 Leonidas Poulopoulos
    # Email subject *must not* contain newlines
1253 7973b176 Leonidas Poulopoulos
    subject = ''.join(subject.splitlines())
1254 7973b176 Leonidas Poulopoulos
    registration_profile = RegistrationProfile.objects.create_profile(userprofile.user)
1255 7973b176 Leonidas Poulopoulos
    message = render_to_string('registration/activation_email.txt',
1256 7973b176 Leonidas Poulopoulos
                                   { 'activation_key': registration_profile.activation_key,
1257 7973b176 Leonidas Poulopoulos
                                     'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
1258 7973b176 Leonidas Poulopoulos
                                     'site': current_site,
1259 7973b176 Leonidas Poulopoulos
                                     'user': userprofile.user,
1260 7973b176 Leonidas Poulopoulos
                                     'institution': userprofile.institution })
1261 7973b176 Leonidas Poulopoulos
    send_new_mail(settings.EMAIL_SUBJECT_PREFIX + subject, 
1262 7973b176 Leonidas Poulopoulos
                              message, settings.SERVER_EMAIL,
1263 7973b176 Leonidas Poulopoulos
                             settings.NOTIFY_ADMIN_MAILS, [])
1264 d163b72b Leonidas Poulopoulos
@never_cache
1265 af9d484b Leonidas Poulopoulos
def closest(request):
1266 af9d484b Leonidas Poulopoulos
    if request.method == 'GET':
1267 af9d484b Leonidas Poulopoulos
        locs = []
1268 af9d484b Leonidas Poulopoulos
        request_data = request.GET.copy()
1269 af9d484b Leonidas Poulopoulos
        response_location = {}
1270 433489b5 Leonidas Poulopoulos
        if 'lat' in request.GET and 'lng' in request.GET:
1271 433489b5 Leonidas Poulopoulos
            response_location["lat"] = request_data['lat']
1272 433489b5 Leonidas Poulopoulos
            response_location["lng"] = request_data['lng']
1273 433489b5 Leonidas Poulopoulos
        else:
1274 433489b5 Leonidas Poulopoulos
            response = {"status":"Cannot parse a request without longitude or latitude. Use ?lng=<langitude>&lat=<latitude>&_=<random_num> in your query"}
1275 433489b5 Leonidas Poulopoulos
            return HttpResponse(json.dumps(response), mimetype='application/json')
1276 af9d484b Leonidas Poulopoulos
        lat = float(request_data['lat'])
1277 af9d484b Leonidas Poulopoulos
        lng = float(request_data['lng'])
1278 af9d484b Leonidas Poulopoulos
        R = 6371
1279 af9d484b Leonidas Poulopoulos
        distances = {}
1280 af9d484b Leonidas Poulopoulos
        closestMarker = {}
1281 af9d484b Leonidas Poulopoulos
        closest = -1
1282 d163b72b Leonidas Poulopoulos
        points = getPoints()
1283 d163b72b Leonidas Poulopoulos
        for (counter, i) in enumerate(points):
1284 d163b72b Leonidas Poulopoulos
            pointname = i['text']
1285 d163b72b Leonidas Poulopoulos
            pointlng = i['lng'] 
1286 d163b72b Leonidas Poulopoulos
            pointlat = i['lat']
1287 d163b72b Leonidas Poulopoulos
            pointtext = i['text']
1288 04cbcb1e Leonidas Poulopoulos
            plainname = i['name']
1289 d163b72b Leonidas Poulopoulos
            dLat = rad(float(pointlat)-float(lat))
1290 d163b72b Leonidas Poulopoulos
            dLong = rad(float(pointlng)-float(lng))
1291 d163b72b Leonidas Poulopoulos
            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) 
1292 d163b72b Leonidas Poulopoulos
            c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
1293 d163b72b Leonidas Poulopoulos
            d = R * c
1294 d163b72b Leonidas Poulopoulos
            distances[counter] = d
1295 d163b72b Leonidas Poulopoulos
            if (closest == -1 or d < distances[closest]):
1296 d163b72b Leonidas Poulopoulos
                closest = counter
1297 04cbcb1e Leonidas Poulopoulos
                closestMarker = {"name": pointname, "lat": pointlat, "lng": pointlng, "text": pointtext, 'plainname':plainname}
1298 d163b72b Leonidas Poulopoulos
        return HttpResponse(json.dumps(closestMarker), mimetype='application/json')
1299 433489b5 Leonidas Poulopoulos
    else:
1300 433489b5 Leonidas Poulopoulos
        response = {"status":"Use a GET method for your request"}
1301 433489b5 Leonidas Poulopoulos
        return HttpResponse(json.dumps(response), mimetype='application/json')
1302 d163b72b Leonidas Poulopoulos
1303 d163b72b Leonidas Poulopoulos
@never_cache
1304 d163b72b Leonidas Poulopoulos
def worldPoints(request):
1305 d163b72b Leonidas Poulopoulos
    if request.method == 'GET':
1306 d163b72b Leonidas Poulopoulos
        points = getPoints()
1307 d163b72b Leonidas Poulopoulos
        return HttpResponse(json.dumps(points), mimetype='application/json')
1308 d163b72b Leonidas Poulopoulos
1309 d163b72b Leonidas Poulopoulos
@never_cache
1310 d163b72b Leonidas Poulopoulos
def world(request):
1311 8a177e59 Leonidas Poulopoulos
        return render_to_response('front/world.html', context_instance=RequestContext(request))
1312 d163b72b Leonidas Poulopoulos
1313 1c417c61 Leonidas Poulopoulos
1314 1c417c61 Leonidas Poulopoulos
@never_cache
1315 1c417c61 Leonidas Poulopoulos
def managementPage(request):
1316 1c417c61 Leonidas Poulopoulos
    return render_to_response('front/management.html',
1317 1c417c61 Leonidas Poulopoulos
                                  context_instance=RequestContext(request))
1318 1c417c61 Leonidas Poulopoulos
1319 d163b72b Leonidas Poulopoulos
def getPoints():
1320 d163b72b Leonidas Poulopoulos
    points = cache.get('points')
1321 d163b72b Leonidas Poulopoulos
    if points:
1322 d163b72b Leonidas Poulopoulos
        points = bz2.decompress(points)
1323 d163b72b Leonidas Poulopoulos
        return json.loads(points)
1324 d163b72b Leonidas Poulopoulos
    else:
1325 d163b72b Leonidas Poulopoulos
        point_list = []
1326 af9d484b Leonidas Poulopoulos
        doc = ET.parse(settings.KML_FILE)
1327 af9d484b Leonidas Poulopoulos
        root = doc.getroot()
1328 af9d484b Leonidas Poulopoulos
        r = root.getchildren()[0]
1329 af9d484b Leonidas Poulopoulos
        for (counter, i) in enumerate(r.getchildren()):
1330 af9d484b Leonidas Poulopoulos
            if "id" in i.keys():
1331 af9d484b Leonidas Poulopoulos
                j = i.getchildren()
1332 af9d484b Leonidas Poulopoulos
                pointname = j[0].text
1333 af9d484b Leonidas Poulopoulos
                point = j[2].getchildren()[0].text
1334 af9d484b Leonidas Poulopoulos
                pointlng, pointlat, pointele = point.split(',')
1335 d163b72b Leonidas Poulopoulos
                Marker = {"name": pointname, "lat": pointlat, "lng": pointlng, "text": j[1].text}
1336 d163b72b Leonidas Poulopoulos
                point_list.append(Marker);
1337 d163b72b Leonidas Poulopoulos
        points = json.dumps(point_list)
1338 d163b72b Leonidas Poulopoulos
        cache.set('points', bz2.compress(points), 60 * 3600 * 24)
1339 d163b72b Leonidas Poulopoulos
        return json.loads(points)
1340 c2b3014a Leonidas Poulopoulos
1341 d163b72b Leonidas Poulopoulos
1342 d163b72b Leonidas Poulopoulos
@never_cache
1343 c2b3014a Leonidas Poulopoulos
def instxml(request):
1344 c2b3014a Leonidas Poulopoulos
    ET._namespace_map["http://www.w3.org/2001/XMLSchema-instance"] = 'xsi'
1345 c2b3014a Leonidas Poulopoulos
    root = ET.Element("institutions")
1346 c2b3014a Leonidas Poulopoulos
    NS_XSI = "{http://www.w3.org/2001/XMLSchema-instance}"
1347 10e9ee83 Leonidas Poulopoulos
    root.set(NS_XSI + "noNamespaceSchemaLocation", "institution.xsd")
1348 c2b3014a Leonidas Poulopoulos
    institutions = Institution.objects.all()
1349 c2b3014a Leonidas Poulopoulos
    for institution in institutions:
1350 c2b3014a Leonidas Poulopoulos
        try:
1351 c2b3014a Leonidas Poulopoulos
            inst = institution.institutiondetails
1352 c2b3014a Leonidas Poulopoulos
            if not inst:
1353 c2b3014a Leonidas Poulopoulos
                pass
1354 c2b3014a Leonidas Poulopoulos
        except InstitutionDetails.DoesNotExist:
1355 c2b3014a Leonidas Poulopoulos
            pass
1356 c2b3014a Leonidas Poulopoulos
        
1357 c2b3014a Leonidas Poulopoulos
        instElement = ET.SubElement(root, "institution")
1358 c2b3014a Leonidas Poulopoulos
        
1359 c2b3014a Leonidas Poulopoulos
        instCountry = ET.SubElement(instElement, "country")
1360 c2b3014a Leonidas Poulopoulos
        instCountry.text = ("%s" %inst.institution.realmid.country).upper()
1361 c2b3014a Leonidas Poulopoulos
        
1362 c2b3014a Leonidas Poulopoulos
        instType = ET.SubElement(instElement, "type")
1363 0790d933 Leonidas Poulopoulos
        instType.text = "%s" %inst.institution.ertype
1364 c2b3014a Leonidas Poulopoulos
        
1365 c2b3014a Leonidas Poulopoulos
        for realm in institution.instrealm_set.all():
1366 c2b3014a Leonidas Poulopoulos
            instRealm = ET.SubElement(instElement, "inst_realm")
1367 c2b3014a Leonidas Poulopoulos
            instRealm.text = realm.realm
1368 c2b3014a Leonidas Poulopoulos
        
1369 c2b3014a Leonidas Poulopoulos
        for name in inst.institution.org_name.all():
1370 c2b3014a Leonidas Poulopoulos
            instOrgName = ET.SubElement(instElement, "org_name")
1371 c2b3014a Leonidas Poulopoulos
            instOrgName.attrib["lang"] = name.lang
1372 c2b3014a Leonidas Poulopoulos
            instOrgName.text = u"%s" %name.name
1373 c2b3014a Leonidas Poulopoulos
        
1374 c2b3014a Leonidas Poulopoulos
        instAddress = ET.SubElement(instElement, "address")
1375 c2b3014a Leonidas Poulopoulos
        
1376 c2b3014a Leonidas Poulopoulos
        instAddrStreet = ET.SubElement(instAddress, "street")
1377 c2b3014a Leonidas Poulopoulos
        instAddrStreet.text = inst.address_street
1378 c2b3014a Leonidas Poulopoulos
        
1379 c2b3014a Leonidas Poulopoulos
        instAddrCity = ET.SubElement(instAddress, "city")
1380 c2b3014a Leonidas Poulopoulos
        instAddrCity.text = inst.address_city
1381 c2b3014a Leonidas Poulopoulos
        
1382 c2b3014a Leonidas Poulopoulos
        for contact in inst.contact.all():
1383 c2b3014a Leonidas Poulopoulos
            instContact = ET.SubElement(instElement, "contact")
1384 c2b3014a Leonidas Poulopoulos
            
1385 c2b3014a Leonidas Poulopoulos
            instContactName = ET.SubElement(instContact, "name")
1386 9741b379 Leonidas Poulopoulos
            instContactName.text = "%s" %(contact.name)
1387 c2b3014a Leonidas Poulopoulos
            
1388 c2b3014a Leonidas Poulopoulos
            instContactEmail = ET.SubElement(instContact, "email")
1389 c2b3014a Leonidas Poulopoulos
            instContactEmail.text = contact.email
1390 c2b3014a Leonidas Poulopoulos
            
1391 c2b3014a Leonidas Poulopoulos
            instContactPhone = ET.SubElement(instContact, "phone")
1392 c2b3014a Leonidas Poulopoulos
            instContactPhone.text = contact.phone
1393 af9d484b Leonidas Poulopoulos
        
1394 34051323 Leonidas Poulopoulos
        urltypes = []
1395 c2b3014a Leonidas Poulopoulos
        for url in inst.url.all():
1396 c2b3014a Leonidas Poulopoulos
            instUrl = ET.SubElement(instElement, "%s_URL"%(url.urltype))
1397 c2b3014a Leonidas Poulopoulos
            instUrl.attrib["lang"] = url.lang
1398 c2b3014a Leonidas Poulopoulos
            instUrl.text = url.url
1399 34051323 Leonidas Poulopoulos
            urltypes.append(url.urltype)
1400 34051323 Leonidas Poulopoulos
1401 34051323 Leonidas Poulopoulos
        if 'policy' not in urltypes:
1402 34051323 Leonidas Poulopoulos
            instUrl = ET.SubElement(instElement, "policy_URL")
1403 34051323 Leonidas Poulopoulos
            instUrl.attrib["lang"] = 'en'
1404 34051323 Leonidas Poulopoulos
            instUrl.text = '-'
1405 c2b3014a Leonidas Poulopoulos
        
1406 10e9ee83 Leonidas Poulopoulos
        instTs = ET.SubElement(instElement, "ts")
1407 10e9ee83 Leonidas Poulopoulos
        instTs.text = "%s" %inst.ts.isoformat()
1408 c2b3014a Leonidas Poulopoulos
        #Let's go to Institution Service Locations
1409 af9d484b Leonidas Poulopoulos
1410 c2b3014a Leonidas Poulopoulos
        for serviceloc in inst.institution.serviceloc_set.all():
1411 c2b3014a Leonidas Poulopoulos
            instLocation = ET.SubElement(instElement, "location")
1412 c2b3014a Leonidas Poulopoulos
            
1413 c2b3014a Leonidas Poulopoulos
            instLong = ET.SubElement(instLocation, "longitude")
1414 c2b3014a Leonidas Poulopoulos
            instLong.text = "%s" %serviceloc.longitude
1415 c2b3014a Leonidas Poulopoulos
            
1416 c2b3014a Leonidas Poulopoulos
            instLat = ET.SubElement(instLocation, "latitude")
1417 c2b3014a Leonidas Poulopoulos
            instLat.text = "%s" %serviceloc.latitude
1418 c2b3014a Leonidas Poulopoulos
            
1419 c2b3014a Leonidas Poulopoulos
            for instlocname in serviceloc.loc_name.all():
1420 c2b3014a Leonidas Poulopoulos
                instLocName = ET.SubElement(instLocation, "loc_name")
1421 c2b3014a Leonidas Poulopoulos
                instLocName.attrib["lang"] = instlocname.lang
1422 c2b3014a Leonidas Poulopoulos
                instLocName.text = instlocname.name
1423 c2b3014a Leonidas Poulopoulos
            
1424 c2b3014a Leonidas Poulopoulos
            instLocAddress = ET.SubElement(instLocation, "address")
1425 c2b3014a Leonidas Poulopoulos
        
1426 c2b3014a Leonidas Poulopoulos
            instLocAddrStreet = ET.SubElement(instLocAddress, "street")
1427 c2b3014a Leonidas Poulopoulos
            instLocAddrStreet.text = serviceloc.address_street
1428 c2b3014a Leonidas Poulopoulos
        
1429 c2b3014a Leonidas Poulopoulos
            instLocAddrCity = ET.SubElement(instLocAddress, "city")
1430 c2b3014a Leonidas Poulopoulos
            instLocAddrCity.text = serviceloc.address_city
1431 c2b3014a Leonidas Poulopoulos
            
1432 138dad8b Leonidas Poulopoulos
            for contact in serviceloc.contact.all():
1433 138dad8b Leonidas Poulopoulos
                instLocContact = ET.SubElement(instLocation, "contact")
1434 138dad8b Leonidas Poulopoulos
                
1435 138dad8b Leonidas Poulopoulos
                instLocContactName = ET.SubElement(instLocContact, "name")
1436 9741b379 Leonidas Poulopoulos
                instLocContactName.text = "%s" %(contact.name)
1437 138dad8b Leonidas Poulopoulos
                
1438 138dad8b Leonidas Poulopoulos
                instLocContactEmail = ET.SubElement(instLocContact, "email")
1439 138dad8b Leonidas Poulopoulos
                instLocContactEmail.text = contact.email
1440 138dad8b Leonidas Poulopoulos
                
1441 138dad8b Leonidas Poulopoulos
                instLocContactPhone = ET.SubElement(instLocContact, "phone")
1442 138dad8b Leonidas Poulopoulos
                instLocContactPhone.text = contact.phone
1443 138dad8b Leonidas Poulopoulos
            
1444 c2b3014a Leonidas Poulopoulos
            instLocSSID = ET.SubElement(instLocation, "SSID")
1445 c2b3014a Leonidas Poulopoulos
            instLocSSID.text = serviceloc.SSID
1446 c2b3014a Leonidas Poulopoulos
            
1447 c2b3014a Leonidas Poulopoulos
            instLocEncLevel = ET.SubElement(instLocation, "enc_level")
1448 138dad8b Leonidas Poulopoulos
            instLocEncLevel.text = ', '.join(serviceloc.enc_level)
1449 c2b3014a Leonidas Poulopoulos
            
1450 c2b3014a Leonidas Poulopoulos
            instLocPortRestrict = ET.SubElement(instLocation, "port_restrict")
1451 c2b3014a Leonidas Poulopoulos
            instLocPortRestrict.text = ("%s" %serviceloc.port_restrict).lower()
1452 c2b3014a Leonidas Poulopoulos
            
1453 c2b3014a Leonidas Poulopoulos
            instLocTransProxy = ET.SubElement(instLocation, "transp_proxy")
1454 c2b3014a Leonidas Poulopoulos
            instLocTransProxy.text = ("%s" %serviceloc.transp_proxy).lower()
1455 c2b3014a Leonidas Poulopoulos
            
1456 c2b3014a Leonidas Poulopoulos
            instLocIpv6 = ET.SubElement(instLocation, "IPv6")
1457 c2b3014a Leonidas Poulopoulos
            instLocIpv6.text = ("%s" %serviceloc.IPv6).lower()
1458 c2b3014a Leonidas Poulopoulos
            
1459 c2b3014a Leonidas Poulopoulos
            instLocNAT = ET.SubElement(instLocation, "NAT")
1460 c2b3014a Leonidas Poulopoulos
            instLocNAT.text = ("%s" %serviceloc.NAT).lower()
1461 c2b3014a Leonidas Poulopoulos
            
1462 c2b3014a Leonidas Poulopoulos
            instLocAP_no = ET.SubElement(instLocation, "AP_no")
1463 c2b3014a Leonidas Poulopoulos
            instLocAP_no.text = "%s" %int(serviceloc.AP_no)
1464 c2b3014a Leonidas Poulopoulos
            
1465 c2b3014a Leonidas Poulopoulos
            instLocWired = ET.SubElement(instLocation, "wired")
1466 c2b3014a Leonidas Poulopoulos
            instLocWired.text = ("%s" %serviceloc.wired).lower()
1467 c2b3014a Leonidas Poulopoulos
            
1468 c2b3014a Leonidas Poulopoulos
            for url in serviceloc.url.all():
1469 c2b3014a Leonidas Poulopoulos
                instLocUrl = ET.SubElement(instLocation, "%s_URL"%(url.urltype))
1470 c2b3014a Leonidas Poulopoulos
                instLocUrl.attrib["lang"] = url.lang
1471 c2b3014a Leonidas Poulopoulos
                instLocUrl.text = url.url
1472 c2b3014a Leonidas Poulopoulos
            
1473 c2b3014a Leonidas Poulopoulos
    return render_to_response("general/institution.xml", {"xml":to_xml(root)},context_instance=RequestContext(request,), mimetype="application/xml")
1474 c2b3014a Leonidas Poulopoulos
        
1475 d163b72b Leonidas Poulopoulos
@never_cache
1476 c2b3014a Leonidas Poulopoulos
def realmxml(request):
1477 c2b3014a Leonidas Poulopoulos
    realm = Realm.objects.all()[0]
1478 c2b3014a Leonidas Poulopoulos
    ET._namespace_map["http://www.w3.org/2001/XMLSchema-instance"] = 'xsi'
1479 c2b3014a Leonidas Poulopoulos
    root = ET.Element("realms")
1480 c2b3014a Leonidas Poulopoulos
    NS_XSI = "{http://www.w3.org/2001/XMLSchema-instance}"
1481 c2b3014a Leonidas Poulopoulos
    root.set(NS_XSI + "noNamespaceSchemaLocation", "realm.xsd")
1482 c2b3014a Leonidas Poulopoulos
    realmElement = ET.SubElement(root, "realm")
1483 c2b3014a Leonidas Poulopoulos
    
1484 c2b3014a Leonidas Poulopoulos
    realmCountry = ET.SubElement(realmElement, "country")
1485 0790d933 Leonidas Poulopoulos
    realmCountry.text = realm.country.upper()
1486 c2b3014a Leonidas Poulopoulos
        
1487 c2b3014a Leonidas Poulopoulos
    realmStype = ET.SubElement(realmElement, "stype")
1488 c2b3014a Leonidas Poulopoulos
    realmStype.text = "%s" %realm.stype
1489 c2b3014a Leonidas Poulopoulos
    
1490 c2b3014a Leonidas Poulopoulos
    for name in realm.org_name.all():
1491 c2b3014a Leonidas Poulopoulos
        realmOrgName = ET.SubElement(realmElement, "org_name")
1492 c2b3014a Leonidas Poulopoulos
        realmOrgName.attrib["lang"] = name.lang
1493 c2b3014a Leonidas Poulopoulos
        realmOrgName.text = u"%s" %name.name
1494 c2b3014a Leonidas Poulopoulos
    
1495 c2b3014a Leonidas Poulopoulos
    realmAddress = ET.SubElement(realmElement, "address")
1496 c2b3014a Leonidas Poulopoulos
        
1497 c2b3014a Leonidas Poulopoulos
    realmAddrStreet = ET.SubElement(realmAddress, "street")
1498 c2b3014a Leonidas Poulopoulos
    realmAddrStreet.text = realm.address_street
1499 c2b3014a Leonidas Poulopoulos
    
1500 c2b3014a Leonidas Poulopoulos
    realmAddrCity = ET.SubElement(realmAddress, "city")
1501 c2b3014a Leonidas Poulopoulos
    realmAddrCity.text = realm.address_city
1502 c2b3014a Leonidas Poulopoulos
    
1503 c2b3014a Leonidas Poulopoulos
    for contact in realm.contact.all():
1504 c2b3014a Leonidas Poulopoulos
        realmContact = ET.SubElement(realmElement, "contact")
1505 c2b3014a Leonidas Poulopoulos
        
1506 c2b3014a Leonidas Poulopoulos
        realmContactName = ET.SubElement(realmContact, "name")
1507 9741b379 Leonidas Poulopoulos
        realmContactName.text = "%s" %(contact.name)
1508 c2b3014a Leonidas Poulopoulos
        
1509 c2b3014a Leonidas Poulopoulos
        realmContactEmail = ET.SubElement(realmContact, "email")
1510 c2b3014a Leonidas Poulopoulos
        realmContactEmail.text = contact.email
1511 c2b3014a Leonidas Poulopoulos
        
1512 c2b3014a Leonidas Poulopoulos
        realmContactPhone = ET.SubElement(realmContact, "phone")
1513 c2b3014a Leonidas Poulopoulos
        realmContactPhone.text = contact.phone
1514 c2b3014a Leonidas Poulopoulos
    
1515 c2b3014a Leonidas Poulopoulos
    for url in realm.url.all():
1516 c2b3014a Leonidas Poulopoulos
        realmUrl = ET.SubElement(realmElement, "%s_URL"%(url.urltype))
1517 c2b3014a Leonidas Poulopoulos
        realmUrl.attrib["lang"] = url.lang
1518 c2b3014a Leonidas Poulopoulos
        realmUrl.text = url.url
1519 c2b3014a Leonidas Poulopoulos
    
1520 0790d933 Leonidas Poulopoulos
    instTs = ET.SubElement(realmElement, "ts")
1521 0790d933 Leonidas Poulopoulos
    instTs.text = "%s" %realm.ts.isoformat()
1522 0790d933 Leonidas Poulopoulos
    
1523 c2b3014a Leonidas Poulopoulos
    return render_to_response("general/realm.xml", {"xml":to_xml(root)},context_instance=RequestContext(request,), mimetype="application/xml")
1524 c2b3014a Leonidas Poulopoulos
1525 d163b72b Leonidas Poulopoulos
@never_cache
1526 c2b3014a Leonidas Poulopoulos
def realmdataxml(request):
1527 c2b3014a Leonidas Poulopoulos
    realm = Realm.objects.all()[0]
1528 c2b3014a Leonidas Poulopoulos
    ET._namespace_map["http://www.w3.org/2001/XMLSchema-instance"] = 'xsi'
1529 0790d933 Leonidas Poulopoulos
    root = ET.Element("realm_data_root")
1530 c2b3014a Leonidas Poulopoulos
    NS_XSI = "{http://www.w3.org/2001/XMLSchema-instance}"
1531 d9a68b19 Leonidas Poulopoulos
    root.set(NS_XSI + "noNamespaceSchemaLocation", "realm_data.xsd")
1532 c2b3014a Leonidas Poulopoulos
    
1533 0790d933 Leonidas Poulopoulos
    realmdataElement = ET.SubElement(root, "realm_data")
1534 0790d933 Leonidas Poulopoulos
    
1535 0790d933 Leonidas Poulopoulos
    realmCountry = ET.SubElement(realmdataElement, "country")
1536 0790d933 Leonidas Poulopoulos
    realmCountry.text = realm.country.upper()
1537 0790d933 Leonidas Poulopoulos
    
1538 d9a68b19 Leonidas Poulopoulos
    nIdpCountry = ET.SubElement(realmdataElement, "number_IdP")
1539 0790d933 Leonidas Poulopoulos
    nIdpCountry.text = "%s" %len(realm.institution_set.filter(ertype=1))
1540 0790d933 Leonidas Poulopoulos
    
1541 0790d933 Leonidas Poulopoulos
    nSPCountry = ET.SubElement(realmdataElement, "number_SP")
1542 0790d933 Leonidas Poulopoulos
    nSPCountry.text = "%s" %len(realm.institution_set.filter(ertype=2))
1543 0790d933 Leonidas Poulopoulos
    
1544 0790d933 Leonidas Poulopoulos
    nSPIdpCountry = ET.SubElement(realmdataElement, "number_SPIdP")
1545 0790d933 Leonidas Poulopoulos
    nSPIdpCountry.text = "%s" %len(realm.institution_set.filter(ertype=3))
1546 0790d933 Leonidas Poulopoulos
    
1547 0790d933 Leonidas Poulopoulos
    ninstCountry = ET.SubElement(realmdataElement, "number_inst")
1548 0790d933 Leonidas Poulopoulos
    ninstCountry.text = "%s" %len(realm.institution_set.all())
1549 0790d933 Leonidas Poulopoulos
    
1550 0790d933 Leonidas Poulopoulos
    nuserCountry = ET.SubElement(realmdataElement, "number_user")
1551 0790d933 Leonidas Poulopoulos
    insts = realm.institution_set.all()
1552 0790d933 Leonidas Poulopoulos
    users = 0
1553 0790d933 Leonidas Poulopoulos
    for inst in insts:
1554 0790d933 Leonidas Poulopoulos
        try:
1555 f545b59c Leonidas Poulopoulos
            if inst.institutiondetails.number_user:
1556 f545b59c Leonidas Poulopoulos
                users = users + inst.institutiondetails.number_user
1557 0790d933 Leonidas Poulopoulos
        except InstitutionDetails.DoesNotExist:
1558 0790d933 Leonidas Poulopoulos
            pass
1559 0790d933 Leonidas Poulopoulos
    nuserCountry.text = "%s" %users
1560 0790d933 Leonidas Poulopoulos
    
1561 0790d933 Leonidas Poulopoulos
    nIdCountry = ET.SubElement(realmdataElement, "number_id")
1562 0790d933 Leonidas Poulopoulos
    insts = realm.institution_set.all()
1563 0790d933 Leonidas Poulopoulos
    ids = 0
1564 0790d933 Leonidas Poulopoulos
    for inst in insts:
1565 0790d933 Leonidas Poulopoulos
        try:
1566 6f08eac3 Leonidas Poulopoulos
            if inst.institutiondetails.number_id:
1567 6f08eac3 Leonidas Poulopoulos
                ids = ids + inst.institutiondetails.number_id
1568 0790d933 Leonidas Poulopoulos
        except InstitutionDetails.DoesNotExist:
1569 0790d933 Leonidas Poulopoulos
            pass
1570 0790d933 Leonidas Poulopoulos
    nIdCountry.text = "%s" %ids
1571 0790d933 Leonidas Poulopoulos
    
1572 0790d933 Leonidas Poulopoulos
    # Get the latest ts from all tables...
1573 0790d933 Leonidas Poulopoulos
    datetimes = []
1574 20802476 Leonidas Poulopoulos
    if InstitutionDetails.objects.aggregate(Max('ts'))['ts__max']:
1575 20802476 Leonidas Poulopoulos
        datetimes.append(InstitutionDetails.objects.aggregate(Max('ts'))['ts__max'])
1576 20802476 Leonidas Poulopoulos
    if Realm.objects.aggregate(Max('ts'))['ts__max']:
1577 20802476 Leonidas Poulopoulos
        datetimes.append(Realm.objects.aggregate(Max('ts'))['ts__max'])
1578 20802476 Leonidas Poulopoulos
    if InstServer.objects.aggregate(Max('ts'))['ts__max']:
1579 20802476 Leonidas Poulopoulos
        datetimes.append(InstServer.objects.aggregate(Max('ts'))['ts__max'])
1580 20802476 Leonidas Poulopoulos
    if ServiceLoc.objects.aggregate(Max('ts'))['ts__max']:
1581 20802476 Leonidas Poulopoulos
        datetimes.append(ServiceLoc.objects.aggregate(Max('ts'))['ts__max'])
1582 20802476 Leonidas Poulopoulos
    if len(datetimes) == 0:
1583 20802476 Leonidas Poulopoulos
        datetimes.append(datetime.datetime.now())
1584 0790d933 Leonidas Poulopoulos
    instTs = ET.SubElement(realmdataElement, "ts")
1585 0790d933 Leonidas Poulopoulos
    instTs.text = "%s" %max(datetimes).isoformat()
1586 0790d933 Leonidas Poulopoulos
    
1587 0790d933 Leonidas Poulopoulos
    
1588 c2b3014a Leonidas Poulopoulos
    return render_to_response("general/realm_data.xml", {"xml":to_xml(root)},context_instance=RequestContext(request,), mimetype="application/xml")
1589 c2b3014a Leonidas Poulopoulos
1590 cca6833d Leonidas Poulopoulos
@never_cache
1591 cca6833d Leonidas Poulopoulos
def servdata(request):
1592 cca6833d Leonidas Poulopoulos
    root = {}
1593 cca6833d Leonidas Poulopoulos
    hosts = InstServer.objects.all()
1594 cca6833d Leonidas Poulopoulos
    insts = Institution.objects.all()
1595 cca6833d Leonidas Poulopoulos
1596 cca6833d Leonidas Poulopoulos
    clients = hosts.filter(ertype__in=[2,3])
1597 cca6833d Leonidas Poulopoulos
    if clients:
1598 cca6833d Leonidas Poulopoulos
        root['clients'] = {}
1599 cca6833d Leonidas Poulopoulos
    for srv in clients:
1600 cca6833d Leonidas Poulopoulos
        srv_id = getSrvIdentifier(srv, "client_")
1601 cca6833d Leonidas Poulopoulos
        srv_dict = {}
1602 cca6833d Leonidas Poulopoulos
        srv_dict['host'] = srv.host
1603 cca6833d Leonidas Poulopoulos
        if srv.name:
1604 cca6833d Leonidas Poulopoulos
            srv_dict['label'] = srv.name
1605 cca6833d Leonidas Poulopoulos
        srv_dict['secret'] = srv.secret
1606 cca6833d Leonidas Poulopoulos
        root['clients'].update({srv_id: srv_dict})
1607 cca6833d Leonidas Poulopoulos
1608 cca6833d Leonidas Poulopoulos
    servers = hosts.filter(ertype__in=[1,3])
1609 cca6833d Leonidas Poulopoulos
    if servers:
1610 cca6833d Leonidas Poulopoulos
        root['servers'] = {}
1611 cca6833d Leonidas Poulopoulos
    for srv in servers:
1612 cca6833d Leonidas Poulopoulos
        srv_id = getSrvIdentifier(srv, "server_")
1613 cca6833d Leonidas Poulopoulos
        srv_dict = {}
1614 cca6833d Leonidas Poulopoulos
        srv_dict['rad_pkt_type'] = srv.rad_pkt_type
1615 cca6833d Leonidas Poulopoulos
        if srv.rad_pkt_type.find("auth") != -1:
1616 cca6833d Leonidas Poulopoulos
            srv_dict['auth_port'] = srv.auth_port
1617 cca6833d Leonidas Poulopoulos
        if srv.rad_pkt_type.find("acct") != -1:
1618 cca6833d Leonidas Poulopoulos
            srv_dict['acct_port'] = srv.acct_port
1619 cca6833d Leonidas Poulopoulos
        srv_dict['host'] = srv.host
1620 cca6833d Leonidas Poulopoulos
        if srv.name:
1621 cca6833d Leonidas Poulopoulos
            srv_dict['label'] = srv.name
1622 cca6833d Leonidas Poulopoulos
        srv_dict['secret'] = srv.secret
1623 cca6833d Leonidas Poulopoulos
        srv_dict['status_server'] = bool(srv.status_server)
1624 cca6833d Leonidas Poulopoulos
        root['servers'].update({srv_id: srv_dict})
1625 cca6833d Leonidas Poulopoulos
1626 cca6833d Leonidas Poulopoulos
    if insts:
1627 cca6833d Leonidas Poulopoulos
        root['institutions'] = []
1628 cca6833d Leonidas Poulopoulos
    for inst in insts:
1629 cca6833d Leonidas Poulopoulos
        inst_dict = {}
1630 cca6833d Leonidas Poulopoulos
        if not hasattr(inst, "institutiondetails"):
1631 cca6833d Leonidas Poulopoulos
            continue
1632 cca6833d Leonidas Poulopoulos
        if hasattr(inst.institutiondetails, "oper_name") and \
1633 cca6833d Leonidas Poulopoulos
                inst.institutiondetails.oper_name:
1634 cca6833d Leonidas Poulopoulos
            inst_dict['id'] = inst.institutiondetails.oper_name
1635 cca6833d Leonidas Poulopoulos
        inst_dict['type'] = inst.ertype
1636 cca6833d Leonidas Poulopoulos
        if inst.ertype in (2, 3):
1637 cca6833d Leonidas Poulopoulos
            inst_clients = inst.instserver_set.filter(ertype__in=[2, 3])
1638 cca6833d Leonidas Poulopoulos
            if inst_clients:
1639 cca6833d Leonidas Poulopoulos
                inst_dict['clients'] = [getSrvIdentifier(srv, "client_") for
1640 cca6833d Leonidas Poulopoulos
                                        srv in inst_clients]
1641 cca6833d Leonidas Poulopoulos
        if inst.ertype in (1, 3):
1642 cca6833d Leonidas Poulopoulos
            inst_realms = inst.instrealm_set.all()
1643 cca6833d Leonidas Poulopoulos
            if inst_realms:
1644 cca6833d Leonidas Poulopoulos
                inst_dict['realms'] = {}
1645 cca6833d Leonidas Poulopoulos
            for realm in inst_realms:
1646 cca6833d Leonidas Poulopoulos
                rdict = {}
1647 cca6833d Leonidas Poulopoulos
                rdict[realm.realm] = {}
1648 cca6833d Leonidas Poulopoulos
                rdict[realm.realm]['proxy_to'] = [getSrvIdentifier(proxy, "server_") for
1649 cca6833d Leonidas Poulopoulos
                                                  proxy in realm.proxyto.all()]
1650 cca6833d Leonidas Poulopoulos
                inst_dict['realms'].update(rdict)
1651 cca6833d Leonidas Poulopoulos
        root['institutions'].append(inst_dict)
1652 cca6833d Leonidas Poulopoulos
1653 cca6833d Leonidas Poulopoulos
1654 cca6833d Leonidas Poulopoulos
    if 'HTTP_ACCEPT' in request.META:
1655 cca6833d Leonidas Poulopoulos
        ret_mimetype = request.META.get('HTTP_ACCEPT')
1656 cca6833d Leonidas Poulopoulos
    else:
1657 cca6833d Leonidas Poulopoulos
        ret_mimetype = "text/yaml"
1658 cca6833d Leonidas Poulopoulos
1659 cca6833d Leonidas Poulopoulos
    if ret_mimetype.find("json") != -1:
1660 cca6833d Leonidas Poulopoulos
        return HttpResponse(json.dumps(root),
1661 cca6833d Leonidas Poulopoulos
                            mimetype=ret_mimetype)
1662 cca6833d Leonidas Poulopoulos
    else:
1663 cca6833d Leonidas Poulopoulos
        if ret_mimetype.find("yaml") == -1:
1664 cca6833d Leonidas Poulopoulos
            ret_mimetype = "text/yaml"
1665 cca6833d Leonidas Poulopoulos
        from yaml import dump
1666 cca6833d Leonidas Poulopoulos
        try:
1667 cca6833d Leonidas Poulopoulos
            from yaml import CDumper as Dumper, \
1668 cca6833d Leonidas Poulopoulos
                CSafeDumper as SafeDumper
1669 cca6833d Leonidas Poulopoulos
        except ImportError:
1670 cca6833d Leonidas Poulopoulos
            from yaml import Dumper, SafeDumper
1671 cca6833d Leonidas Poulopoulos
        return HttpResponse(dump(root,
1672 cca6833d Leonidas Poulopoulos
                                 Dumper=SafeDumper,
1673 cca6833d Leonidas Poulopoulos
                                 default_flow_style=False),
1674 cca6833d Leonidas Poulopoulos
                            mimetype=ret_mimetype)
1675 cca6833d Leonidas Poulopoulos
1676 cca6833d Leonidas Poulopoulos
@never_cache
1677 cca6833d Leonidas Poulopoulos
def adminlist(request):
1678 cca6833d Leonidas Poulopoulos
    users = User.objects.all()
1679 cca6833d Leonidas Poulopoulos
    data = [
1680 cca6833d Leonidas Poulopoulos
        (u.get_profile().institution.get_name('el'),
1681 cca6833d Leonidas Poulopoulos
         u.first_name + " " + u.last_name,
1682 cca6833d Leonidas Poulopoulos
         m)
1683 cca6833d Leonidas Poulopoulos
        for u in users if
1684 cca6833d Leonidas Poulopoulos
        len(u.registrationprofile_set.all()) > 0 and
1685 cca6833d Leonidas Poulopoulos
        u.registrationprofile_set.all()[0].activation_key == "ALREADY_ACTIVATED"
1686 cca6833d Leonidas Poulopoulos
        for m in u.email.split(';')
1687 cca6833d Leonidas Poulopoulos
        ]
1688 cca6833d Leonidas Poulopoulos
    data.sort(key=lambda d: unicode(d[0]))
1689 cca6833d Leonidas Poulopoulos
    resp_body = ""
1690 cca6833d Leonidas Poulopoulos
    for (foreas, onoma, email) in data:
1691 cca6833d Leonidas Poulopoulos
        resp_body += u'{email}\t{onoma}'.format(
1692 cca6833d Leonidas Poulopoulos
            email=email,
1693 cca6833d Leonidas Poulopoulos
            onoma=onoma
1694 cca6833d Leonidas Poulopoulos
            ) \
1695 cca6833d Leonidas Poulopoulos
            + "\n"
1696 cca6833d Leonidas Poulopoulos
    return HttpResponse(resp_body,
1697 cca6833d Leonidas Poulopoulos
                        mimetype="text/plain")
1698 cca6833d Leonidas Poulopoulos
1699 cca6833d Leonidas Poulopoulos
1700 c2b3014a Leonidas Poulopoulos
def to_xml(ele, encoding="UTF-8"):
1701 c2b3014a Leonidas Poulopoulos
    "Convert and return the XML for an *ele* (:class:`~xml.etree.ElementTree.Element`) with specified *encoding*."
1702 c2b3014a Leonidas Poulopoulos
    xml = ET.tostring(ele, encoding)
1703 c2b3014a Leonidas Poulopoulos
    return xml if xml.startswith('<?xml') else '<?xml version="1.0" encoding="%s"?>%s' % (encoding, xml)
1704 c2b3014a Leonidas Poulopoulos
    
1705 cca6833d Leonidas Poulopoulos
def getSrvIdentifier(srv, prefix):
1706 cca6833d Leonidas Poulopoulos
    if not hasattr(srv, "id"):
1707 cca6833d Leonidas Poulopoulos
        return None
1708 cca6833d Leonidas Poulopoulos
    retid = "{0}{1:d}".format(prefix,
1709 cca6833d Leonidas Poulopoulos
                              srv.id)
1710 cca6833d Leonidas Poulopoulos
    if hasattr(srv, "name") and srv.name:
1711 cca6833d Leonidas Poulopoulos
        from django.template.defaultfilters import slugify
1712 cca6833d Leonidas Poulopoulos
        retid = "{0}_{1}".format(retid,
1713 cca6833d Leonidas Poulopoulos
                                 slugify(srv.name))
1714 cca6833d Leonidas Poulopoulos
    return retid
1715 cca6833d Leonidas Poulopoulos
1716 cca6833d Leonidas Poulopoulos
1717 38f2278d Leonidas Poulopoulos
def getInstContacts(inst):
1718 38f2278d Leonidas Poulopoulos
    contacts = InstitutionContactPool.objects.filter(institution=inst)
1719 38f2278d Leonidas Poulopoulos
    contact_pks = []
1720 38f2278d Leonidas Poulopoulos
    for contact in contacts:
1721 38f2278d Leonidas Poulopoulos
        contact_pks.append(contact.contact.pk)
1722 38f2278d Leonidas Poulopoulos
    return list(set(contact_pks))
1723 38f2278d Leonidas Poulopoulos
1724 41f67637 Leonidas Poulopoulos
def getInstServers(inst, idpsp=False):
1725 04df82f7 Leonidas Poulopoulos
    servers = InstServer.objects.filter(instid=inst)
1726 41f67637 Leonidas Poulopoulos
    if idpsp:
1727 41f67637 Leonidas Poulopoulos
        servers = servers.filter(ertype__in=[1,3])
1728 04df82f7 Leonidas Poulopoulos
    server_pks = []
1729 04df82f7 Leonidas Poulopoulos
    for server in servers:
1730 04df82f7 Leonidas Poulopoulos
        server_pks.append(server.pk)
1731 04df82f7 Leonidas Poulopoulos
    return list(set(server_pks))
1732 04df82f7 Leonidas Poulopoulos
1733 04df82f7 Leonidas Poulopoulos
1734 af9d484b Leonidas Poulopoulos
def rad(x):
1735 c2b3014a Leonidas Poulopoulos
    return x*math.pi/180
1736 7973b176 Leonidas Poulopoulos
1737 7973b176 Leonidas Poulopoulos
def send_new_mail(subject, message, from_email, recipient_list, bcc_list):
1738 7973b176 Leonidas Poulopoulos
    return EmailMessage(subject, message, from_email, recipient_list, bcc_list).send()
1739 7973b176 Leonidas Poulopoulos
1740 baa68271 Leonidas Poulopoulos
def lookupShibAttr(attrmap, requestMeta):
1741 baa68271 Leonidas Poulopoulos
    for attr in attrmap:
1742 d1874bce Leonidas Poulopoulos
        if (attr in requestMeta.keys()):
1743 d1874bce Leonidas Poulopoulos
            if len(requestMeta[attr]) > 0:
1744 d1874bce Leonidas Poulopoulos
                return requestMeta[attr]
1745 d1874bce Leonidas Poulopoulos
    return ''
1746 d1874bce Leonidas Poulopoulos
1747 c666e0f0 Leonidas Poulopoulos
1748 c666e0f0 Leonidas Poulopoulos