This repository has been archived by the owner on Jan 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
admin-api.php
2476 lines (2384 loc) · 94.1 KB
/
admin-api.php
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
<?php
/***
* Handle admin-specific requests
***/
#$debug = true;
if ($debug) {
error_reporting(E_ALL);
ini_set('display_errors', 1);
error_log('AdminAPI is running in debug mode!');
}
try {
ini_set('post_max_size', '500M');
ini_set('upload_max_filesize', '500M');
} catch (Exception $e) {
}
$print_login_state = false;
require_once 'DB_CONFIG.php';
require_once dirname(__FILE__).'/core/core.php';
# This is a public API
header('Access-Control-Allow-Origin: *');
$db = new DBHelper($default_database, $default_sql_user, $default_sql_password, $sql_url, $default_table, $db_cols);
require_once dirname(__FILE__).'/admin/async_login_handler.php';
# Declaring this makes Aldo slow
# $udb = new DBHelper($default_user_database,$default_sql_user,$default_sql_password,$sql_url,$default_user_table,$db_cols);
$start_script_timer = microtime_float();
if (!function_exists('elapsed')) {
function elapsed($start_time = null)
{
/***
* Return the duration since the start time in
* milliseconds.
* If no start time is provided, it'll try to use the global
* variable $start_script_timer
*
* @param float $start_time in unix epoch. See http://us1.php.net/microtime
***/
if (!is_numeric($start_time)) {
global $start_script_timer;
if (is_numeric($start_script_timer)) {
$start_time = $start_script_timer;
} else {
return false;
}
}
return 1000 * (microtime_float() - (float) $start_time);
}
}
$admin_req = isset($_REQUEST['perform']) ? strtolower($_REQUEST['perform']) : null;
if ($admin_req == null && isset($_REQUEST["action"])) {
$admin_req = strtolower($_REQUEST["action"]);
}
$login_status = getLoginState($get);
if ($as_include !== true) {
if ($login_status['status'] !== true) {
if ($admin_req == 'list') {
returnAjax(listProjects());
}
if ($admin_req == "advanced_project_search") {
returnAjax(advancedSearchProject($_REQUEST));
}
$login_status['error'] = 'Invalid user';
$login_status['human_error'] = "You're not logged in as a valid user to do this. Please log in and try again.";
returnAjax($login_status);
}
switch ($admin_req) {
# Stuff
case 'save':
returnAjax(saveEntry($_REQUEST));
break;
case 'new':
returnAjax(newEntry($_REQUEST));
break;
case 'delete':
returnAjax(deleteEntry($_REQUEST));
break;
case 'list':
returnAjax(listProjects(false));
break;
case 'sulist':
returnAjax(suListProjects(false));
break;
case 'get':
returnAjax(readProjectData($_REQUEST));
break;
case 'edit_access':
case 'editaccess':
$link = $_REQUEST['project'];
$deltas = smart_decode64($_REQUEST['deltas']);
returnAjax(editAccess($link, $deltas));
break;
case 'mint_data':
case 'mint':
$link = $_REQUEST['link'];
$file = $_REQUEST['file'];
$title64 = $_REQUEST['title'];
$title = decode64($title64);
if (empty($link) || empty($title)) {
returnAjax(array(
'status' => false,
'error' => 'BAD_PARAMETERS',
));
}
$addToExpedition = isset($_REQUEST['expedition']) ? boolstr($_REQUEST['expedition']) : false;
returnAjax(mintBcid($link, $file, $title, $addToExpedition));
break;
case 'create_expedition':
$link = $_REQUEST['link'];
$title64 = $_REQUEST['title'];
$public = boolstr($_REQUEST['public']);
$title = decode64($title64);
if (empty($link) || empty($title)) {
returnAjax(array(
'status' => false,
'error' => 'BAD_PARAMETERS',
));
}
$associate = boolstr($_REQUEST['bind_datasets']);
returnAjax(mintExpedition($link, $title, $public, $associate));
break;
case 'associate_expedition':
$link = $_REQUEST['link'];
$bcid = isset($_REQUEST['bcid']) ? $_REQUEST['bcid'] : null;
returnAjax(associateBcidsWithExpeditions($link, null, $bcid));
break;
case 'validate':
//$data = $_REQUEST["data"];
$datasrc = $_REQUEST['datasrc'];
$link = isset($_REQUEST['link']) ? $_REQUEST['link'] : $_REQUEST['project'];
$cookies = $_REQUEST['auth'];
$continue = empty($cookies) ? false : true;
returnAjax(validateDataset($datasrc, $link, $cookies, $continue));
break;
case 'check_access':
returnAjax(authorizedProjectAccess($_REQUEST));
break;
case 'su_manipulate_user':
returnAjax(superuserEditUser($_REQUEST));
break;
case "update_profile":
returnAjax(updateOwnProfile($_REQUEST));
break;
case "write_profile_image":
returnAjax(saveProfileImage($_REQUEST));
break;
case 'advanced_project_search':
returnAjax(advancedSearchProject($_REQUEST));
break;
case "invite":
returnAjax(inviteUser($_REQUEST));
break;
case "notify":
$subject = empty($_REQUEST["subject"]) ? null : $_REQUEST["subject"];
$body = empty($_REQUEST["body"]) ? null : $_REQUEST["body"];
returnAjax(notifyUsers($_REQUEST["project"], $subject, $body));
break;
default:
$defaultResponse = getLoginState($_REQUEST, true);
$defaultResponse["requested"] = $admin_req;
returnAjax($defaultResponse);
}
}
function inviteUser($get)
{
# Is the invite target valid?
$destination = deEscape($get["invitee"]);
if (!preg_match('/^(?:[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/im', $destination)) {
return array(
"status" => false,
"action" => "INVITE_USER",
"error" => "INVALID_EMAIL",
"target" => $destination,
);
}
# Go through the process
$u = new UserFunctions($login_status["detail"]["dblink"], 'dblink');
# Does the invite target exist as a user?
$userExists = $u->isEntry($destination, $u->userColumn);
if ($userExists !== false) {
return array(
"status" => false,
"error" => "ALREADY_REGISTERED",
"target" => $destination,
"action" => "INVITE_USER",
);
}
require_once dirname(__FILE__).'/admin/PHPMailer/PHPMailerAutoload.php';
require_once dirname(__FILE__).'/admin/CONFIG.php';
global $is_smtp,$mail_host,$mail_user,$mail_password,$is_pop3;
$mail = new PHPMailer();
if ($is_smtp) {
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->Host = $mail_host;
$mail->Username = $mail_user;
$mail->Password = $mail_password;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
}
if ($is_pop3) {
$mail->isPOP3();
} # Need to expand this
$mail->From = $u->getUsername();
$mail->FromName = $u->getShortUrl().' on behalf of '.$u->getName();
$mail->isHTML(true);
$mail->addAddress($destination);
$mail->Subject = "[".$u->getShortUrl()."] Invitation to Collaborate";
$body = "<h1>You've been invited to join a research project!</h1><p>You've been invited to join ".$u->getShortUrl()." by ".$u->getName()." (".$u->getUsername().").</p><p>Visit <a href='https://amphibiandisease.org/admin-login.php?q=create'>https://amphibiandisease.org/admin-login.php?q=create</a> to create a new user and get going!</p>";
$mail->Body = $body;
$success = $mail->send();
if ($success) {
return array(
"status" => $success,
"action" => "INVITE_USER",
"invited" => $destination,
);
} else {
return array(
"status" => $success,
"action" => "INVITE_USER",
"invited" => $destination,
"error" => "MAIL_SEND_FAIL",
"error_detail" => $mail->ErrorInfo,
);
}
}
function notifyUsers($projectId, $subject = "Default Message", $body = "Default Body", $superusers = false)
{
/***
* Wrapper to handle notifying users of changes.
***/
require_once dirname(__FILE__).'/admin/PHPMailer/PHPMailerAutoload.php';
require_once dirname(__FILE__).'/admin/CONFIG.php';
global $is_smtp,$mail_host,$mail_user,$mail_password,$is_pop3, $db;
$mail = new PHPMailer();
if ($is_smtp) {
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->Host = $mail_host;
$mail->Username = $mail_user;
$mail->Password = $mail_password;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
}
if ($is_pop3) {
$mail->isPOP3();
} # Need to expand this
$mail->From = "blackhole@amphibiandisease.org";
$mail->FromName = "Amphibian Disease Webserver";
$mail->isHTML(true);
# Look up the project
$query = "SELECT `author`, `author_data`, `access_data`, `technical_contact_email` FROM `disease_tracking_data` WHERE `project_id` = '".$db->sanitize($projectId)."'";
$userList = array();
$r = mysqli_query($db->getLink(), $query);
$row = mysqli_fetch_assoc($r);
# Find recipients
if ($row["technical_contact_email"] !== null) {
$userList[] = $row["technical_contact_email"];
}
$authorData = json_decode($row["author_data"], true);
$authorEmail = $authorData["contact_email"];
$userList[] = $authorEmail;
$accessors = explode(",", $row["access_data"]);
foreach ($accessors as $accessString) {
$parts = explode(":", $accessString);
$uid = $parts[0];
$query = "SELECT `username` FROM `userdata` WHERE `dblink`='".$uid."'";
$r = mysqli_query($db->getLink(), $query);
$row = mysqli_fetch_row($r);
$email = $row[0];
if ($email !== null && $email != $authorEmail) {
$userList[] = $email;
}
}
# Add superusers
$query = "SELECT `username` FROM `userdata` WHERE `su_flag` IS TRUE";
$r = mysqli_query($db->getLink(), $query);
while ($row = mysqli_fetch_row($r)) {
$userList[] = $row[0];
}
# Add everyone to the mail object
foreach ($userList as $destination) {
$mail->addAddress($destination);
}
$mail->Subject = "[Server Notice] ".$subject;
$htmlBody = "<html><head><link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\" integrity=\"sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7\" crossorigin=\"anonymous\"/></head><body>".$body."</body></html>";
$mail->Body = $htmlBody;
$success = $mail->send();
#$success = false;
if ($success) {
return array(
"status" => $success,
"action" => "NOTIFY_USER",
"notified" => $userList,
);
} else {
return array(
"status" => $success,
"action" => "NOTIFY_USER",
"notified" => $userList,
"error" => "MAIL_SEND_FAIL",
"error_detail" => $mail->ErrorInfo,
"body" => $body,
"subject" => $subject,
// "accessors" => $accessors,
// "author"=> $authorData,
);
}
}
function saveEntry($get)
{
/***
* Save updates to a project
*
* @param data a base 64-encoded JSON string of the data to insert
***/
$data64 = $get['data'];
$enc = strtr($data64, '-_', '+/');
$enc = chunk_split(preg_replace('!\015\012|\015|\012!', '', $enc));
$enc = str_replace(' ', '+', $enc);
$data_string = base64_decode($enc);
$data = json_decode($data_string, true);
if (!isset($data['project_id']) || !isset($data['id'])) {
# The required attribute is missing
$details = array(
'original_data' => $data64,
'decoded_data' => $data_string,
'data_array' => $data,
'message' => 'POST data attribute "project_id" or "id" is missing',
);
return array(
'status' => false,
'error' => 'BAD_PARAMETERS',
'detail' => $details,
'human_error' => 'The request to the server was malformed. Please try again.',
);
}
global $db, $login_status;
$uid = $login_status['detail']['uid'];
$project = $data['project_id'];
$id = $data['id'];
if (!$db->isEntry($id)) {
return array(
'status' => false,
'error' => 'INVALID_PROJECT',
'human_error' => 'No project exists at database row #'.$id,
);
}
$search = array('id' => $id);
$projectServerDataRow = $db->getQueryResults($search);
$projectServer = $projectServerDataRow[0];
if ($projectServer['project_id'] != $project) {
return array(
'status' => false,
'error' => 'MISMATCHED_PROJECT_IDENTIFIERS',
'human_error' => 'The project at row #'.$id." doesn't match the provided project number (provided: '".$project."'; expected '".$projectServer['project_id']."')",
);
}
$authorizedStatus = checkProjectAuthorized($projectServer, $uid);
if (!$authorizedStatus['can_edit']) {
return array(
'status' => false,
'error' => 'UNAUTHORIZED',
'human_error' => 'You have insufficient privileges to edit project #'.$project,
);
}
# Remove some read-only attributes
$ref = array(
'project_id' => $project,
);
unset($data['project_id']); # Obvious
unset($data['project_obj_id']); # ARK
if (strlen($data['dataset_arks']) < strlen($projectServer['dataset_arks'])) {
# It can only grow, not shrink
# Check formatting
unset($data['dataset_arks']);
}
unset($data['id']); # Obvious
unset($data['access_data']); # Handled seperately
try {
$result = $db->updateEntry($data, $ref);
} catch (Exception $e) {
return array(
'status' => false,
'error' => $e->getMessage(),
'humman_error' => 'Database error saving',
'data' => $data,
'ref' => $ref,
);
}
if ($result !== true) {
return array(
'status' => false,
'error' => $result,
'human_error' => 'Database error saving',
'data' => $data,
'ref' => $ref,
);
}
return array(
'status' => true,
'data' => $data,
'project' => readProjectData($project, true),
);
}
function newEntry($get)
{
/***
* Create a new entry
*
*
* @param data a base 64-encoded JSON string of the data to insert
***/
global $login_status;
$isUnrestricted = toBool($login_status["unrestricted"]);
if (!$isUnrestricted) {
return array(
"status" => false,
"error" => "RESTRICTED_USER_UNAUTHORIZED",
"human_error" => "Your account is still restricted. Please unrestrict your account before trying to create a project.",
);
}
$data64 = $get['data'];
$enc = strtr($data64, '-_', '+/');
$enc = chunk_split(preg_replace('!\015\012|\015|\012!', '', $enc));
$enc = str_replace(' ', '+', $enc);
$data_string = base64_decode($enc);
$data = json_decode($data_string, true);
# Add the perform key
global $db;
try {
$result = $db->addItem($data);
} catch (Exception $e) {
return array('status' => false, 'error' => $e->getMessage(), 'humman_error' => 'Database error saving', 'data' => $data, 'ref' => $result, 'perform' => 'new');
}
if ($result !== true) {
return array('status' => false, 'error' => $result, 'human_error' => 'Database error saving', 'data' => $data, 'ref' => $result, 'perform' => 'new');
}
return array('status' => true, 'perform' => 'new', 'data' => $data);
}
function deleteEntry($get)
{
/***
* Delete a project entry described by the ID parameter
*
* @param $get["id"] The DB id to delete
***/
global $db, $login_status;
$uid = $login_status['detail']['uid'];
$id = $get['id'];
if (!$db->isEntry($id)) {
return array(
'status' => false,
'error' => 'INVALID_PROJECT',
'human_error' => 'No project exists at database row #'.$id,
);
}
$search = array('id' => $id);
$project = $db->getQueryResults($search);
$authorizedStatus = checkProjectAuthorized($project, $uid);
if (!$authorizedStatus['can_edit']) {
return array(
'status' => false,
'error' => 'UNAUTHORIZED',
'human_error' => 'You have insufficient privileges to delete project #'.$project['project_id'],
);
}
$result = $db->deleteRow($id, 'id');
if ($result['status'] === false) {
$result['human_error'] = "Failed to delete item '$id' from the database";
}
return $result;
}
function editAccess($link, $deltas)
{
/***
*
***/
global $db, $login_status,$default_user_database,$default_sql_user,$default_sql_password,$sql_url,$default_user_table,$db_cols;
try {
$udb = new DBHelper($default_user_database, $default_sql_user, $default_sql_password, $sql_url, $default_user_table, $db_cols);
$uid = $login_status['detail']['uid'];
$pid = $db->sanitize($link);
if (!$db->isEntry($pid, 'project_id', true)) {
return array(
'status' => false,
'error' => 'INVALID_PROJECT',
'human_error' => 'No project #'.$pid.' exists',
);
}
$search = array('project_id' => $pid);
$projectList = $db->getQueryResults($search, '*', 'AND', false, true);
$project = $projectList[0];
$originalAccess = $project['access_data'];
$authorizedStatus = checkProjectAuthorized($project, $uid);
if (!$authorizedStatus['can_edit']) {
return array(
'status' => false,
'error' => 'UNAUTHORIZED',
'human_error' => 'You have insufficient privileges to change user permissions on project #'.$pid,
);
}
if (!is_array($deltas)) {
return array(
'status' => false,
'error' => 'BAD_DELTAS',
'human_error' => 'Your permission changes were malformed. Please correct them and try again.',
);
}
$additions = $deltas['add'];
$removals = $deltas['delete'];
$changes = $deltas['changes'];
$editList = $authorizedStatus['editors'];
$viewList = $authorizedStatus['viewers'];
$authorList = array($project['author']);
$totalList = array_merge($editList, $viewList, $authorList);
$notices = array();
$operations = array();
# Add users
foreach ($additions as $newUid) {
if (!$udb->isEntry($newUid, 'dblink')) {
$notices[] = 'User '.$user['uid']." doesn't exist";
continue;
}
if (in_array($newUid, $totalList)) {
$notices[] = "$newUid is already given project permissions";
continue;
}
$viewList[] = $newUid;
$operations[] = "Succesfully added $newUid as a viewer";
}
# Remove users
foreach ($removals as $user) {
# Remove user from list after looping through each
if (!is_array($user)) {
$notices[] = "Couldn't remove user, permissions object malformed";
continue;
}
if (!$udb->isEntry($user['uid'], 'dblink')) {
$notices[] = 'User '.$user['uid']." doesn't exist";
continue;
}
$currentRole = strtolower($user['currentRole']);
if ($currentRole == 'edit') {
$observeList = 'editList';
} elseif ($currentRole == 'read') {
$observeList = 'viewList';
} elseif ($currentRole == 'authorList') {
# Check the lists for other author thing
$observeList = 'authorList';
continue;
} else {
$notices[] = "Unrecognized current role '".strotupper($currentRole)."'";
continue;
}
$key = array_find($user['uid'], ${$observeList});
if ($key === false) {
$notices[] = 'Invalid current role for '.$user['uid'];
continue;
}
$orig = ${$observeList};
unset(${$observeList}[$key]);
$operations[] = 'User '.$user['uid']." removed from role '".strtoupper($currentRole)."' in ".$observeList;
}
# Changes to existing users
foreach ($changes as $user) {
if (!is_array($user)) {
$notices[] = "Couldn't change permissions, permissions object malformed";
continue;
}
if (!$udb->isEntry($user['uid'], 'dblink')) {
$notices[] = 'User '.$user['uid']." doesn't exist";
continue;
}
if (empty($user['currentRole']) || empty($user['newRole']) || empty($user['uid'])) {
$notices[] = "Couldn't change permissions, missing one of newRole, uid, or currentRole for user";
continue;
}
# Match the roles
$newRole = strtolower($user['newRole']);
$currentRole = strtolower($user['currentRole']);
if ($newRole == $currentRole) {
$notices[] = 'User '.$user['uid']." already has permissions '".strtoupper($currentRole)."'";
continue;
}
if ($currentRole == 'edit') {
$observeList = 'editList';
} elseif ($currentRole == 'read') {
$observeList = 'viewList';
} elseif ($currentRole == 'authorList') {
$observeList = 'authorList';
} else {
$notices[] = "Unrecognized current role '".strtoupper($currentRole)."'";
continue;
}
if ($newRole == 'edit') {
$addToList = 'editList';
} elseif ($newRole == 'read') {
$addToList = 'viewList';
} elseif ($newRole == 'authorList' || $newRole == "author") {
# $addToList = 'authorList';
$addToList = 'editList';
} else {
$notices[] = "Unrecognized new role '".strtoupper($newRole)."'";
continue;
}
$useAuthorQuery = false;
if ($newRole == 'edit' || $newRole == 'read' || $newRole == "author") {
$key = array_find($user['uid'], ${$observeList});
if ($key === false) {
$notices[] = 'Invalid current role for '.$user['uid'];
continue;
}
if ($observeList == 'authorList') {
# Someone else must be set as the author
} else {
unset(${$observeList}[$key]);
}
array_push(${$addToList}, $user['uid']);
$operations[] = 'Removed '.$user['uid']." from $observeList and added to $addToList";
if ($newRole == 'author') {
# Need to do fanciness
$useAuthorQuery = true;
$authorQuery = 'UPDATE `'.$db->getTable()."` SET `author`='".$user['uid']."' WHERE `project_id`='".$pid."'";
$db->closeLink();
$r = mysqli_query($db->getLink(), $authorQuery);
if ($r !== true) {
throw(new Exception(mysqli_error($db->getLink())));
}
$operations[] = "Changed project author to ".$user['uid'];
}
} else {
$notices[] = 'Invalid role assignment for user '.$user['uid'];
}
}
# Write the new lists back out
$newList = array();
$editListTracker =array();
$readListTracker = array();
foreach ($editList as $user) {
if (array_key_exists($user, $editListTracker)) {
continue;
}
$newList[] = $user.':EDIT';
$editListTracker[$user] = true;
}
foreach ($viewList as $user) {
if (array_key_exists($user, $readListTracker)) {
continue;
}
$newList[] = $user.':READ';
$readListTracker[$user] = true;
}
$newListString = implode(',', $newList);
$newListString = $db->sanitize($newListString);
$newEntry = array(
'access_data' => $newListString,
);
$lookup = array(
'project_id' => $pid,
);
$db->closeLink();
$query = 'UPDATE `'.$db->getTable()."` SET `access_data`='".$newListString."' WHERE `project_id`='".$pid."'";
$r = mysqli_query($db->getLink(), $query);
if ($r !== true) {
throw(new Exception(mysqli_error($db->getLink())));
}
$projectList = $db->getQueryResults($search, 'access_data', 'AND', false, true);
$project = $projectList[0];
return array(
'status' => true,
'operations_status' => $operations,
'notices' => $notices,
'new_access_list' => $newList,
'deltas' => $deltas,
'new_access_saved' => $newListString,
// "new_access_entry" => $project["access_data"],
// "original" => $originalAccess,
// "search" => $search,
// "query" => $query,
'project_id' => $pid,
);
} catch (Exception $e) {
return array(
'status' => false,
'error' => $e->getMessage(),
'human_error' => 'Server error processing access changes',
);
}
}
function listProjects($unauthenticated = true)
{
/***
* List accessible projects to the user.
*
* @param bool $unauthenticated -> Check for authorized projects
* to the user if false. Default true.
***/
global $db, $login_status;
$query = 'SELECT `project_id`,`project_title`, `carto_id`, `author_data`, `sample_raw_data` FROM '.$db->getTable().' WHERE `public` IS TRUE';
$l = $db->openDB();
$r = mysqli_query($l, $query);
$authorizedProjects = array();
$editableProjects = array();
$authoredProjects = array();
$publicProjects = array();
$queries = array();
$queries[] = $query;
$checkedPermissions = array();
$cartoTableList = array();
while ($row = mysqli_fetch_row($r)) {
$authorizedProjects[$row[0]] = $row[1];
$publicProjects[] = $row[0];
try {
$cartoJson = json_decode(deEscape($row[2]), true);
$authorJson = json_decode(deEscape($row[3]), true);
$cartoTable = $cartoJson["table"];
$creation = $authorJson["entry_date"];
$cartoTableList[$row[0]] = array(
"table" => $cartoTable,
"creation" => $creation,
"has_data" => !empty($row[4]),
);
} catch (Exception $e) {
}
}
if (!$unauthenticated) {
try {
$uid = $login_status['detail']['uid'];
} catch (Exception $e) {
$queries[] = 'UNAUTHORIZED';
}
if (!empty($uid)) {
$searchedAuthorized = true;
$query = 'SELECT `project_id`,`project_title`,`author`, `carto_id`, `author_data`, `sample_raw_data` FROM `'.$db->getTable()."` WHERE (`access_data` LIKE '%".$uid."%' OR `author`='$uid')";
$queries[] = $query;
$r = mysqli_query($l, $query);
while ($row = mysqli_fetch_row($r)) {
$pid = $row[0];
if (empty($pid)) {
continue;
}
# All results here are authorized projects
$authorizedProjects[$pid] = $row[1];
try {
$cartoJson = json_decode(deEscape($row[3]), true);
$authorJson = json_decode(deEscape($row[4]), true);
$cartoTable = $cartoJson["table"];
$creation = $authorJson["entry_date"];
$cartoTableList[$row[0]] = array(
"table" => $cartoTable,
"creation" => $creation,
"has_data" => !empty($row[5]),
);
} catch (Exception $e) {
}
if ($row[2] == $uid) {
$authoredProjects[] = $pid;
$editableProjects[] = $pid;
} else {
# Check permissions
$access = checkProjectIdAuthorized($pid);
$accessCopy = $access;
unset($accessCopy["detail"]);
$checkedPermissions[$pid] = $accessCopy;
$isEditor = $access["detailed_authorization"]["can_edit"];
$isViewer = $access["detailed_authorization"]["can_view"];
if ($isEditor === true) {
$editableProjects[] = $pid;
}
}
}
} else {
$searchedAuthorized = false;
}
}
$result = array(
'status' => true,
'projects' => $authorizedProjects,
'public_projects' => $publicProjects,
'authored_projects' => $authoredProjects,
'editable_projects' => $editableProjects,
'check_authentication' => !$unauthenticated,
"carto_table_map" => $cartoTableList,
"checked_authorized_projects" => $searchedAuthorized,
#"permissions" => $checkedPermissions,
);
return $result;
}
function suListProjects()
{
global $db, $login_status;
$suFlag = $login_status['detail']['userdata']['su_flag'];
$isSu = boolstr($suFlag);
if ($isSu !== true) {
return array(
'status' => false,
'error' => 'INVALID_PERMISSIONS',
'human_error' => "Sorry, you don't have permissions to do that.",
);
}
# Get a list of all the projects
$query = 'SELECT `project_id`,`project_title`, `public` FROM '.$db->getTable();
try {
$l = $db->openDB();
$r = mysqli_query($l, $query);
$projectList = array();
while ($row = mysqli_fetch_row($r)) {
$details = array(
'title' => $row[1],
'public' => boolstr($row[2]),
);
$projectList[$row[0]] = $details;
}
return array(
'status' => boolstr($suFlag),
'projects' => $projectList,
);
} catch (Exception $e) {
return array(
'status' => false,
'error' => 'SERVER_ERROR',
'human_error' => 'The server returned an error: '.$e->message(),
);
}
}
function checkProjectIdAuthorized($projectId, $simple = false)
{
/***
*
*
* @return array. If $simple = true, @return bool
***/
$access = array("project"=>$projectId);
try {
$accessResult = authorizedProjectAccess($access);
} catch (Exception $e) {
$accessResult = array(
"status" => false,
"error" => $e->getMessage(),
"human_error" => "Bad access result; defaulting no access",
);
}
return $simple ? $accessResult["status"] : $accessResult;
}
function checkProjectAuthorized($projectData, $uid)
{
/***
* Helper function for checking authorization
***/
global $login_status;
$currentUser = $login_status['detail']['uid'];
if ($uid == $currentUser) {
$suFlag = $login_status['detail']['userdata']['su_flag'];
$isSu = boolstr($suFlag);
} else {
$isSu = false;
}
$isAuthor = $projectData['author'] == $uid;
$isPublic = boolstr($projectData['public']);
$accessList = explode(',', $projectData['access_data']);
$editList = array();
$viewList = array();
foreach ($accessList as $viewer) {
$permissions = explode(':', $viewer);
$user = $permissions[0];
$access = $permissions[1];
if ($access == 'READ') {
$viewList[] = $user;
}
if ($access == 'EDIT') {
$editList[] = $user;
}
# Any other access value, including nullish, gives no permissions
}
$isEditor = in_array($uid, $editList);
$isViewer = in_array($uid, $viewList);
if ($isSu === true) {
# Superuser is everything!
if (!$isEditor) {
$editList[] = $uid;
}
$isAuthor = true;
$isEditor = true;
}
$response = array(
'can_edit' => $isAuthor || $isEditor,
'can_view' => $isAuthor || $isEditor || $isViewer || $isPublic,
'is_author' => $isAuthor,
'editors' => $editList,
'viewers' => $viewList,
'check' => array(
'current_user' => $currentUser,
'checked_user' => $uid,
'is_checked' => $uid == $currentUser,
'is_su' => $isSu,
),
"raw_access" => $projectData['access_data'],
"parsed_access" => $accessList,
);
return $response;
}
function authorizedProjectAccess($get)
{
global $db, $login_status;
$userProject = $get['project'];
$db->invalidateLink();
$project = $db->sanitize($userProject);
$projectExists = $db->isEntry($project, 'project_id', true);
if (!$projectExists) {
return array(
'status' => false,
'error' => 'INVALID_PROJECT',
'human_error' => "This project doesn't exist. Please check your project ID.",
'project_id' => $project,
"provided" => $get,
"read" => $userProject,
);
}
$uid = $login_status['detail']['uid'];
$projectDataList = $db->getQueryResults(array("project_id"=>$project), "*", "AND", false, true);
$projectData = $projectDataList[0];
$authorizedStatus = checkProjectAuthorized($projectData, $uid);
$status = $authorizedStatus['can_view'];
$results = array(
'status' => $status,
'project' => $project,
'detailed_authorization' => $authorizedStatus,
);
if ($status === true) {
$results['detail'] = readProjectData($project, true);
}
return $results;
}
function readProjectData($get, $precleaned = false, $debug = false)
{
/***
*
***/
global $db, $login_status;
if ($precleaned) {
$project = $get;
} else {
$project = $db->sanitize($get['project']);
}
$userdata = $login_status['detail'];
unset($userdata['source']);
unset($userdata['iv']);
unset($userdata['userdata']['random_seed']);