-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDBConnect.php
More file actions
executable file
·1197 lines (1008 loc) · 37.9 KB
/
DBConnect.php
File metadata and controls
executable file
·1197 lines (1008 loc) · 37.9 KB
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
class MyDB extends SQLite3
{
function __construct()
{
$dbName = '../../queuedb/database.sqlite';
$initDB = false;
$initDB = !file_exists($dbName);
$this->open($dbName);
$this->busyTimeout(15000);
if ($initDB) {
chmod($dbName, 0777);
DBInit($this);
//Insert a TA to get things up and going
$this->exec("BEGIN");
$sql = "INSERT INTO TAS (NetId, Counter) VALUES (:netId, 0);";
try {
$stmt = $this->prepare($sql);
$stmt->bindValue(":netId", phpCAS::getUser());
$stmt->execute();
$stmt->close();
$this->exec("COMMIT");
} catch (CAS_OutOfSequenceBeforeClientException $e) {
$this->exec("ROLLBACK");
echo $e;
echo "error adding initial TA";
}
}
}
}
function DBInit($db)
{
if ($db == null) {
$db = new MyDB();
} else {
$createUsers = "CREATE TABLE IF NOT EXISTS Students(NetId TEXT Not NULL,name TEXT, Counter INT NOT NULL DEFAULT 0, PassOffCounter Integer DEFAULT 0, UNIQUE(NetId))";
$createTA = "CREATE TABLE IF NOT EXISTS TAS(NetId TEXT Not NULL, name TEXT, Counter INT Not NULL DEFAULT 0, PassOffCounter INT DEFAULT 0, Active Bit Default 1, UNIQUE(NetId))";
$createQueue = "CREATE TABLE IF NOT EXISTS QUEUE(NetId TEXT Not NULL, ENQUEUETIME INT Not NULL, QUEUENUM INT Not NULL, QUESTION TEXT, PASSOFF BIT, STARTEDGETTINGHELPTIME INT, BeingHelpedBy TEXT, ZOOMLINK TEXT, UNIQUE(NetId))";
$createSettings = "CREATE TABLE IF NOT EXISTS SETTINGS(name TEXT Not NULL, value TEXT NOT NULL, UNIQUE(name))";
$createQueueHistory = "CREATE TABLE IF NOT EXISTS QUEUEHISTORY(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,NetId TEXT NOT NULL, removedBy TEXT NOT NULL,enqueueTime INTEGER NOT NULL, dequeueTime INTEGER NOT NULL, QUESTION TEXT, PASSOFF Bit, DoneGettingHelpTime INTEGER, ZOOMLINK TEXT,)";
$insertMessage = "INSERT OR IGNORE INTO SETTINGS (name, value) VALUES ('message', 'No Current Message')";
$insertDisplayMessage = "INSERT OR IGNORE INTO SETTINGS (name, value) VALUES ('displayMessage', '0')";
//create an after delete trigger on the queue table (get the person who was just deleted and start there and minus one to every spot in line)
//insert the settings
$insertActiveQueue = "INSERT OR IGNORE INTO SETTINGS (name, value) VALUES ('queueActive', 'true')";
$insertName = "INSERT OR IGNORE INTO SETTINGS (name, value) VALUES ('courseTitle', '')";
$insertStudentPollTime = "INSERT OR IGNORE INTO SETTINGS (name, value) VALUES ('studentPollTime', '5000')";
$insertTAPollTime = "INSERT OR IGNORE INTO SETTINGS (name, value) VALUES ('taPollTime', '3000')";
$insertNotifyThreshold = "INSERT OR IGNORE INTO SETTINGS (name, value) VALUES ('notifyThreshold', '3')";
$insertPassOffColor = "INSERT OR IGNORE INTO SETTINGS (name, value) VALUES ('passOffHighlightColor', 'yellow')";
$insertLastXMin = "INSERT OR IGNORE INTO SETTINGS (name, value) VALUES ('lastXMin', '5')";
$insertRequireQuestion = "INSERT OR IGNORE INTO SETTINGS (name, value) VALUES ('requireQuestion', 'true')";
$extendedView = "CREATE VIEW IF NOT EXISTS EXTENDEDQUEUE AS SELECT * FROM QUEUE JOIN Students USING (NetId) ORDER BY QUEUENUM";
$db->exec("BEGIN;");
$statement1 = $db->prepare($createUsers);
$statement2 = $db->prepare($createTA);
$statement3 = $db->prepare($createQueue);
$statement5 = $db->prepare($createSettings);
$statementQueueHistory = $db->prepare($createQueueHistory);
//$statement->bindValue(':id', $id);
$statement1->execute();
$statement2->execute();
$statement3->execute();
$statement5->execute();
$statementQueueHistory->execute();
$statement1->close();
$statement2->close();
$statement3->close();
$statement5->close();
$statementQueueHistory->close();
$statement7 = $db->prepare($extendedView);
$statement7->execute();
$statement7->close();
$statement6 = $db->prepare($insertActiveQueue);
$statement6->execute();
$statement6->close();
$statement8 = $db->prepare($insertName);
$statement8->execute();
$statement8->close();
$statement9 = $db->prepare($insertStudentPollTime);
$statement9->execute();
$statement9->close();
$statement10 = $db->prepare($insertTAPollTime);
$statement10->execute();
$statement10->close();
$statement11 = $db->prepare($insertNotifyThreshold);
$statement11->execute();
$statement11->close();
$statement12 = $db->prepare($insertPassOffColor);
$statement12->execute();
$statement12->close();
$statement13 = $db->prepare($insertLastXMin);
$statement13->execute();
$statement13->close();
$statement14 = $db->prepare($insertRequireQuestion);
$statement14->execute();
$statement14->close();
$statement15 = $db->prepare($insertMessage);
$statement15->execute();
$statement15->close();
$statement16 = $db->prepare($insertDisplayMessage);
$statement16->execute();
$statement16->close();
$db->exec('COMMIT');
//dont close $db because its going to be used by whom ever calle this function
}
//return "statement1: " + var_dump($statement1);
}
function enqueue($userId, $question, $passOff, $zoomLink)
{
//see if queue is active
if (isQueueActive() == false) {
return getUserStatus($userId);
}
$db = new MyDB();
$db->exec("BEGIN;");
//check if person is already on the list
$findDups = "Select * From Queue WHERE NetId = :id";
$findDupsStmt = $db->prepare($findDups);
$findDupsStmt->bindValue(':id', $userId);
$findDupsResult = $findDupsStmt->execute();
if ($findDupsRow = $findDupsResult->fetchArray(SQLITE3_ASSOC)) {
$findDupsResult->finalize();
$findDupsStmt->close();
//return data already in DB
$db->exec("COMMIT");
$db->close();
unset($db);
return array(
"status" => "success",
"userId" => $findDupsRow["NetId"],
"spot" => $findDupsRow["QUEUENUM"],
"enqueueTime" => $findDupsRow["ENQUEUETIME"],
"question" => $findDupsRow["QUESTION"],
"passOff" => $findDupsRow["PASSOFF"],
"gettingHelpTime" => $findDupsRow["STARTEDGETTINGHELPTIME"],
"beingHelpedBy" => $findDupsRow["BeingHelpedBy"],
"zoomLink" => $findDupsRow["ZOOMLINK"]
);
} else {
$findDupsResult->finalize();
$findDupsStmt->close();
}
$getTopQueue = "SELECT MAX(QUEUENUM) AS MAXNUM FROM QUEUE";
$statement2 = $db->prepare($getTopQueue);
$result1 = $statement2->execute();
if ($topResultRow = $result1->fetchArray(SQLITE3_ASSOC)) {
$queueNum = $topResultRow["MAXNUM"] + 1;
} else {
$queueNum = 1;
}
$result1->finalize();
$statement2->close();
require_once 'CAS-1.3.4/CAS.php';
phpCAS::client(CAS_VERSION_2_0, 'cas.byu.edu', 443, 'cas');
$auth = phpCAS::checkAuthentication();
//here we could check auth. if it is false send back a json {status:loggedOut}
//uncomment this only during testing
//$auth = true;
if (!$auth) {
$db->exec("ROLLBACK;");
$db->close();
unset($db);
return array("status" => "loggedOut");
} else {
try {
$toReturn;
//check the supplied userID is the same as the logged in user
//*******************************************************************
//comment this only during testing
if (phpCAS::getUser() == $userId) {
//Clean up any injecting jank
$invalid_characters = array("$", "%", "#", "<", ">", "|");
$question = str_replace($invalid_characters, "", $question);
$passOff = str_replace($invalid_characters, "", $passOff);
// if ($passOff == "true") {
// $question = "PASS OFF";
// } else //not passing off
// {
// if ($question == "PASS OFF") {
// $db->exec("ROLLBACK;");
// $db->close();
// unset($db);
// return array("status" => "error", "message" => "Not a valid question. If you want to pass off click the check box");
// }
// }
if (strlen($question) > 300) {
$db->exec("ROLLBACK;");
$db->close();
unset($db);
return array("status" => "error", "message" => "Question length is too long");
}
//enter the data in
$insertData = "INSERT INTO QUEUE (NetId, ENQUEUETIME, QUEUENUM, QUESTION, PASSOFF, ZOOMLINK) VALUES (:netId, :time, :spot, :question, :passoff, :zoomLink);";
$insertDupsStmt = $db->prepare($insertData);
$insertDupsStmt->bindValue(':netId', $userId);
$insertDupsStmt->bindValue(':time', time() * 1000);
$insertDupsStmt->bindValue(':spot', $queueNum);
$insertDupsStmt->bindValue(':question', $question);
$insertDupsStmt->bindValue(':passoff', $passOff);
$insertDupsStmt->bindValue(':zoomLink', $zoomLink);
//add the student to the student table
$insertToStudent = "INSERT OR IGNORE INTO STUDENTS (NetId, counter) VALUES (:netId, 0)";
$insertToStudentStmt = $db->prepare($insertToStudent);
$insertToStudentStmt->bindValue(':netId', $userId);
$insertDupsStmt->execute();
$insertToStudentStmt->execute();
$insertDupsStmt->close();
$insertToStudentStmt->close();
$toReturn = array("status" => "success", "enqueueTime" => time() * 1000, "spot" => $queueNum, "question" => $question, "passOff" => $passOff);
} else {
$toReturn = array("status" => "error", "message" => "not authorized");
}
$db->exec("COMMIT");
$db->close();
unset($db);
return $toReturn;
} catch (CAS_OutOfSequenceBeforeClientException $e) {
//return error
$db->exec("ROLLBACK");
$db->close();
unset($db);
return array("status" => "error", "message" => "not authorized");
}
}
}
function dequeueUser($userIdToRemove)
{
//check if a TA or the user himself is removing from the queue
//if the user himself is removing, just remove it
//if the TA is removing, then remove it and +1 to the counters on both tables
//(may require adding to the Users table is the people aren't in there)
//This assumes the TA table is already populated with the TA netIds.
try {
require_once 'CAS-1.3.4/CAS.php';
phpCAS::client(CAS_VERSION_2_0, 'cas.byu.edu', 443, 'cas');
$auth = phpCAS::checkAuthentication();
$thisUsersID = phpCAS::getUser();
//only uncomment during testing
//$thisUsersID = $userIdToRemove; //this means someones removing themselves
//$thisUsersID = $userIdToRemove . "NOT"; //this means a TA is removing someone
$settings = getSettings();
$db = new MyDB();
$db->exec("BEGIN;");
$arrayToReturn;
$enqueueDetails = getEnqueueDetails($db, $userIdToRemove);
//the student is removing themselfs
if ($thisUsersID == $userIdToRemove) {
//check if they were being helped, if so treat is as if the TA removed them, otherwise just remove them
if ($enqueueDetails["startedGettingHelpTime"] == null) {
// Update queue positions
$queuePos = $enqueueDetails["queueNum"];
updateQueuePositions($db, $queuePos);
//just remove student from queue no mas
$removeUser = "DELETE FROM QUEUE WHERE NetId = :netId";
$removeUserStmt = $db->prepare($removeUser);
$removeUserStmt->bindValue(':netId', $userIdToRemove);
$removeUserStmt->execute();
$removeUserStmt->close();
if ($db->changes() > 0) {
insertHistory($db, $userIdToRemove, $userIdToRemove, $enqueueDetails);
}
} else //the student was being helped by a TA, so act like a TA removed them
{
dequeueHelperForTa($db, $userIdToRemove, $enqueueDetails["beingHelpedBy"], $enqueueDetails);
}
//update
$avgs = getAverages($db);
$arrayToReturn = array("status" => 'success', "userId" => $thisUsersID, "spot" => -1, "enqueueTime" => 0, "settings" => $settings, "avgs" => $avgs);
} else //it could be a TA. Lets check
{
$findTA = "SELECT COUNT(*) AS NUM FROM TAS WHERE NetId = :netId";
$findTAStmt = $db->prepare($findTA);
$findTAStmt->bindValue(':netId', $thisUsersID);
$findTARslt = $findTAStmt->execute();
//A TA was found
$findTARow = $findTARslt->fetchArray(SQLITE3_ASSOC);
if ($findTARow["NUM"] == 1) {
$findTARslt->finalize();
$findTAStmt->close();
//Check if STARTEDGETTINGHELPTIME is empty, if so, update QUEUE and set STARTEDGETTINGHELPTIME to current time
if ($enqueueDetails["startedGettingHelpTime"] == null) {
// Update queue positions
$queuePos = $enqueueDetails["queueNum"];
updateQueuePositions($db, $queuePos);
$sql = "UPDATE QUEUE Set startedGettingHelpTime = :time, BeingHelpedBy = :taId, QUEUENUM = 0 WHERE netId = :netId";
$updateStmt = $db->prepare($sql);
$updateStmt->bindValue(":netId", $userIdToRemove);
$updateStmt->bindValue(":taId", $thisUsersID);
$updateStmt->bindValue("time", time() * 1000);
$updateStmt->execute();
$updateStmt->close();
} else //remove them from the queue and update the history
{
//**** Updated 7/3/18 by Gibson Ainge - Dequeue cooldown added to prevent "queue sniping"
$cooldown = (time() * 1000) - $enqueueDetails["startedGettingHelpTime"];
if ($cooldown > 3000) { // If has been on the queue for > 5 seconds, allow dequeue
dequeueHelperForTa($db, $userIdToRemove, $thisUsersID, $enqueueDetails);
}
}
$avgs = getAverages($db);
$arrayToReturn = array("status" => "success", "list" => getQueue($db), "avgs" => $avgs);
} else {
$findTARslt->finalize();
$findTAStmt->close();
//return error
$arrayToReturn = array("status" => "error", "message" => "not authorized to remove that person");
}
}
$db->exec("COMMIT");
} catch (CAS_OutOfSequenceBeforeClientException $e) {
//return error
$db->exec("ROLLBACK");
$arrayToReturn = array("status" => "error", "message" => "not authorized");
}
$db->close();
unset($db);
return $arrayToReturn;
}
// Updated by Gibson Ainge 1/7/19, removed QUEUENUM trigger and replaced with update statement
// This method is called whenever a student removes themselves when NOT bein helped, or when a TA clicks on a student to provide help
// In both of the above cases, the student is removed from the regular queue ordering, and positions should be updated where applicable.
function updateQueuePositions($db, $indexRemoved)
{
$updatePos = "UPDATE QUEUE SET QUEUENUM = QUEUENUM - 1 WHERE QUEUENUM > :position";
$updateStmt = $db->prepare($updatePos);
$updateStmt->bindValue(':position', $indexRemoved);
$updateStmt->execute();
$updateStmt->close();
}
function dequeueHelperForTa($db, $userIdToRemove, $thisUsersID, $enqueueDetails)
{
//remove the student from the queue (a trigger will update everyone elses spot in line)
$removeStudentSQL = "DELETE FROM QUEUE WHERE NetId = :netId";
$removeStudentStmt = $db->prepare($removeStudentSQL);
$removeStudentStmt->bindValue(':netId', $userIdToRemove);
$removeStudentStmt->execute();
$removeStudentStmt->close();
if ($db->changes() > 0) {
$incrementStudentCounter;
$incrementTACounter;
if ($enqueueDetails["passOff"] == "true") {
$incrementTACounter = "UPDATE TAS SET PassOffCounter = PassOffCounter + 1 WHERE NetId = :netId";
$incrementStudentCounter = "UPDATE Students SET PassOffCOUNTER = PassOffCOUNTER + 1 WHERE NetId = :netId";
} else {
$incrementTACounter = "UPDATE TAS SET Counter = Counter + 1 WHERE NetId = :netId";
$incrementStudentCounter = "UPDATE Students SET COUNTER = COUNTER + 1 WHERE NetId = :netId";
}
//increment the TAs counter
$incrementTACounterStmt = $db->prepare($incrementTACounter);
$incrementTACounterStmt->bindValue(':netId', $thisUsersID);
$incrementTACounterStmt->execute();
$incrementTACounterStmt->close();
//increment the Students counter
$incrementStudentCounterStmt = $db->prepare($incrementStudentCounter);
$incrementStudentCounterStmt->bindValue(':netId', $userIdToRemove);
$incrementStudentCounterStmt->execute();
$incrementStudentCounterStmt->close();
insertHistory($db, $userIdToRemove, $thisUsersID, $enqueueDetails);
}
}
function getEnqueueDetails($db, $netId)
{
$getTimeStamp = "Select * FROM QUEUE WHERE NetId = :netId";
$getTimeStampStmt = $db->prepare($getTimeStamp);
$getTimeStampStmt->bindValue(':netId', $netId);
$getTimeStampResult = $getTimeStampStmt->execute();
$toReturn = array();
if ($getTimeStampRow = $getTimeStampResult->fetchArray(SQLITE3_ASSOC)) {
$toReturn = array(
"enqueueTime" => $getTimeStampRow["ENQUEUETIME"],
"question" => $getTimeStampRow["QUESTION"],
"passOff" => $getTimeStampRow["PASSOFF"],
"startedGettingHelpTime" => $getTimeStampRow["STARTEDGETTINGHELPTIME"],
"beingHelpedBy" => $getTimeStampRow["BeingHelpedBy"],
"queueNum" => $getTimeStampRow["QUEUENUM"]
);
}
$getTimeStampResult->finalize();
$getTimeStampStmt->close();
return $toReturn;
}
function insertHistory($db, $netId, $removedBy, $enqueueDetails)
{
$insertHistory = "Insert Into QUEUEHISTORY (NetId, removedBy, enqueueTime, dequeueTime, QUESTION, PASSOFF, DoneGettingHelpTime) VALUES (:netId, :removedBy, :enqueueTime, :dequeueTime, :question, :passoff, :doneGettingHelpTime)";
$dequeueHistoryStmt = $db->prepare($insertHistory);
$dequeueHistoryStmt->bindValue(':netId', $netId);
$dequeueHistoryStmt->bindValue(':removedBy', $removedBy);
$dequeueHistoryStmt->bindValue(':enqueueTime', $enqueueDetails["enqueueTime"]);
//if startedGettingHelpTime is null and were here it means a student got out of line without getting help. Just insert the current time
$dequeueHistoryStmt->bindValue(':dequeueTime', ($enqueueDetails["startedGettingHelpTime"] == null ? time() * 1000 : $enqueueDetails["startedGettingHelpTime"]));
$dequeueHistoryStmt->bindValue(':question', $enqueueDetails["question"]);
$dequeueHistoryStmt->bindValue(':passoff', $enqueueDetails["passOff"]);
//if startedGettingHelpTime is null they didn't get help so just put null here, other wise put in the current time
$dequeueHistoryStmt->bindValue(':doneGettingHelpTime', ($enqueueDetails["startedGettingHelpTime"] == null ? $enqueueDetails["startedGettingHelpTime"] : time() * 1000));
$dequeueHistoryStmt->execute();
$dequeueHistoryStmt->close();
}
function clearQueue()
{
$toReturn;
try {
require_once 'CAS-1.3.4/CAS.php';
phpCAS::client(CAS_VERSION_2_0, 'cas.byu.edu', 443, 'cas');
$auth = phpCAS::checkAuthentication();
//only a TA can do this
if (verifyTA(phpCAS::getUser())) {
$db = new MyDB();
$db->exec("BEGIN;");
//get all entrys in the queue, have to insert them into queuehistory table
//After thinking it over I decided to comment this out. My reasoning is that if someone clears the
//queue, no ones stats are increased, so why should the QueueHistory reflect that
/* $getAllQueue = "Select * FROM QUEUE";
$getAllQueueStmt = $db->prepare($getAllQueue);
$getAllQueueRslt = $getAllQueueStmt->execute();
$insertHistory = "Insert Into QUEUEHISTORY (NetId, removedBy, enqueueTime, dequeueTime) VALUES (:netId, :removedBy, :enqueueTime, :dequeueTime)";
$dequeueHistoryStmt = $db->prepare($insertHistory);
while($row = $getAllQueueRslt->fetchArray(SQLITE3_ASSOC) )
{
$dequeueHistoryStmt->bindValue(':netId', $row["NetId"]);
$dequeueHistoryStmt->bindValue(':removedBy', phpCAS::getUser());
$dequeueHistoryStmt->bindValue(':enqueueTime', $row["ENQUEUETIME"]);
$dequeueHistoryStmt->bindValue(':dequeueTime', time()*1000);
$dequeueHistoryStmt->execute();
}
$getAllQueueRslt->finalize();
$getAllQueueStmt->close();
$dequeueHistoryStmt->close();
*/
$sql = "DELETE FROM QUEUE";
$stmt = $db->prepare($sql);
$stmt->execute();
$stmt->close();
$avgs = getAverages($db);
$toReturn = array("status" => "success", "list" => getQueue($db), "avgs" => $avgs);
$db->exec("COMMIT");
$db->close();
unset($db);
} else
$toReturn = array("status" => "No authorized to do that");
} catch (CAS_OutOfSequenceBeforeClientException $e) {
$toReturn = array("status" => "error", "message" => "login error");
}
return $toReturn;
}
function getUserStatus($userId)
{
$settings = getSettings();
$db = new MyDB();
$db->exec('BEGIN');
$avgs = getAverages($db);
$sql = "SELECT * FROM EXTENDEDQUEUE WHERE NetId = :netId";
$stmt = $db->prepare($sql);
$stmt->bindValue("netId", $userId);
$result = $stmt->execute();
$itemInQueue;
if ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$itemInQueue = array(
"status" => "success",
"userId" => $row["NetId"],
"name" => $row["name"],
"spot" => $row["QUEUENUM"],
"enqueueTime" => $row["ENQUEUETIME"],
"helpScore" => $row["Counter"],
"settings" => $settings,
"avgs" => $avgs,
"question" => $row["QUESTION"],
"passOff" => $row["PASSOFF"],
"startedGettingHelpTime" => $row["STARTEDGETTINGHELPTIME"],
"beingHelpedBy" => $row["BeingHelpedBy"],
"zoomLink" => $row["ZOOMLINK"]
);
} else {
$itemInQueue = array("status" => 'success', "userId" => $userId, "spot" => -1, "enqueueTime" => 0, "settings" => $settings, "avgs" => $avgs);
}
$result->finalize();
$stmt->close();
$db->exec("COMMIT");
$db->close();
unset($db);
return $itemInQueue;
}
function verifyTA($userId)
{
$db = new MyDB();
$db->exec("BEGIN;");
$findTA = "SELECT * FROM TAS WHERE NetId = :netId and active = 1";
$findTAStmt = $db->prepare($findTA);
$findTAStmt->bindValue(":netId", $userId);
$findTAResult = $findTAStmt->execute();
$result = "";
if ($findTARow = $findTAResult->fetchArray(SQLITE3_ASSOC)) {
$result = $findTARow["NetId"] == $userId;
}
$findTAResult->finalize();
$findTAStmt->close();
$db->exec("COMMIT;");
$db->close();
unset($db);
return $result;
}
function inTATable($userId)
{
$db = new MyDB();
$db->exec("BEGIN;");
$findTA = "SELECT * FROM TAS WHERE NetId = :netId";
$findTAStmt = $db->prepare($findTA);
$findTAStmt->bindValue(":netId", $userId);
$findTAResult = $findTAStmt->execute();
$result = "";
if ($findTARow = $findTAResult->fetchArray(SQLITE3_ASSOC)) {
$result = $findTARow["NetId"] == $userId;
}
$findTAResult->finalize();
$findTAStmt->close();
$db->exec("COMMIT;");
$db->close();
unset($db);
return $result;
}
function insertTags($question)
{
$regex = "/https?:\/\/.*\..*/i";
$numMatches = preg_match($regex, $question, $matches);
if ($numMatches == 1) {
// We found a match! so we need to replace it
// add https:// if missing
// if (strpos($matches[0], "https://") === false) {
// $matches[0] = "https://" . $matches[0];
// }
$url = $matches[0];
$newUrl = "<a href=\"" . $url . "\" target=\"_blank\">" . $url . "</a>";
return preg_replace($regex, $newUrl, $question);
} else {
//No zoom link found, so just return the original question
return $question;
}
}
function getQueue($db)
{
$manageDB = false;
if ($db == null) {
$manageDB = true;
$db = new MyDB();
$db->exec('BEGIN');
}
$sql = "SELECT * FROM EXTENDEDQUEUE";
$stmt = $db->prepare($sql);
$result = $stmt->execute();
$listToReturn = array();
//******************************************
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$itemInQueue = array(
"netId" => $row["NetId"],
"name" => $row["name"],
"spot" => $row["QUEUENUM"],
"enqueueTime" => $row["ENQUEUETIME"],
"helpScore" => $row["Counter"],
"question" => $row["QUESTION"],
"passOff" => $row["PASSOFF"],
"startedGettingHelpTime" => $row["STARTEDGETTINGHELPTIME"],
"beingHelpedBy" => $row["BeingHelpedBy"],
"zoomLink" => $row["ZOOMLINK"]
);
// Insert hyperlink tags if there is a zoom link found within the question
$itemInQueue["question"] = insertTags($itemInQueue["question"]);
$itemInQueue["zoomLink"] = insertTags($itemInQueue["zoomLink"]);
array_push($listToReturn, $itemInQueue);
}
$result->finalize();
$stmt->close();
if ($manageDB) {
$db->exec("COMMIT");
$db->close();
unset($db);
}
return $listToReturn;
}
function getStats()
{
$listToReturn = array("tas" => array(), "students" => array());
$db = new MyDB();
$db->exec("BEGIN");
$sql = "SELECT * FROM STUDENTS ORDER BY COUNTER DESC";
$stmt = $db->prepare($sql);
$result = $stmt->execute();
//***********************************
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
array_push($listToReturn["students"], array("netId" => $row["NetId"], "name" => $row["name"], "helpCounter" => $row["Counter"], 'passOffCounter' => $row["PassOffCounter"]));
}
$result->finalize();
$stmt->close();
$sqlT = "SELECT * FROM TAS ORDER BY COUNTER DESC";
$stmtT = $db->prepare($sqlT);
$resultT = $stmtT->execute();
//********************************************
while ($row = $resultT->fetchArray(SQLITE3_ASSOC)) {
array_push($listToReturn["tas"], array("netId" => $row["NetId"], "name" => $row["name"], "helpCounter" => $row["Counter"], 'passOffCounter' => $row["PassOffCounter"], "active" => $row["Active"]));
}
$resultT->finalize();
$stmtT->close();
$db->exec("COMMIT");
$db->close();
unset($db);
return $listToReturn;
}
function getExtendedStats($netId, $startTime, $endTime)
{
$sql = "Select * From QUEUEHISTORY";
$db = new MyDB();
$db->exec("BEGIN");
$stmt;
if ($netId != null && $startTime != null && $endTime != null) {
$endTime = $endTime + 3600000; //3600000 is one hour in miliseconds
$sql = $sql . " WHERE netId = :netId and dequeueTime >= :startTime and dequeueTime <= :endTime order by dequeueTime asc";
$stmt = $db->prepare($sql);
$stmt->bindValue(":netId", $netId);
$stmt->bindValue(":startTime", $startTime);
$stmt->bindValue(":endTime", $endTime);
} else if ($netId != null) {
$sql = $sql . " WHERE netId = :netId order by dequeueTime asc";
$stmt = $db->prepare($sql);
$stmt->bindValue(":netId", $netId);
} else if ($startTime != null && $endTime != null) {
$endTime = $endTime + 3600000; //3600000 is one hour in miliseconds
$sql = $sql . " WHERE dequeueTime >= :startTime and dequeueTime <= :endTime order by dequeueTime asc";
$stmt = $db->prepare($sql);
$stmt->bindValue(":startTime", $startTime);
$stmt->bindValue(":endTime", $endTime);
} else {
$stmt = $db->prepare($sql);
}
$rslt = $stmt->execute();
$studentData = array();
while ($row = $rslt->fetchArray(SQLITE3_ASSOC)) {
array_push($studentData, array("id" => $row["id"], "netId" => $row["NetId"], "removedBy" => $row["removedBy"], "enqueueTime" => $row["enqueueTime"], "dequeueTime" => $row["dequeueTime"], "question" => $row["QUESTION"], "passOff" => $row["PASSOFF"], "doneGettingHelp" => $row["DoneGettingHelpTime"]));
}
$rslt->finalize();
$stmt->close();
//get netId => names to print names instead of netIds on client side
$sql = "Select NetId, name from Students";
$stmt = $db->prepare($sql);
$rslt = $stmt->execute();
$studentNames = array();
while ($row = $rslt->fetchArray(SQLITE3_ASSOC)) {
$name = $row["name"] == null ? 'No name' : $row["name"];
array_push($studentNames, array("netId" => $row["NetId"], "name" => $name));
}
$rslt->finalize();
$stmt->close();
$taData = getAllTAs($db);
$db->exec("COMMIT");
$db->close();
unset($db);
return array("studentData" => $studentData, "tas" => $taData, "studentNames" => $studentNames);
}
function updateHistory($thisUser, $data)
{
if (verifyTA($thisUser)) {
$db = new MyDB();
$db->exec("BEGIN;");
$initRowSql = "Select netId, removedBy, PASSOFF from QUEUEHISTORY Where id = :id";
$stmt = $db->prepare($initRowSql);
$stmt->bindValue(":id", $data["id"]);
$initRowRslt = $stmt->execute();
$oldNetId = null;
$oldRemovedBy = null;
$oldPassOff = null;
if ($row = $initRowRslt->fetchArray(SQLITE3_ASSOC)) {
$oldNetId = $row["NetId"];
$oldRemovedBy = $row["removedBy"];
$oldPassOff = $row["PASSOFF"];
}
$initRowRslt->finalize();
$stmt->close();
$sql = "UPDATE QUEUEHISTORY SET NetId = :netId, removedBy = :removedBy, enqueueTime = :enqueueTime, dequeueTime = :dequeueTime, QUESTION = :question, PASSOFF = :passOff, DoneGettingHelpTime = :doneGettingHelpTime WHERE id = :id";
$stmt = $db->prepare($sql);
$stmt->bindValue(":id", $data["id"]);
$stmt->bindValue(":netId", $data["netId"]);
$stmt->bindValue(":removedBy", $data["removedBy"]);
$stmt->bindValue(":enqueueTime", $data["enqueueTime"]);
$stmt->bindValue(":dequeueTime", $data["dequeueTime"]);
$stmt->bindValue(":question", $data["question"]);
$stmt->bindValue(":passOff", $data["passOff"]);
$stmt->bindValue(":doneGettingHelpTime", $data["doneGettingHelpTime"]);
$stmt->execute();
$stmt->close();
$updateOldValuesNetId = "Update Students set " . ($oldPassOff == "true" ? "passOffCounter" : "counter") . " = (Select count(*) from QueueHistory where netId = :oldNetId and passOff = '" . $oldPassOff . "') where netId = :oldNetId";
$updateOldValuesRemovedBy = "Update " . (inTATable($oldRemovedBy) ? "TAs" : "Students") . " set " . ($oldPassOff == "true" ? "passOffCounter" : "counter") . " = (Select Count(*) from QueueHistory where removedBy = :oldRemovedBy and passOff ='" . $oldPassOff . "') Where netId = :oldRemovedBy";
$updateNewValuesNetId = "Update Students set " . ($data["passOff"] == "true" ? "passOffCounter" : "counter") . " = (Select count(*) from QueueHistory where netId = :newNetId and passOff = '" . $data["passOff"] . "') where netId = :newNetId";
$updateNewValuesRemovedBy = "Update " . (inTATable($data["removedBy"]) ? "TAs" : "Students") . " set " . ($data["passOff"] == "true" ? "passOffCounter" : "counter") . " = (Select Count(*) from QueueHistory where removedBy = :newRemovedBy and passOff ='" . $data["passOff"] . "') Where netId = :newRemovedBy";
$stmtOldValuesNewId = $db->prepare($updateOldValuesNetId);
$stmtOldValuesRemovedBy = $db->prepare($updateOldValuesRemovedBy);
$stmtNewValuesNewId = $db->prepare($updateNewValuesNetId);
$stmtNewValuesRemovedBy = $db->prepare($updateNewValuesRemovedBy);
$stmtOldValuesNewId->bindValue(":oldNetId", $oldNetId);
$stmtOldValuesRemovedBy->bindValue(":oldRemovedBy", $oldRemovedBy);
$stmtNewValuesNewId->bindValue(":newNetId", $data["netId"]);
$stmtNewValuesRemovedBy->bindValue("newRemovedBy", $data["removedBy"]);
$stmtOldValuesNewId->execute();
$stmtOldValuesRemovedBy->execute();
$stmtNewValuesNewId->execute();
$stmtNewValuesRemovedBy->execute();
$stmtOldValuesNewId->close();
$stmtOldValuesRemovedBy->close();
$stmtNewValuesNewId->close();
$stmtNewValuesRemovedBy->close();
$db->exec("COMMIT");
$db->close();
unset($db);
return array("status" => "success");
} else
return array("status" => "not authorized");
}
function getAllTAs($db)
{
$selfDB = false;
if ($db == null) {
$selfDB = true;
$db = new MyDB();
$db->exec("BEGIN;");
}
$sql = "Select * from TAS";
$stmt = $db->prepare($sql);
$rslt = $stmt->execute();
$taData = array();
while ($row = $rslt->fetchArray(SQLITE3_ASSOC)) {
array_push($taData, array("netId" => $row["NetId"], "name" => $row["name"]));
}
$rslt->finalize();
$stmt->close();
if ($selfDB) {
$db->exec("COMMIT");
$db->close();
unset($db);
}
return $taData;
}
function toggleTAActive($userId)
{
$db = new MyDB();
$db->exec("BEGIN");
$sql = "UPDATE TAs SET Active = ~Active WHERE NetId = :netId";
$deleteStmt = $db->prepare($sql);
$deleteStmt->bindValue(':netId', $userId);
$deleteStmt->execute();
$deleteStmt->close();
$db->exec("COMMIT");
$db->close();
unset($db);
return getStats();
}
function addTA($userId, $name)
{
$db = new MyDB();
$db->exec("BEGIN");
$insertToTAs = "INSERT OR IGNORE INTO TAS (NetId, name, counter, active) VALUES (:netId, :nameIn, 0, 1)";
$insertToTAsStmt = $db->prepare($insertToTAs);
$insertToTAsStmt->bindValue(':netId', $userId);
$insertToTAsStmt->bindValue(':nameIn', $name);
$insertToTAsStmt->execute();
$insertToTAsStmt->close();
$db->exec("COMMIT");
$db->close();
unset($db);
return getStats();
}
function addStudent($userId)
{
$db = new MyDB();
$db->exec("BEGIN;");
$insertToStudent = "INSERT OR IGNORE INTO STUDENTS (NetId, counter) VALUES (:netId, 0)";
$insertToStudentStmt = $db->prepare($insertToStudent);
$insertToStudentStmt->bindValue(':netId', $userId);
$insertToStudentStmt->execute();
$insertToStudentStmt->close();
$db->exec("COMMIT;");
$db->close();
unset($db);
}
function getAverages($db)
{
$selfDB = false;
if ($db == null) {
$selfDB = true;
$db = new MyDB();
$db->exec("BEGIN;");
}
$sql = "SELECT AVG(ENQUEUETIME) AS AVRG, COUNT(*) AS NUM FROM QUEUE WHERE QUEUENUM < (Select Min(QUEUENUM)+5 FROM QUEUE WHERE STARTEDGETTINGHELPTIME is null) AND STARTEDGETTINGHELPTIME is null";
$sql2 = "SELECT COUNT(*) AS LEN FROM QUEUE WHERE STARTEDGETTINGHELPTIME is null";
$sql2_5 = "SELECT COUNT(*) AS LEN FROM QUEUE WHERE STARTEDGETTINGHELPTIME > 1";
//get the number of people who got in line and the number of people who got helped in the lastXMin
$sql3 = "SELECT COUNT(*) AS EnqueueCount FROM QUEUE WHERE ENQUEUETIME >= (((SELECT strftime('%s', 'now')) - (Select value * 60 from settings where name = 'lastXMin')) * 1000)";
$sql4 = "SELECT COUNT(*) AS DequeueCount FROM QUEUEHISTORY WHERE DEQUEUETIME >= (((SELECT strftime('%s', 'now')) - (Select value * 60 from settings where name = 'lastXMin')) * 1000)";
$sql5 = "SELECT COUNT(*) AS EnqueueCount FROM QUEUEHISTORY WHERE ENQUEUETIME >= (((SELECT strftime('%s', 'now')) - (Select value * 60 from settings where name = 'lastXMin')) * 1000)";
$stmt = $db->prepare($sql);
$stmt2 = $db->prepare($sql2);
$stmt2_5 = $db->prepare($sql2_5);
$stmt3 = $db->prepare($sql3);
$stmt4 = $db->prepare($sql4);
$stmt5 = $db->prepare($sql5);
$result = $stmt->execute();
$result2 = $stmt2->execute();
$result2_5 = $stmt2_5->execute();
$result3 = $stmt3->execute();
$result4 = $stmt4->execute();
$result5 = $stmt5->execute();
$enqueueCount = 0;
$dequeueCount = 0;
$avg = 0;
$avgLen = 0;
$queueLen = 0;
$currentlyBeingHelped = 0;
if ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$avg = $row["AVRG"] == null ? 0 : $row["AVRG"];
$avgLen = $row["NUM"] == 0 ? 0 : $row["NUM"];
}
if ($row = $result2->fetchArray(SQLITE3_ASSOC)) {
$queueLen = $row["LEN"];
}
if ($row = $result2_5->fetchArray(SQLITE3_ASSOC)) {
$currentlyBeingHelped = $row["LEN"];
}
if ($row = $result3->fetchArray(SQLITE3_ASSOC)) {
$enqueueCount = $enqueueCount + $row["EnqueueCount"];
}
if ($row = $result4->fetchArray(SQLITE3_ASSOC)) {
$dequeueCount = $dequeueCount + $row["DequeueCount"];
}
if ($row = $result5->fetchArray(SQLITE3_ASSOC)) {
$enqueueCount = $enqueueCount + $row["EnqueueCount"];
}
$toReturn = array("avg" => $avg, "avgLen" => $avgLen, "queueLen" => $queueLen, "enqueueInLastXMin" => $enqueueCount, "dequeueInLastXMin" => $dequeueCount, "currentlyBeingHelpedCount" => $currentlyBeingHelped);
$result->finalize();
$result2->finalize();
$result2_5->finalize();
$result3->finalize();
$result4->finalize();
$result5->finalize();
$stmt->close();
$stmt2->close();
$stmt2_5->close();
$stmt3->close();
$stmt4->close();
$stmt5->close();