-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCA-Repository-Server-v1.py
1828 lines (1440 loc) · 78.9 KB
/
CA-Repository-Server-v1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, render_template, request, session, redirect, url_for, g, flash
from werkzeug.utils import secure_filename
import os
CARepository = Flask(__name__)
import datetime
import json
# from pyld import jsonld
from markupsafe import escape
from owlready2 import *
from rdflib import Graph
# modules for measuring distance between text in Indicators
import gensim
import numpy as np
import nltk
from nltk.tokenize import word_tokenize, sent_tokenize
# global variables to be used in a session
global g_user # need to know who the user is that is logged in
global convLocatedIn # converts location name into object
global g_organization # selected organization for the user
global g_impactModel # selected impact model for the organization
global cidsServer
convLocatedIn = dict()
# definitions of database paths
path = "/Users/markfox/Dropbox/CSSE Folder/Projects/Common Approach/Repository/db/"
db = "cidsrepository.sqlite3"
dbfile = path + db
# from Crypto.Cipher import AES
@CARepository.context_processor
def injectKeyVariables() :
global g_user, g_organization, g_impactModel, cidsServer
return(dict(user=g_user,
userGname= g_user.forPerson.givenName if g_user and g_user.forPerson else "" ,
userFname= g_user.forPerson.familyName if g_user and g_user.forPerson else "" ,
userEmail= g_user.hasEmail if g_user else "",
organization = g_organization,
orgName= g_organization.hasLegalName if g_organization else "",
impactModel = g_impactModel ,
userType = g_user.userType if g_user else "",
superUser = cidsrep.superuser,
adminUser = cidsrep.admin,
editorUser = cidsrep.editor,
researcherUser = cidsrep.researcher ,
convertYMDtoDTD = convertYMDtoDTD ,
convertDTDtoYMD = convertDTDtoYMD ))
# ------------------------------ Login/logout/Save/logging -------------------------------
@CARepository.route('/', methods=['GET'])
def index() :
global g_user, g_organization, g_impactModel, cidsServer
return(render_template('index.html'))
@CARepository.route('/Login', methods=['POST'])
def login() :
global g_user, g_organization, g_impactModel, cidsServer
valid_user = valid_login(request.form['hasEmail'],request.form['hasPassword'])
if valid_user :
log_the_user_in(valid_user)
if g_user.userType in [cidsrep.admin, cidsrep.editor]:
if len(g_organization.hasImpactModel) > 1 :
impactModels = [ (im.iri, im.hasName, im.hasDescription) for im in g_organization.hasImpactModel ]
return(render_template("impactModelSelect.html", action="display", impactModels=impactModels, message="Please select Impact Model to edit."))
g_impactModel = g_organization.hasImpactModel[0]
return(renderImpactModel(g_impactModel, "display", "", g_organization.hasID.hasIdentifier + " Impact Model Configuration."))
return(render_template('main.html'))
else :
return(render_template('index.html', message="Login Failed: Invalid email or password"))
@CARepository.route('/Logout')
def logout():
global g_user, g_organization, g_impactModel, cidsServer
# remove the user Email from the session if it's there
session.pop('hasEmail', None)
# set session user to None
g_user = None
g_organization = None
g.userType = None
cidsServer.save()
return redirect(url_for('index'))
@CARepository.route('/DumpInstances')
def saveCADR() :
global g_user, g_organization, g_impactModel, cidsServer
print("saving cadr instances")
cadrfile = path + "/cadrarchive/cadr.rdf" + "." + str(datetime.datetime.now())
cadr.save(file=cadrfile) # saves as rdf/xml as default
return(render_template('main.html', message="CADR saved as " + cadrfile))
def logIndividual(comment, *arg) :
global g_user, g_organization, g_impactModel, cidsServer
logchan = open("logs/cadrChanges.log" + str(datetime.date.today()), 'a+')
for ind in arg :
if ind :
print("logIndividual ", comment, ": IRI=", ind.iri)
js = cnvIndJSONLD(ind, comment=comment)
logchan.write("\n\n" + js)
logchan.close()
# cidsServer.save() # uncomment when system is ready to really run
# -------------------- JSON conversion functions ----------------------------------------
@CARepository.route('/RequestLoadJSONLD', methods=['GET'])
def requestLoadJSONLD() :
global g_user, g_organization, g_impactModel, cidsServer
# kick user out if they are not a superuser - should not happen as they would not get access to the registerorganization page
if (g_user.userType != cidsrep.superuser) and (g_user.userType != cidsrep.admin) :
return(render_template('main.html', message="You do not have access rights for loading data."))
return(render_template('loadJsonld.html', path="http://localhost:5000/LoadJSONLD"))
@CARepository.route('/LoadJSONLD', methods=['POST', 'GET'])
def loadJSONLD() :
global g_user, g_organization, g_impactModel, convLocatedIn, cidsServer
global UPLOAD_FOLDER, ALLOWED_EXTENSIONS
if request.method != 'POST': return(render_template('main.html', message="Incorrect post method."))
if not g_organization : return(render_template('main.html', message="No organization selected."))
# Part 1: save the file to the subdirectory for the organization
# * file contents cannot be binary!!! ascii string
# check if the post request has the file part
if not 'file' in request.files :
flash('No file part')
return(redirect(request.url))
file = request.files['file']
# if user does not select file
if file.filename == '':
flash('No selected file')
return(redirect(request.url))
if not (file and allowed_file(file.filename)): render_template('main.html', message="File extension not allowed.")
# store the file in the organization's upload directory
filename = secure_filename(file.filename)
print("Filename: ", filename)
uploadDirectory = UPLOAD_FOLDER + '/' + g_organization.hasID.hasIdentifier
if not os.path.exists(uploadDirectory): os.makedirs(uploadDirectory)
path = os.path.join(uploadDirectory, filename)
file.save(path)
# Part 2: convert json-ld into n-triple and then load into OWLReady2
# Next is to read and convert the file using rdflib serialization
g = Graph()
g.parse(path, format="json-ld")
nt = g.serialize(format="nt")
nt = nt.decode('ascii')
ntpath, ext = path.split(".")
ntpath = ntpath + ".owl" # have to save with owl extension for owlready2 to compile entities properly
with open(ntpath, 'w') as f:
f.write(nt)
f.close()
uploadns = cidsServer.get_ontology(ntpath) # now load the indiv into owlready2
uploadns.load()
# get ids of and log each one by re-reading the json-ld file and pulling ids
with open(path, "r") as f: js = json.load(f)
if type(js) != list : js = [js]
for ind in js :
id = ind["@id"]
print("Loaded ", id)
if id :
idp = cidsServer.search_one(iri=id)
if not idp :
print("Can't find ", id)
else :
logIndividual("Upload", idp)
return(render_template('main.html', message="Upload complete: " + filename))
def loadNtriples(js) :
global g_user, g_organization, g_impactModel, convLocatedIn, cidsServer
graph = cidsServer.as_rdflib_graph()
jsonDict = json.loads(js)
id = jsonDict["@id"]
typ = jsonDict["@type"]
ind = cadr.search_one(iri=id)
if ind :
# check that the type is consistent, if not generate an errot
ns, entity = rdflib.namespace.split_uri(ind)
# delete entity and replace with new data
logIndividual("Load JSONLD - delete", ind) # log it so that it can be retrieved if need
delete_entity(ind)
# create individual of the correct type
type_ns, type_entity = rdflib.namespace.split_uri(typ)
ind_ns, ind_entity = rdflib.namespace.split_uri(ind)
tns = rdflib.Namespace(type_ns)
ins = rdflib.Namespace(ind_ns)
with cadr :
graph.add((ins[ind_entity], RDF.type, tns[type_entity]))
# go through keys and produce corresponding attribute
# ADD HANDLING OF VALUE THAT IS A LIST
for key in jsonDict :
if (key != "@id") and (key != "@type") and (key != "@context") :
pns, pentity = rdflib.namespace.split_uri(key)
rdflib_pns = rdflib.Namespace(pns)
values = jsonDict[key] if type(jsonDict[key]) is list else [jsonDict[key]]
vns, ventity = rdflib.namespace.split_uri(jsonDict[key])
for value in values :
rdflib_vns = rdflib.Namespace(vns)
with cadr:
graph.add((ins[ind_entity], rdflib_pns[pentity], rdflib_vns(ventity)))
def cnvIndJSONLD(ind, comment=None, annotate=True) :
global g_user, g_organization, g_impactModel, convLocatedIn, cidsServer
js = [ ("@id", ind.iri) ]
for typ in ind.is_a : js.append(("@type", typ.iri))
for prop in ind.get_properties() :
for val in prop[ind] :
if isinstance(val, owl.Thing) : js.append((str(prop.iri), str(val.iri)))
else : js.append((str(prop.iri), str(val))) # need to convert to xsd format
# now convert multiples of same attribute into single attribute with list of values
jsd = dict()
for att, val in js :
if att in jsd :
jsd[att].append(val)
else :
jsd[att] = [val]
# if annotate is true then add modification properties
if annotate :
jsd["<http://purl.org/dc/terms/modified>"] = [str(datetime.datetime.now())]
jsd['<http://ontology.eil.utoronto.ca/cids/cids#modifiedBy>'] = [g_user.hasEmail]
if comment : jsd["<http://purl.org/dc/terms/description"] = [comment]
# should convert to string for printing
jsonString = '{ "@context : \n { "xsd": "http://www.w3.org/2001/XMLSchema#", \n"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", \n"rdfs": "http://www.w3.org/2000/01/rdf-schema#" }'
for att in jsd :
val = jsd[att]
jsonString += ' ,\n "' + att + '": '
if len(val) == 1:
jsonString += '"' + val[0] + '"'
else :
count = 0
jsonString += '[ '
for v in val :
jsonString += '"' + v + '"'
count += 1
if count < len(val) : jsonString += ' ,'
jsonString += ' ]'
jsonString += '\n}'
return(jsonString)
#--------------- User --------------------------------------------------------------------
@CARepository.route('/AddUser')
def addUser() :
global g_user, g_organization, g_impactModel, cidsServer
if g_user.userType == cidsrep.superuser : return(render_template('userEdit.html', action='add'))
if g_user.userType == cidsrep.admin :
return(render_template('userEdit.html', orgIDValue= g_user.forOrganization.hasID.hasIdentifier,
readonly="readonly", action="add", path=path))
path = "http://localhost:5000/UpdateUser"
return(render_template('main.html', message="Error: User does not have permission to add a User."))
@CARepository.route('/SelectUser', methods=['GET'])
def selectUser() :
global g_user, g_organization, g_impactModel, cidsServer
if (g_user.userType != cidsrep.superuser) and (g_user.userType != cidsrep.admin) :
return(render_template('main.html', message="You do not have access rights to add a User."))
action = request.args.get('action')
print("Action: ", action)
if (action == "edit") or (action == "display") :
path = "http://localhost:5000/EditUser"
elif action == "delete" :
path = "http://localhost:5000/DeleteUser"
else :
return(render_template('main.html', message="Error: Unknown User action: " + str(action)))
if (g_user.userType == cidsrep.superuser) : return(render_template('userSelect.html', path=path, action=action))
users = dict()
print("gorg=", g_organization)
for user in cadr.search(type=cidsrep.User, forOrganization=g_organization) :
value = user.hasEmail + " [ "
if user.forPerson :
if user.forPerson.familyName : value += user.forPerson.familyName + ", "
if user.forPerson.givenName : value += user.forPerson.givenName
value += " ]"
users[user.hasEmail] = value
return(render_template('userSelect.html', path=path, action=action, users=users))
@CARepository.route('/EditUser', methods=['POST'])
def editUser() :
global g_user, g_organization, g_impactModel, cidsServer
path = "http://localhost:5000/UpdateUser"
if (g_user.userType == cidsrep.researcher) or (g_user.userType == cidsrep.editor):
return(render_template('main.html', message="Error: " + g_user.hasEmail + " does not have permission to edit a User."))
euser = cadr.search_one(type=cidsrep.User, hasEmail=request.form['hasEmail'])
if not euser :
return(render_template('main.html', message="Error: User " + request.form['hasEmail'] + " does not exist."))
if (g_user.userType == cidsrep.admin) and (g_user.forOrganization != euser.forOrganization) :
return(render_template('main.html', message="Error: User " + g_user.hasEmail + " and " + request.form['hasEmail'] + " organizations do not match."))
action = request.form['action']
readonly = "readonly" if g_user != cidsrep.superuser else ""
return(renderUser(euser, action, path, readonly, ""))
@CARepository.route('/UpdateUser', methods=['POST'])
def updateUser() :
global g_user, g_organization, g_impactModel, cidsServer
if (g_user.userType == cidsrep.superuser) or (g_user.userType == cidsrep.admin):
readonly = "readonly" if g_user != cidsrep.superuser else ""
euser = cadr.search_one(type=cidsrep.User, hasEmail=request.form['hasEmail'])
if not euser : euser = cidsrep.User(namespace=cadr, forPerson= cids.Person(namespace=cadr))
euser.hasEmail = request.form['hasEmail']
euser.hasPassword = request.form['hasPassword']
euser.forPerson.givenName = request.form['givenName']
euser.forPerson.familyName = request.form['familyName']
if not euser.forPerson.hasTelephone :
pn = ic.PhoneNumber(namespace=cadr)
euser.forPerson.hasTelephone = [pn]
else :
pn = euser.forPerson.hasTelephone[0]
pn.hasPhoneNumber = request.form['hasPhoneNumber']
euser.forOrganization = g_user.forOrganization if g_user.userType == cidsrep.admin else getOrganization(request.form['orgID'])
logIndividual("Update User", euser, euser.forPerson, pn)
return(renderUser(euser, "display", "", readonly, "User " + euser.hasEmail + " added."))
return(render_template('main.html', message="Error: User does not have permission to add a User."))
@CARepository.route('/DeleteUser', methods=['POST'])
def deleteUser() :
global g_user, g_organization, g_impactModel, cidsServer
if (g_user.userType != cidsrep.superuser) and (g_user.userType != cidsrep.admin) :
return(render_template('main.html', message="You do not have access rights to add a User."))
euser = cadr.search_one(type=cidsrep.User, hasEmail=request.form['hasEmail'])
if euser :
if (g_user.userType == cidsrep.admin) and (euser.forOrganization != g_user.forOrganization) :
return(render_template('main.html', message="You can only delete Users associated with your organization."))
logIndividual("Deleted User", euser)
destroy_entity(euser)
return(render_template('menu.html', message="Deleted user " + request.form['hasEmail'] + "."))
return(render_template('main.html', message="Error: User " + request.form['hasEmail'] + " does not exist."))
def renderUser(user, action, path, readonly, message) :
global g_user, g_organization, g_impactModel, cidsServer
per = user.forPerson
pn = per.hasTelephone[0].hasPhoneNumber if per.hasTelephone else ""
o = user.forOrganization
bn = o.hasID.hasIdentifier
return(render_template('userUpdate.html', readonly=readonly, action=action, message=message, path=path,
hasEmailValue= user.hasEmail,
hasPasswordValue= user.hasPassword,
givenNameValue= user.forPerson.givenName,
familyNameValue= user.forPerson.familyName,
hasPhoneNumberValue= pn,
orgIDValue= bn,
userTypeValue = user.userType
))
# -------------------- Organization -------------------------------------------------------
@CARepository.route('/AddOrganization', methods=['GET'])
def addOrganization() :
global g_user, g_organization, g_impactModel, cidsServer
user = cadr.search_one(type=cidsrep.User, hasEmail=session['hasEmail'])
# kick user out if they are not a superuser - should not happen as they would not get access to the registerorganization page
if user.userType != cidsrep.superuser :
return(render_template('main.html',
message="You do not have access rights for Registering an Organization."))
return(render_template('organizationEdit.html', action='add', path="http://localhost:5000/UpdateOrganization"))
@CARepository.route('/SelectOrganization', methods=['GET'])
def selectOrganization() :
global g_user, g_organization, g_impactModel, cidsServer
if g_user.userType != cidsrep.superuser :
return(render_template('main.html', message="You do not have access rights for an Organization."))
action = request.args.get('action')
if action == "edit" :
path = "http://localhost:5000/EditOrganization"
elif action == "delete" :
path = "http://localhost:5000/DeleteOrganization"
else :
return(render_template('main.html', message="Error: Unknown Organization action: " + str(action)))
orgs = dict()
for og in cadr.search(type=cids.Organization) : orgs[og.hasID.hasIdentifier] = og.hasLegalName
return(render_template('organizationSelect.html', path=path, action=action, organizations=orgs))
@CARepository.route('/EditOrganization', methods=['POST', 'GET'])
def editOrganization() :
global g_user, g_organization, g_impactModel, cidsServer
action = request.args.get('action') or request.form['action']
path = "http://localhost:5000/UpdateOrganization"
# get organization for the current user
if g_user.userType == cidsrep.superuser :
if action == "display" :
if not g_organization : return(render_template('main.html', message="Organization not selected."))
o = g_organization
else :
o = getOrganization(request.form["orgID"])
g_organization = o
ro =""
elif g_user.userType == cidsrep.admin :
o = g_user.forOrganization
ro = "readonly"
else :
# kick user out if they are not a superuser or admin - should not happen as they would not get access to the registerorganization page
return(render_template('main.html', message="You do not have access rights for Registering/Editing an Organization."))
return(renderOrganization(o, action, path, ro, ""))
@CARepository.route('/UpdateOrganization', methods=['POST'])
def updateOrganization() :
global g_user, g_organization, g_impactModel, cidsServer
# kick user out if they are not a superuser - should not happen as they would not get access to the registerorganization page
if (request.form["action"] == "add") and (g_user.userType != cidsrep.superuser) :
return(render_template('main.html', message="You do not have access rights for Adding an Organization."))
# check that the organization does not already exist
oid = cadr.search_one(type=org.OrganizationID, hasIdentifier= request.form['orgID'])
if oid :
if request.form['action'] == 'add' : return(render_template('organizationUpdate.html', message="Error: Organization already exists."))
else :
if request.form['action'] == 'edit' : return(render_template('organizationUpdate.html', message="Error: Organization does not exist."))
readonly = "readonly" if g_user.userType != cidsrep.superuser else ""
if request.form['action'] == 'add' :
neworg = cids.Organization(namespace=cadr)
# create the OrganizationID and link
newid = org.OrganizationID(namespace=cadr)
newid.forOrganization = neworg
newid.hasIdentifier = request.form['orgID']
neworg.hasID = newid
neworg.dateCreated = datetime.datetime.now().isoformat()
# create impact model for common approach
im = cids.ImpactMeasurement(namespace=cadr, forOrganization=neworg, hasStakeholder=[],
hasOutcome=[], hasIndicator=[], hasImpactRisk=[], hasImpactReport=[], hasStakeholderOutcome=[])
neworg.hasImpactModel = [im]
g_organization = neworg
g_impactModel = im
elif request.form['action'] == 'edit' :
neworg = oid.forOrganization
newid = oid
else :
return(render_template('main.html', message="Error: unknown action for Organization."))
# Fill the instance of cids.Organization
neworg.hasLegalName = request.form['hasLegalName']
neworg.useOfFunds = request.form['useOfFunds']
neworg.hasDescription = request.form['hasDescription']
# Build the ic.Address instance and link
if not neworg.hasAddress :
addr = ic.Address(namespace=cadr)
neworg.hasAddress = [addr]
else :
addr = neworg.hasAddress[0]
print("address: ", addr, request.form['hasStreetNumber'])
addr.hasStreetNumber = request.form['hasStreetNumber']
addr.hasStreet = request.form['hasStreet']
addr.hasUnitNumber = request.form['hasUnitNumber']
addr.hasCityS = request.form['hasCityS']
addr.hasProvince = request.form['hasProvince']
addr.hasPostalCode = request.form['hasPostalCode']
# Build Phone number for the Organization
if not neworg.hasTelephone :
pn1 = ic.PhoneNumber(namespace=cadr)
neworg.hasTelephone = [pn1]
else :
pn1 = neworg.hasTelephone[0]
pn1.hasPhoneNumber = request.form['hasPhoneNumber']
# Build the contact as Person and link
if not neworg.hasContact :
contac = cids.Person(namespace=cadr)
neworg.hasContact = [contac]
else :
contac = neworg.hasContact[0]
contac.givenName = request.form['contactFirstName']
contac.familyName = request.form['contactLastName']
contac.hasEmail = request.form['contactEmail']
if not contac.hasTelephone :
pn2 = ic.PhoneNumber(namespace=cadr)
contac.hasTelephone = [pn2]
else :
pn2 = contac.hasTelephone[0]
pn2.hasPhoneNumber = request.form['contactPhoneNumber']
logIndividual("Update Organization", neworg, newid, addr, pn1, contac, pn2, neworg.hasImpactModel[0])
return(renderOrganization(neworg, "display", readonly, "Organization " + newid.hasIdentifier + " information saved."))
@CARepository.route('/DeleteOrganization', methods=['POST'])
def deleteOrganization() :
global g_user, g_organization, g_impactModel, cidsServer
if g_user.userType != cidsrep.superuser :
return(render_template('main.html', message="You do not have access rights for Deleting an Organization."))
oid = cadr.search_one(type=org.OrganizationID, hasIdentifier=request.form['orgID'])
og = oid.forOrganization
if oid :
logIndividual("Delete Organization", oid)
destroy_entity(oid)
if og :
logIndividual("DeleteOrganization", og)
destroy_entity(og)
if og or oid: return(render_template('main.html', message="Deleted organization " + request.form['orgID'] + "."))
return(render_template('main.html', message="Error: Organization " + request.form['orgID'] + " does not exist."))
def renderOrganization(o, action, path, readonly, message) :
global g_user, g_organization, g_impactModel, cidsServer
hasImpactModelValue = None
hasStreetNumberValue= ""
hasStreetValue= ""
hasUnitNumberValue= ""
hasCitySValue= ""
hasProvince= ""
hasPostalCodeValue= ""
if o.hasAddress :
hasStreetNumberValue= o.hasAddress[0].hasStreetNumber
hasStreetValue= o.hasAddress[0].hasStreet
hasUnitNumberValue= o.hasAddress[0].hasUnitNumber
hasCitySValue= o.hasAddress[0].hasCityS
hasProvince= o.hasAddress[0].hasProvince
hasPostalCodeValue= o.hasAddress[0].hasPostalCode
hasPhoneNumberValue= ""
if o.hasTelephone :
hasPhoneNumberValue= o.hasTelephone[0].hasPhoneNumber
contactFirstNameValue= ""
contactLastNameValue= ""
contactEmailValue= ""
contactPhoneNumberValue=""
if o.hasContact :
contactFirstNameValue= o.hasContact[0].givenName
contactLastNameValue= o.hasContact[0].familyName
contactEmailValue= o.hasContact[0].hasEmail
if o.hasContact[0].hasTelephone :
contactPhoneNumberValue= o.hasContact[0].hasTelephone[0].hasPhoneNumber
return(render_template('organizationEdit.html', readonly=readonly, action=action, path=path,
orgIDValue = o.hasID.hasIdentifier,
hasImpactModelValue = hasImpactModelValue,
hasLegalNameValue = o.hasLegalName,
hasDescriptionValue= o.hasDescription,
useOfFundsValue= o.useOfFunds,
hasStreetNumberValue= hasStreetNumberValue,
hasStreetValue= hasStreetValue,
hasUnitNumberValue= hasUnitNumberValue,
hasCitySValue= hasCitySValue,
hasProvince= hasProvince,
hasPostalCodeValue= hasPostalCodeValue,
hasPhoneNumberValue= hasPhoneNumberValue,
contactFirstNameValue= contactFirstNameValue,
contactLastNameValue= contactLastNameValue,
contactEmailValue= contactEmailValue,
contactPhoneNumberValue= contactPhoneNumberValue
))
#--------------- ImpactModel -------------------------------------------------------------
@CARepository.route('/AddImpactModel', methods=['GET'])
def addImpactModel() :
global g_user, g_organization, g_impactModel, convLocatedIn, cidsServer
if (g_user.userType == cidsrep.superuser) or (g_user.userType == cidsrep.admin):
path = "http://localhost:5000/UpdateImpactModel"
return(renderImpactModel(None, "add", path, g_organization.iri))
return(render_template('main.html', message="Error: User does not have permission to add an ImpactModel."))
@CARepository.route('/SelectImpactModel', methods=['GET'])
def selectImpactModel() :
global g_user, g_organization, g_impactModel, convLocatedIn, cidsServer
action = request.args.get('action')
if (action == "edit") or (action == "display") :
path = "http://localhost:5000/EditImpactModel"
elif action == "delete" :
path = "http://localhost:5000/DeleteImpactModel"
else :
return(render_template('main.html', message="Error: Unknown ImpactModel action: " + action))
if g_user.userType in [cidsrep.superuser, cidsrep.admin, cidsrep.editor]:
impactModels = [ (im.iri, im.hasName, im.hasDescription) for im in g_organization.hasImpactModel ]
return(render_template('ImpactModelSelect.html', path=path, impactModels=impactModels, action=action))
return(render_template('main.html', message="Error: " + g_user.hasEmail + " does not have permission to edit/display a Stakeholder."))
@CARepository.route('/EditImpactModel', methods=['POST'])
def editImpactModel() :
global g_user, g_organization, g_impactModel, convLocatedIn, cidsServer
action = request.form['action']
path = "http://localhost:5000/UpdateImpactModel"
if (g_user.userType == cidsrep.researcher) and (action != 'display') :
return(render_template('main.html', message="Error: User does not have permission to add/edit/delete a Stakeholder."))
if (g_user.userType == cidsrep.admin) or (g_user.userType == cidsrep.editor) :
g_organization = g_user.forOrganization
imIRI = request.form['imIRI']
if not imIRI :
return(render_template('main.html', message="Error: No impact model selected."))
im = cadr.search_one(iri=imIRI)
if not im :
return(render_template('main.html', message="Error: ImpactModel " + request.form['imIRI'] + " does not exist."))
if ((g_user.userType == cidsrep.admin) or (g_user.userType == cidsrep.editor)) and (g_user.forOrganization != im.forOrganization) :
return(render_template('main.html', message="Error: User " + g_user.hasEmail + " and ImpactModel " + request.form['imIRI'] + " organizations do not match."))
return(renderImpactModel(im, action, path, ""))
@CARepository.route('/UpdateImpactModel', methods=['POST'])
def updateImpactModel() :
global g_user, g_organization, g_impactModel, convLocatedIn, cidsServer
action = request.form['action']
if action == "add" :
imType = cids.search_one(iri=request.form["imIRI"])
im = cids[imType](namespace=cadr)
else :
im = cadr.search_one(iri=request.form['imIRI'])
if not im :
return(render_template('main.html', message="Error: editing a missing ImpactModel. " + imIRI))
im.hasName = request.form['hasName']
im.hasDescription = request.form['hasDescription']
logIndividual("Update ImpactModel", im)
return(renderImpactModel(im, "display", readonly, "ImpactModel " + im.hasName + " information saved."))
def renderImpactModel(im, action, path, message) :
global g_user, g_organization, g_impactModel, convLocatedIn, cidsServer
hasImpactModelTypeIRI = ""
impactModelTypes = []
for imtype in cids.search(subclass_of=cids.ImpactModel) :
if imtype != cids.ImpactModel :
if im and isinstance(im, imtype) : hasImpactModelTypeIRI = imtype.iri
impactModelTypes.append(imtype)
stakeholders = im.hasStakeholder if im else []
outcomes = im.hasOutcome if im else []
indicators = im.hasIndicator if im else []
hasNameValue = im.hasName if im else ""
hasDescriptionValue = im.hasDescription if im else ""
return(render_template('impactModelEdit.html', action=action, path=path, message=message,
impactModelTypes = impactModelTypes ,
stakeholders = stakeholders ,
indicators = indicators ,
outcomes = outcomes ,
hasNameValue = hasNameValue ,
hasDescriptionValue = hasDescriptionValue ,
hasImpactModelTypeIRI = hasImpactModelTypeIRI
))
#--------------- Stakeholder -------------------------------------------------------------
@CARepository.route('/AddStakeholder')
def addStakeholder() :
global g_user, g_organization, g_impactModel, convLocatedIn, cidsServer
if (g_user.userType == cidsrep.superuser) or (g_user.userType == cidsrep.admin):
path = "http://localhost:5000/UpdateStakeholder"
return(render_template('stakeholderEdit.html', path=path, action="add"))
return(render_template('main.html', message="Error: User does not have permission to add a Stakeholder."))
@CARepository.route('/SelectStakeholder', methods=['GET'])
def selectStakeholder() :
global g_user, g_organization, g_impactModel, convLocatedIn, cidsServer
action = request.args.get('action')
if (action == "edit") or (action == "display") :
path = "http://localhost:5000/EditStakeholder"
elif action == "delete" :
path = "http://localhost:5000/DeleteStakeholder"
else :
return(render_template('main.html', message="Error: Unknown Stakeholder action: " + action))
if (g_user.userType == cidsrep.superuser) :
return(render_template('stakeholderSelect.html', path=path, action=action))
if (g_user.userType == cidsrep.admin) or (g_user.userType == cidsrep.editor):
stakeholders = cadr.search(type=cids.Stakeholder, forOrganization=g_organization)
stkList = []
for stk in stakeholders : stkList.append(stk.hasName)
return(render_template('stakeholderSelect.html', path=path, stakeholders=stkList, action=action))
return(render_template('main.html', message="Error: " + g_user.hasEmail + " does not have permission to edit/display a Stakeholder."))
@CARepository.route('/EditStakeholder', methods=['POST', 'GET'])
def editStakeholder() :
global g_user, g_organization, g_impactModel, convLocatedIn, cidsServer
if request.method == 'POST':
action = request.form['action']
stkIRI = request.form['stkIRI']
else :
action = "display"
stkIRI = request.args.get('stkIRI')
path = "http://localhost:5000/UpdateStakeholder"
if (g_user.userType == cidsrep.researcher) and (action != 'display') :
return(render_template('main.html', message="Error: User does not have permission to add/edit/delete a Stakeholder."))
if (g_user.userType == cidsrep.admin) or (g_user.userType == cidsrep.editor) :
g_organization = g_user.forOrganization
stk = cadr.search_one(type=cids.Stakeholder, iri=stkIRI)
if not stk :
return(render_template('main.html', message="Error: Stakeholder " + request.form['hasName'] + " does not exist."))
if ((g_user.userType == cidsrep.admin) or (g_user.userType == cidsrep.editor)) and (g_user.forOrganization != stk.forOrganization) :
return(render_template('main.html', message="Error: User " + g_user.hasEmail + " and Stakeholder " + request.form['hasName'] + " organizations do not match."))
return(renderStakeholder(stk, action, path, ""))
@CARepository.route('/UpdateStakeholder', methods=['POST'])
def updateStakeholder() :
global g_user, g_organization, g_impactModel, convLocatedIn, cidsServer
action = request.form['action']
# check if user is permitted to add a Stakeholder
if (g_user.userType != cidsrep.superuser) and (g_user.userType != cidsrep.admin):
return(render_template('main.html', message="Error: User does not have permission to add/update a Stakeholder."))
# check if stakeholder already exists for the org and doing add
stk = cadr.search_one(type=cids.Stakeholder, iri=request.form['stkIRI'], forOrganization=g_organization)
if stk and (request.form['action'] == 'add') :
return(render_template('main.html', message="Error: Stakeholder with that name already exists."))
if not stk and (request.form['action'] == 'edit') :
return(render_template('main.html', message="Error: Stakeholder not found in database."))
if request.form['action'] == 'add' : # create new stakeholder
stk = cids.Stakeholder(namespace=cadr)
stk.hasName = request.form['hasName']
stk.forOrganization = g_organization
g_impactModel.hasStakeholder.append(stk)
stk.hasDescription = request.form['hasDescription']
stk.located_in = [convLocatedIn[request.form['located_in']]]
logIndividual("Update Stakeholder", stk, g_impactModel)
return(renderStakeholder(stk, "display", "", " Stakeholder " + action + " successful."))
@CARepository.route('/DeleteStakeholder', methods=['POST'])
def deleteStakeholder() :
global g_user, g_organization, g_impactModel, cidsServer
if (g_user.userType != cidsrep.superuser) and (g_user.userType != cidsrep.admin):
return(render_template('main.html', message="Error: User does not have permission to delete a Stakeholder."))
stk = cadr.search_one(type=cids.Stakeholder, forOrganization=g_organization, hasName=request.form['hasName'])
if not stk : return(render_template('main.html', message="Error: Stakeholder " + request.form['hasName'] + " does not exist."))
if (g_user.userType == cidsrep.admin) and (g_user.forOrganization != stk.forOrganization) :
return(render_template('main.html', message="Error: User does not have permission to delete a Stakeholder not associated with their Organization."))
logIndividual("Delete Stakeholder", stk)
destroy_entity(stk)
return(render_template('main.html', message="Deleted Stakeholder " + request.form['hasName'] + "."))
def renderStakeholder(stk, action, path, message) :
return(render_template('stakeholderEdit.html', action=action, path=path, message=message,
stkIRIValue = stk.iri ,
hasNameValue = stk.hasName,
hasDescriptionValue= stk.hasDescription,
located_inValue= stk.located_in[0].has_Name
))
#--------------- Indicator -------------------------------------------------------------
@CARepository.route('/AddIndicator', methods=['GET'])
def addIndicator() :
global g_user, g_organization, g_impactModel, convLocatedIn, cidsServer
orgID = g_organization.hasID.hasIdentifier if g_organization and g_organization.hasID else None
if (g_user.userType == cidsrep.superuser) : return(render_template('indicatorEdit.html', orgIDValue=orgID, action="add", ))
if (g_user.userType == cidsrep.admin) and (g_user.forOrganization) :
g_organization = g_user.forOrganization
orgID = g_organization.hasID.hasIdentifier if g_organization and g_organization.hasID else None
return(render_template('indicatorEdit.html', orgIDValue=orgID, readonly="readonly", action="add", path="http://localhost:5000/UpdateIndicator"))
return(render_template('main.html', message="Error: User does not have permission to add an Indicator."))
@CARepository.route('/SelectIndicator', methods=['GET'])
def selectIndicator() :
global g_user, g_organization, g_impactModel, convLocatedIn, cidsServer
action = request.args.get('action')
# check if user is permitted to add an Indicator
if not g_user.userType in [cidsrep.superuser, cidsrep.admin, cidsrep.editor]:
return(render_template('main.html', message="Error: User does not have permission to add an Indicator."))
# reset g_organization to be the same as the user's
if (g_user.userType == cidsrep.admin) or (g_user.userType == cidsrep.editor) : g_organization = g_user.forOrganization
if (action == "edit") or (action == "display") :
path = "http://localhost:5000/EditIndicator"
elif action == "delete" :
path = "http://localhost:5000/DeleteIndicator"
elif action == "compare" :
path = "http://localhost:5000/SimilarIndicator"
else :
return(render_template('main.html', message="Error: Unknown Indicator action: " + action))
inds = cadr.search(type=cids.Indicator, definedBy=g_organization) if g_organization else []
if not inds and (action == "display"): return(render_template('main.html', message="Error: No indicators to display."))
indSelect = dict()
for ind in inds: indSelect[ind.iri] = ind.hasName
return(render_template('indicatorSelect.html', path=path, action=action, indicators=indSelect))
@CARepository.route('/EditIndicator', methods=['POST', 'GET'])
def editIndicator() :
global g_user, g_organization, g_impactModel, convLocatedIn, cidsServer
if request.method == 'POST':
action = request.form['action']
indIRI = request.form['indIRI']
else :
action = "display"
indIRI = request.args.get('indIRI')
print("indIRI=", indIRI)
path = "http://localhost:5000/UpdateIndicator"
if (g_user.userType == cidsrep.Researcher) and (action != 'display') :
return(render_template('main.html', message="Error: User does not have permission to add/edit/delete an Indicator."))
ind = cadr.search_one(type=cids.Indicator, iri=indIRI)
if not ind : return(render_template('main.html', message="Error: Edit Indicator " + indIRI + " does not exist."))
if not canModify(g_user, ind) :
return(render_template('main.html', message="Error: User does not have permission to add/edit/delete the Indicator."))
return(renderIndicator(ind, action, path, "readonly", ""))
def canModify(user, entity) :
global g_user, g_organization, g_impactModel, convLocatedIn, cidsServer
og = entity.definedBy if type(entity) in [cids.Indicator, cids.Outcome] else entity.forOrganization
if user.userType == cidsrep.superuser : return(True)
elif user.userType == cidsrep.admin :
if user.forOrganization == og : return(True)
elif user.userType == cidsrep.editor :
if user.forOrganization == og: return(True)
return(False)
@CARepository.route('/UpdateIndicator', methods=['POST'])
def updateIndicator() :
global g_user, g_organization, g_impactModel, convLocatedIn, cidsServer
# check if user is permitted to add an Indicator
if not g_user.userType in [cidsrep.superuser, cidsrep.admin, cidsrep.editor]:
return(render_template('main.html', message="Error: User does not have permission to add/update an Indicator."))
# verify returned orgID
if (g_user.userType == cidsrep.admin) or (g_user.userType == cidsrep.editor) :
if request.form['orgID'] != g_user.forOrganization.hasID.hasIdentifier :
return(render_template('main.html', message="Error: Organization ID mismatch: req=" + request.form['orgID'] + "; g_org=" + g_user.forOrganization.hasID.hasIdentifier ))
else:
oid = cadr.search_one(type=org.OrganizationID, hasIdentifier=request.form['orgID']) if request.form['orgID'] else None
g_organization = oid.forOrganization if oid else None # set g_organization to superuser specified organization
# check if Indicator already exists for the org and doing add
indIRI = flask.unescape(request.form['indIRI'])
ind = cadr.search_one(type=cids.Indicator, iri=indIRI) if indIRI else None
if not ind and (request.form['action'] == 'edit') :
return(render_template('main.html', message="Error: Indicator not found in database."))
if request.form['action'] == 'add' : # create new Indicator
ind = cids.Indicator(namespace=cadr)
ind.definedBy = g_organization
# NEED TO UPDATE CODE SO IF THERE IS MORE THAN ONE IMPACT MODEL, IT REQUESTS WHICH ONE
if g_organization : g_impactModel.hasIndicator.append(ind)
ind.hasName = request.form['hasName']
ind.hasDescription = request.form['hasDescription']
ind.hasBaseline = i72.Measure(namespace=cadr, hasNumercalValue=request.form['hasBaseline'], hasUnit=None)
ind.hasThreshold = i72.Measure(namespace=cadr, hasNumercalValue=request.form['hasThreshold'], hasUnit=None)
# define the optional standard
indst = cadr.search_one(type=cids.IndicatorStandard, forOrganization = getOrganization(request.form['stOrgID']), hasIdentifier=request.form['stHasIdentifier'])
mess = "Standard organization of standard ID not found." if indst else ""
logIndividual("Update Indicator", ind, ind.hasBaseline, ind.hasThreshold )
return(renderIndicator(ind, "display", None, "readonly", "Indicator " + ind.hasName + " added. " + mess ))
def renderIndicator(ind, action, path, readonly, message) :
global g_user, g_organization, g_impactModel, cidsServer
orgIDValue = g_user.forOrganization.hasID.hasIdentifier
hasNameValue = ind.hasName if ind else ''
hasDescriptionValue = ind.hasDescription if ind else ""
located_inValue = ind.located_in if ind else None
hasBaselineValue = None
hasThresholdValue = None
hasBaselineValue = ind.hasBaseline.hasNumercalValue if ind.hasBaseline else None
hasThresholdValue = ind.hasThreshold.hasNumercalValue if ind.hasThreshold else None
return(render_template("indicatorEdit.html", action=action, path=path, indIRIValue=ind.iri,
orgIDValue = orgIDValue,
hasNameValue = hasNameValue,
hasDescriptionValue = hasDescriptionValue,
located_inValue = located_inValue,
hasBaselineValue = hasBaselineValue,
hasThresholdValue = hasThresholdValue))
@CARepository.route('/DeleteIndicator', methods=['POST'])
def deleteIndicator() :
global g_user, g_organization, g_impactModel, cidsServer
# check if user is permitted to add an Indicator
if not g_user.userType in [cidsrep.superuser, cidsrep.admin, cidsrep.editor]:
return(render_template('main.html', message="Error: User does not have permission to delete an Indicator."))
ind = cadr.search_one(type=cids.Indicator, iri=request.form['indIRI'])
if not ind : return(render_template('main.html', message="Error: Delete Indicator " + request.form['hasName'] + " does not exist."))
if (g_user.userType in [cidsrep.admin, cidsrep.editor]) and (g_user.forOrganization != ind.definedBy):
return(render_template('main.html', message="Error: User does not have permission to delete an Indicator not defined by their Organization."))
if not canModify(g_user, ind) :
return(render_template('main.html', message="Error: User does not have permission to delete Indicator."))