-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathunimoodleservercli.php
More file actions
1978 lines (1895 loc) · 73.3 KB
/
unimoodleservercli.php
File metadata and controls
1978 lines (1895 loc) · 73.3 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
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
// Project implemented by the "Recovery, Transformation and Resilience Plan.
// Funded by the European Union - Next GenerationEU".
//
// Produced by the UNIMOODLE University Group: Universities of
// Valladolid, Complutense de Madrid, UPV/EHU, León, Salamanca,
// Illes Balears, Valencia, Rey Juan Carlos, La Laguna, Zaragoza, Málaga,
// Córdoba, Extremadura, Vigo, Las Palmas de Gran Canaria y Burgos..
/**
* CLI version of websocket server
*
* @package mod_kuet
* @copyright 2023 Proyecto UNIMOODLE {@link https://unimoodle.github.io}
* @author UNIMOODLE Group (Coordinator) <direccion.area.estrategia.digital@uva.es>
* @author 3IPUNT <contacte@tresipunt.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
declare(strict_types=1);
// Define unimoodleservercli constant.
define('UNIMOOODLESERVERCLI', value: "UNIMOODLEKUET");
// @phpcs:disable PHP0420
// @phpcs:disable PSR1.Classes.ClassDeclaration.MultipleClasses
// @phpcs:disable moodle.Files.MoodleInternal.MoodleInternalGlobalState
/**
* CLI version of websocket server.
*/
class unimoodleservercli extends websockets {
/**
* @var array students
*/
protected $students = [];
/**
* @var array teacher
*/
protected $teacher = [];
/**
* @var array session id users
*/
protected $sidusers = [];
/**
* @var array session id groups
*/
protected $sidgroups = [];
/**
* @var array session id users by group
*/
protected $sidgroupusers = [];
/**
* @var string password
*/
protected $password = 'elktkktagqes';
/**
* Run Unimoodleservercli protocol forever.
*
* @return mixed
*/
public function run() {
while (true) {
try {
// Check if the master socket is still valid and purge not valid sockets.
if (!is_resource($this->master) || get_resource_type($this->master) !== 'stream') {
$this->stdout(self::red_text("Master socket is not a valid resource. Recreating.", false));
$this->create_master_socket();
}
// Add the master socket to the list of sockets to read from.
$this->sockets['m'] = $this->master;
$read = $this->sockets;
$write = $except = null;
$this->tick_core();
$this->tick();
if ($this->verboselog) {
$this->stdout(self::blue_text("Waiting for messages on $this->addr:$this->port", false));
}
stream_select($read, $write, $except, seconds: null);
if (in_array($this->master, $read, true)) {
$client = @stream_socket_accept($this->master, 20);
if (!$client) {
continue;
}
$ip = stream_socket_get_name($client, true);
$this->stdout(self::blue_text("Connection attempt from $ip", false));
if ($this->handshake($client)) {
// Show stats.
$this->stdout(self::white_text("Total users: " . count($this->users), false));
$this->stdout(self::white_text("Groups: " . count($this->sidgroups), false));
$this->stdout(self::white_text("Held messages: " . count($this->heldmessages), false));
} else {
$this->stdout(self::red_text("Handshake failed for $ip", false));
continue;
}
// Delete master socket from the read array to avoid processing messages bellow.
// This is necessary to avoid processing the master socket as a client socket.
$foundsocket = array_search($this->master, $read, true);
unset($read[$foundsocket]);
if ($client < 0) {
$this->stdout(self::red_text("Failed: socket_accept()", false));
continue;
}
}
foreach ($read as $socket) {
$ip = stream_socket_get_name($socket, true);
$usersocket = $this->get_user_by_socket($socket);
if ($usersocket === null) {
$this->stdout(self::red_text("Unknown user for socket $socket", false));
$this->disconnect($socket, true, "Unknown user for socket $socket");
continue;
}
if (!$usersocket->handshake) {
// If the user has not yet performed the handshake, then we read the headers from the socket.
$this->handshake($usersocket->socket);
}
// JPC limit messages length to avoid memory issues.
$buffer = stream_get_contents($socket, $this->maxbuffersize);
// 3IP review detect disconnect for min buffer lenght.
if ($buffer === false || strlen($buffer) <= 8) {
$unmasked = $this->unmask($buffer);
// If the unmasked data is 0x03e8 or 0xe9 then it is a disconnect message.
if ($unmasked === "\x03\xe8" || $unmasked === "\x03\xe9") {
$this->disconnect($socket, true, "Disconnect message received from $ip");
continue;
} else {
// Empty frames are not allowed.
$this->disconnect($socket);
$this->stdout(
self::red_text(
"Message too short." .
bin2hex($unmasked) . " disconnected. TCP connection lost: " . $socket,
false
)
);
continue;
}
}
$blocksread = 0;
// JPC Consume the rest of the data in the socket to avoid repeated reads and to mitigate DoS attacks.
while ($remaining = stream_get_contents($socket, $this->maxbuffersize)) {
$blocksread++;
if ($blocksread > 3) {
// If we have read more than 3 blocks, then we assume that the message is artificially large.
$this->disconnect($socket);
$this->stdout(
self::red_text("Too large message from $ip. Suspected attack. Closing connection.", false)
);
continue 2; // Continue to the next iteration of the main loop.
}
if ($this->verboselog) {
$this->stdout(
self::red_text(
"More data received from $ip for the message. Possible attack: " .
strlen($remaining) . ' bytes',
false
)
);
}
}
$unmasked = $this->unmask($buffer);
if ($unmasked !== "") {
$isjson = $this->check_json($unmasked);
if ($this->verboselog) {
$this->stdout(message: self::green_text("Message from " .
$usersocket->userid . " user. Content: " .
substr($unmasked, 0, 100) .
'...[' . strlen($unmasked) . ' bytes]', false));
}
// Only process the message if it is a valid userid and the message is valid JSON.
if ($isjson === true) {
$this->process($usersocket, $unmasked);
} else {
if ($unmasked == 'ping') {
$msg = json_encode([
'action' => 'connect',
'usersocketid' => $usersocket->userid ?? 'Unknown',
], JSON_THROW_ON_ERROR);
$this->send_masked([$usersocket], $msg);
} else if ($unmasked == 'diag') {
// Diagnostic message, send the current status of the server.
// Number of users connected, groups, held messages, memory usage, etc.
$memoryusageinmb = round(memory_get_usage() / 1024 / 1024, 2);
$msg = json_encode([
'action' => 'diag',
'usersocketid' => 'Unknown',
'sockets' => count($this->sockets),
'users' => count($this->users),
'groups' => count($this->sidgroups),
'heldmessages' => count($this->heldmessages),
'memoryusage' => $memoryusageinmb . ' MB',
], JSON_THROW_ON_ERROR);
$this->send_masked([$usersocket], $msg, false);
} else {
// Unknown amd malformed JSON message.
$msg = json_encode([
'action' => 'error',
'user' => $usersocket->userid,
'message' => mb_convert_encoding('Invalid message received: ' . $unmasked, 'UTF-8', 'auto'),
'usersocketid' => $usersocket->userid ?? 'Unknown',
], JSON_THROW_ON_ERROR);
$this->send_masked([$usersocket], $msg);
// Disconnect the socket if the message is not valid.
$this->disconnect($socket, true, 'Invalid message received: ' . $unmasked);
}
}
}
} // End of foreach read sockets.
} catch (Exception | Error | TypeError $e) {
$this->stdout(self::red_text("FATAL Error: " . $e->getMessage(), false));
// If the socket is not the master, then disconnect it.
$this->stdout(self::red_text("Disconnecting socket due to error: " . $e->getMessage(), false));
$this->disconnect($socket, true, $e->getMessage());
}
}
}
/**
* Process message
*
* @param $user
* @param $message
* @return void
* @throws JsonException
*/
protected function process($user, $message) {
// Sends a message to all users on the socket belonging to the same "sid" session.
$data = json_decode(
mb_convert_encoding($message, 'UTF-8', 'UTF-8'),
true,
512,
JSON_THROW_ON_ERROR
);
if (isset($data['oft']) && $data['oft'] === true) {
// Only for teacher.
$responsetext = $this->get_response_from_action_for_teacher($user, $data['action'], $data);
if ($responsetext !== '' && isset($this->sidusers[$data['sid']])) {
$this->send_masked($this->sidusers[$data['sid']], $responsetext);
}
} else if (isset($data['ofs']) && $data['ofs'] === true) {
// Only for student.
$responsetext = $this->get_response_from_action_for_student($user, $data['action'], $data);
if ($responsetext !== '') {
// TODO: Check if this is correct. Believe on reported usersocketid???
$usersocket = $this->get_user_by_socket($data['usersocketid']);
$this->send_masked([$usersocket], $responsetext);
}
} else if (isset($data['ofg']) && $data['ofg'] === true) {
// Only for groups.
$responsetext = $this->get_response_from_action_for_group($data);
$groupid = $this->get_groupid_from_a_member((int) $data['sid'], (int) $data['userid']);
if ($responsetext !== '' && $groupid) {
$socketgroups = $this->sidgroups[$data['sid']];
$sentto = [];
foreach ($socketgroups[$groupid]->users as $usergroup) {
foreach ($this->sockets as $key => $socket) {
if ($key === $usergroup->usersocketid) {
$this->send_masked([$usergroup], $responsetext);
break;
}
}
}
}
} else { // All users in this sid.
$responsetext = $this->get_response_from_action($user, $data['action'], $data);
if ($responsetext !== '' && isset($this->sidusers[$data['sid']])) {
$this->send_masked($this->sidusers[$data['sid']], $responsetext);
}
}
}
/**
* Check connected user
*
* @param $user
* @return void
*/
protected function connected($user) {
// 3IP log user connected. This function is called by handshake.
}
/**
* Connect socket
*
* @param $socket
* @param $ip
* @return void
* @throws JsonException
*/
protected function connect($socket, $ip) {
$user = new websocketuser(uniqid('u', true), $socket, $ip);
// Add the user to the list of all users on the socket.
$this->users[$user->usersocketid] = $user;
$this->sockets[$user->usersocketid] = $socket;
/* inactivity time for SSL client https://bugs.php.net/bug.php?id=70939
$sock = socket_import_stream ($socket);
socket_set_option($sock, SOL_SOCKET, SO_KEEPALIVE, 1);*/
// We return the usersocketid only to the new user so that responds by identifying with newuser.
$this->send_masked([$user], json_encode([
'action' => 'connect',
'usersocketid' => $user->usersocketid,
], JSON_THROW_ON_ERROR));
$this->connecting($user);
}
/**
* Send message using mask function.
* It optionally uses a password.
* @param array[websocketuser] $usersockets
* @param string $message
* @param bool $encrypt
*/
protected function send_masked($usersockets, $message, $encrypt = true) {
if ($encrypt) {
$message = kuet_encrypt($this->password, $message);
}
$maskedmessage = $this->mask($message);
foreach ($usersockets as $usersocket) {
fwrite($usersocket->socket, $maskedmessage, strlen($maskedmessage));
}
}
/**
* Close group member connection to socket
*
* @param $user
* @return void
* @throws JsonException
*/
protected function close_groupmember($user) {
$groupmemberdisconected = false;
$groupdisconected = false;
$groupid = 0;
$groupname = '';
$numgroups = 0;
if (array_key_exists($user->usersocketid, $this->sidgroupusers)) {
$groupmemberdisconected = true;
$groupid = $this->sidgroupusers[$user->usersocketid];
$groupname = $this->sidgroups[$user->sid][$groupid]->groupname;
$numusers = count($this->sidgroups[$user->sid][$groupid]->users);
$numgroups = count($this->sidgroups[$user->sid]);
unset($this->sidgroups[$user->sid][$groupid]->users[$user->usersocketid], $this->sidgroupusers[$user->usersocketid]);
--$numusers;
if ($numusers === 0) {
unset($this->sidgroups[$user->sid][$groupid]);
--$numgroups;
$groupdisconected = true;
}
}
if ($groupdisconected) {
$groupresponse = $this->mask(
kuet_encrypt(
$this->password,
json_encode(
[
'action' => 'groupdisconnected',
'usersocketid' => $user->usersocketid,
'groupid' => $groupid,
'message' =>
'<span style="color: red">' . $groupname . ' disconnected </span>',
'count' => $numgroups,
],
JSON_THROW_ON_ERROR
)
)
);
if (isset($this->sidusers[$user->sid])) {
$this->send_masked($this->sidusers[$user->sid], $groupresponse);
}
} else if ($groupmemberdisconected) {
$groupresponse = $this->mask(
kuet_encrypt(
$this->password,
json_encode(
[
'action' => 'groupmemberdisconnected',
'usersocketid' => $user->usersocketid,
'groupid' => $groupid,
'message' =>
'<span style="color: red"> Group member ' . $user->dataname . ' has been disconnected. </span>',
'count' => $numusers,
],
JSON_THROW_ON_ERROR
)
)
);
if (isset($this->sidusers[$user->sid])) {
$this->send_masked($this->sidusers[$user->sid], $groupresponse);
}
}
}
/**
* Closed connection routine
*
* @param $user
* @return void
* @throws JsonException
*/
protected function closed($user) {
unset(
$this->sidusers[$user->sid][$user->usersocketid],
$this->students[$user->sid][$user->usersocketid]
);
// Group mode.
$this->close_groupmember($user);
$response = json_encode(
[
'action' => 'userdisconnected',
'usersocketid' => $user->usersocketid,
'message' =>
'<span style="color: red">' . "User $user->dataname has been disconnected." . '</span>',
'count' => isset($this->students[$user->sid]) ? count($this->students[$user->sid]) : 0,
],
JSON_THROW_ON_ERROR
);
if (isset($this->sidusers[$user->sid])) {
$this->send_masked($this->sidusers[$user->sid], $response);
}
if ($user->isteacher) {
unset($this->teacher[$user->sid]);
if (isset($this->sidusers[$user->sid])) {
foreach ($this->sidusers[$user->sid] as $socket) {
$this->disconnect($socket->socket);
unset($this->students[$user->sid], $this->sidusers[$user->sid]);
}
}
}
}
/**
* Get response from action for teacher
*
* @param websocketuser $user
* @param string $useraction
* @param array $data
* @return string
* @throws JsonException
*/
protected function get_response_from_action_for_teacher(websocketuser $user, string $useraction, array $data): string {
switch ($useraction) {
case 'studentQuestionEnd':
return json_encode([
'action' => 'studentQuestionEnd',
'onlyforteacher' => true,
'context' => $data,
'message' => 'El alumno ' . $data['userid'] . ' ha contestado una pregunta', // 3IP delete.
], JSON_THROW_ON_ERROR);
case 'ImproviseStudentTag':
return json_encode([
'action' => 'ImproviseStudentTag',
'onlyforteacher' => true,
'improvisereply' => $data['improvisereply'],
'userid' => $data['userid'],
'message' => '',
], JSON_THROW_ON_ERROR);
case 'StudentVotedTag':
return json_encode([
'action' => 'StudentVotedTag',
'onlyforteacher' => true,
'votedtag' => $data['votedtag'],
'userid' => $data['userid'],
'message' => '',
], JSON_THROW_ON_ERROR);
default:
return '';
}
}
/**
* Get group id for a member
*
* @param int $sid
* @param int $userid
* @return int
*/
protected function get_groupid_from_a_member(int $sid, int $userid): int {
$groupid = 0;
if (!array_key_exists($sid, $this->sidgroups)) {
return $groupid;
}
foreach ($this->sidgroups[$sid] as $sidgroup) {
foreach ($sidgroup->users as $member) {
if ((int)$member->userid === $userid) {
$groupid = $sidgroup->groupid;
return $groupid;
}
}
}
return $groupid;
}
/**
* Get response from action for a group
*
* @param array $data
* @return string
* @throws JsonException
*/
protected function get_response_from_action_for_group(array $data): string {
switch ($data['action']) {
case 'alreadyAnswered':
return json_encode([
'action' => 'alreadyAnswered',
'userid' => $data['userid'],
'kid' => $data['kid'],
], JSON_THROW_ON_ERROR);
default:
return '';
}
}
/**
* Get response from action for student user
*
* @param websocketuser $user
* @param string $useraction
* @param array $data
* @return string
* @throws JsonException
*/
protected function get_response_from_action_for_student(websocketuser $user, string $useraction, array $data): string {
switch ($useraction) {
case 'normalizeUser':
return json_encode([
'action' => 'question',
'context' => $data['context'],
], JSON_THROW_ON_ERROR);
default:
return '';
}
}
/**
* Get response from action
*
* @param websocketuser $user
* @param string $useraction
* @param array $data
* @return string
* @throws JsonException
*/
protected function get_response_from_action(websocketuser $user, string $useraction, array $data): string {
// Prepare data to be sent to client.
switch ($useraction) {
case 'newgroup':
$this->newuser($user, $data);
$this->newgroup($user, $data);
return $this->manage_newgroup_for_sid($user, $data);
case 'newuser':
$this->newuser($user, $data);
if (isset($data['isteacher']) && $data['isteacher'] === true) {
return $this->manage_newteacher_for_sid($user, $data);
}
return $this->manage_newstudent_for_sid($user, $data);
case 'countusers':
return json_encode([
'action' => 'countusers',
'count' => count($this->students[$data['sid']]),
], JSON_THROW_ON_ERROR);
case 'question':
return json_encode([
'action' => 'question',
'context' => $data['context'],
], JSON_THROW_ON_ERROR);
case 'ranking':
return json_encode([
'action' => 'ranking',
'context' => $data['context'],
], JSON_THROW_ON_ERROR);
case 'endSession':
return json_encode([
'action' => 'endSession',
'context' => $data['context'],
], JSON_THROW_ON_ERROR);
case 'teacherQuestionEnd':
return json_encode([
'action' => 'teacherQuestionEnd',
'kid' => $data['kid'],
'statistics' => $data['statistics'],
], JSON_THROW_ON_ERROR);
case 'pauseQuestion':
return json_encode([
'action' => 'pauseQuestion',
'kid' => $data['kid'],
], JSON_THROW_ON_ERROR);
case 'playQuestion':
return json_encode([
'action' => 'playQuestion',
'kid' => $data['kid'],
], JSON_THROW_ON_ERROR);
case 'showAnswers':
return json_encode([
'action' => 'showAnswers',
'kid' => $data['kid'],
], JSON_THROW_ON_ERROR);
case 'hideAnswers':
return json_encode([
'action' => 'hideAnswers',
'kid' => $data['kid'],
], JSON_THROW_ON_ERROR);
case 'showStatistics':
return json_encode([
'action' => 'showStatistics',
'kid' => $data['kid'],
], JSON_THROW_ON_ERROR);
case 'hideStatistics':
return json_encode([
'action' => 'hideStatistics',
'kid' => $data['kid'],
], JSON_THROW_ON_ERROR);
case 'showFeedback':
return json_encode([
'action' => 'showFeedback',
'kid' => $data['kid'],
], JSON_THROW_ON_ERROR);
case 'hideFeedback':
return json_encode([
'action' => 'hideFeedback',
'kid' => $data['kid'],
], JSON_THROW_ON_ERROR);
case 'improvising':
return json_encode([
'action' => 'improvising',
'kid' => $data['kid'],
], JSON_THROW_ON_ERROR);
case 'closeImprovise':
return json_encode([
'action' => 'closeImprovise',
], JSON_THROW_ON_ERROR);
case 'improvised':
return json_encode([
'action' => 'improvised',
'improvisestatement' => $data['improvisestatement'],
'improvisereply' => $data['improvisereply'],
'cmid' => $data['cmid'],
'sessionid' => $data['sid'],
], JSON_THROW_ON_ERROR);
case 'printNewTag':
return json_encode([
'action' => 'printNewTag',
'tags' => $data['tags'],
], JSON_THROW_ON_ERROR);
case 'initVote':
return json_encode([
'action' => 'initVote',
], JSON_THROW_ON_ERROR);
case 'shutdownTest':
default:
return '';
}
}
/**
* Set new user for the websocket
*
* @param websocketuser $user
* @param array $data
* @return void
*/
private function newuser(websocketuser $user, array $data): void {
// If reported usersocketid does not march stored usersocketid, then throw error. Possible attack.
if ($data['usersocketid'] !== $user->usersocketid) {
throw new Exception('Reported usersocketid does not match stored usersocketid. Possible attack.');
}
$this->users[$user->usersocketid]->dataname = $data['name'];
$this->users[$user->usersocketid]->picture = $data['pic'];
$this->users[$user->usersocketid]->userid = $data['userid'];
$this->users[$user->usersocketid]->usersocketid = $data['usersocketid'];
$this->users[$user->usersocketid]->sid = $data['sid'];
$this->users[$user->usersocketid]->cmid = $data['cmid'];
$user->update_user($data);
}
/**
* Set new group for websocket
*
* @param websocketuser $user
* @param array $data
* @return void
*/
private function newgroup(websocketuser $user, array $data): void {
if (!array_key_exists($data['sid'], $this->sidgroups)) {
$this->sidgroups[$data['sid']] = [];
}
if (!array_key_exists($data['groupid'], $this->sidgroups[$data['sid']])) {
$this->sidgroups[$data['sid']][$data['groupid']] = new stdClass();
$this->sidgroups[$data['sid']][$data['groupid']]->users = [];
}
$this->sidgroups[$data['sid']][$data['groupid']]->groupid = $data['groupid'];
$this->sidgroups[$data['sid']][$data['groupid']]->groupname = $data['name'];
$this->sidgroups[$data['sid']][$data['groupid']]->grouppicture = $data['pic'];
$this->sidgroups[$data['sid']][$data['groupid']]->sid = $data['sid'];
$this->sidgroups[$data['sid']][$data['groupid']]->cmid = $data['cmid'];
if (!array_key_exists($data['usersocketid'], $this->sidgroups[$data['sid']][$data['groupid']]->users)) {
$this->sidgroups[$data['sid']][$data['groupid']]->users[$user->usersocketid] = new stdClass();
$this->sidgroups[$data['sid']][$data['groupid']]->users[$user->usersocketid]->usersocketid = $data['usersocketid'];
$this->sidgroups[$data['sid']][$data['groupid']]->users[$user->usersocketid]->userid = $data['userid'];
$this->sidgroupusers[$data['usersocketid']] = $data['groupid'];
}
}
/**
* Manage new teacher user for session id
*
* @param websocketuser $user
* @param array $data
* @return string
* @throws JsonException
*/
private function manage_newteacher_for_sid(websocketuser $user, array $data): string {
if (isset($this->teacher[$data['sid']]) && count($this->teacher[$data['sid']]) === 1) {
// There can only be one teacher in each session to avoid conflicts of functionality.
$response = json_encode([
'action' => 'alreadyteacher',
'message' => 'There is already a teacher controlling this session, so you cannot connect.' .
'Please wait for the current session to end before you can enter.',
], JSON_THROW_ON_ERROR);
$usersocket = $this->get_socket_by_user($user);
$this->send_masked([$usersocket], $response);
$this->disconnect($usersocket);
return '';
}
$user->isteacher = true;
$this->users[$user->usersocketid]->isteacher = true;
$this->teacher[$data['sid']][$user->usersocketid] = $this->users[$user->usersocketid];
$this->sidusers[$data['sid']][$user->usersocketid] = $this->users[$user->usersocketid];
return json_encode([
'action' => 'newteacher',
'name' => $data['name'] ?? '',
'userid' => $user->id ?? '',
'message' => '<span style="color: green">The teacher ' . $user->dataname . ' has connected</span>',
'count' => isset($this->sidusers[$data['sid']]) ? count($this->sidusers[$data['sid']]) : 0,
], JSON_THROW_ON_ERROR);
}
/**
* Manage new student user for session id
*
* @param websocketuser $user
* @param array $data
* @return string
* @throws JsonException
*/
private function manage_newstudent_for_sid(websocketuser $user, array $data): string {
$duplicateresolve = false;
if (isset($this->students[$data['sid']])) {
foreach ($this->students[$data['sid']] as $usersocketid => $studentsid) {
if ($studentsid->userid === $data['userid']) {
// There can only be one same user in each session to avoid conflicts of functionality.
foreach ($this->sockets as $key => $socket) {
if ($key === $usersocketid) {
$this->disconnect($socket);
$duplicateresolve = true;
break;
}
}
}
if ($duplicateresolve === true) {
break;
}
}
}
$this->users[$user->usersocketid]->isteacher = false;
$this->sidusers[$data['sid']][$user->usersocketid] = $this->users[$user->usersocketid];
$this->students[$data['sid']][$user->usersocketid] = $this->users[$user->usersocketid];
$studentsdata = [];
foreach ($this->students[$data['sid']] as $key => $student) {
$studentsdata[$key]['picture'] = $student->picture;
$studentsdata[$key]['usersocketid'] = $student->usersocketid;
$studentsdata[$key]['name'] = $student->dataname;
}
return json_encode([
'action' => 'newuser',
'usersocketid' => $user->usersocketid,
'students' => array_values($studentsdata),
'count' => count($this->students[$data['sid']]),
], JSON_THROW_ON_ERROR);
}
/**
* Manage new users group for session id
*
* @param websocketuser $user
* @param array $data
* @return string
* @throws JsonException
*/
private function manage_newgroup_for_sid(websocketuser $user, array $data): string {
$this->users[$user->usersocketid]->isteacher = false;
$this->sidusers[$data['sid']][$user->usersocketid] = $this->users[$user->usersocketid];
$this->students[$data['sid']][$user->usersocketid] = $this->users[$user->usersocketid];
$groupsdata = [];
foreach ($this->sidgroups[$data['sid']] as $key => $group) {
$groupsdata[$key]['groupid'] = $group->groupid;
$groupsdata[$key]['picture'] = $group->grouppicture;
$groupsdata[$key]['usersocketid'] = $data['usersocketid'];
$groupsdata[$key]['name'] = $group->groupname;
$groupsdata[$key]['numgroupusers'] = count($group->users);
}
return json_encode([
'action' => 'newgroup',
'usersocketid' => $user->usersocketid,
'groups' => array_values($groupsdata),
'count' => count($this->sidgroups[$data['sid']]),
], JSON_THROW_ON_ERROR);
}
}
/**
* Websocket class.
*
*/
abstract class websockets {
/**
* @var int max buffer size
*/
protected $maxbuffersize;
/**
* @var false|resource master
*/
protected $master;
/**
* @var array sockets
*/
protected $sockets = [];
/**
* @var array users
*/
protected $users = [];
/**
* @var array held message
*/
protected $heldmessages = [];
/**
* @var bool interactive
*/
protected $interactive = true;
/**
* @var string IP address
*/
protected $addr;
/**
* @var int port
*/
protected $port;
/**
* @var string certificate file
*/
protected $certificate;
/**
* @var string private key file
*/
protected $privatekey;
/**
* @var bool use ssl
*/
protected $usessl = false;
/**
* @var string network transport protocol
*/
protected $transport;
/**
* @var bool verboselog
*/
protected $verboselog = false;
/**
* SSL transport protocol
*/
const SECURE_TRANSPORT = 'ssl';
/**
* No ssl transport protocol
*/
const INSECURE_TRANSPORT = 'tcp';
/**
* @var array ANSI color codes
*/
private static array $colors = [
'red' => '31',
'green' => '32',
'yellow' => '33',
'blue' => '34',
'magenta' => '35',
'cyan' => '36',
'white' => '37',
];
/**
* Constructor
*
* @param $addr
* @param $bufferlength
* @throws Exception
*/
public function __construct($addr, $bufferlength = 16000) {
global $_SERVER;
// Check minimal prerequisites for run this server.
$this->check_prerequisites();
$this->addr = $addr;
$usessl = false;
if (PHP_SAPI !== 'cli') {
throw new Exception('This application must be run on the command line.');
}
// Get from command line arguments:
// * Port number.
// * Certificate file (optional).
// * Private key file (optional).
// * Buffer length (optional).
// * Verbose mode (optional).
// Parse command line arguments.
// unimoodleservercli.php port [-c certificatefile -p privatekeyfile] [-b bufferlength] [-v].
if (isset($_SERVER['argv'][1]) && is_numeric($_SERVER['argv'][1])) {
$port = $_SERVER['argv'][1];
unset($_SERVER['argv'][1]);
$_SERVER['argv'] = array_values($_SERVER['argv']);
}
// If the port is not set, then show the interactive form and execute the server.
if (!isset($port) || !is_numeric($port)) {
echo self::white_text('USAGE: unimoodleservercli.php port [-c certificatefile -p privatekeyfile -b bufferlength] [-v]', false) . PHP_EOL;
$this->executeform();
echo self::green_text(PHP_EOL .
'Socket is running in the background. You can see the process running in the process list of your server.');
die();
}
$verbosepos = array_search('-v', $_SERVER['argv'], true);
if ($verbosepos !== false) {
$this->verboselog = true;
unset($_SERVER['argv'][$verbosepos]);
$_SERVER['argv'] = array_values($_SERVER['argv']);
}
$certificate = '';
$privatekey = '';
$bufferlength = 16000; // Default buffer length.
// Check if buffer length is set.
$bufferlengthpos = array_search('-b', $_SERVER['argv'], true);
if (
$bufferlengthpos !== false && isset($_SERVER['argv'][$bufferlengthpos + 1])
&& is_numeric($_SERVER['argv'][$bufferlengthpos + 1])
) {
$bufferlength = (int)$_SERVER['argv'][$bufferlengthpos + 1];
unset($_SERVER['argv'][$bufferlengthpos], $_SERVER['argv'][$bufferlengthpos + 1]);
$_SERVER['argv'] = array_values($_SERVER['argv']);
}
// Check if certificate file is set.
$certificatepos = array_search('-c', $_SERVER['argv'], true);
if (
$certificatepos !== false
&& isset($_SERVER['argv'][$certificatepos + 1])
&& is_file($_SERVER['argv'][$certificatepos + 1])
) {
$certificate = $_SERVER['argv'][$certificatepos + 1];
unset($_SERVER['argv'][$certificatepos], $_SERVER['argv'][$certificatepos + 1]);
$_SERVER['argv'] = array_values($_SERVER['argv']);
}
// Check if private key file is set.
$privatekeypos = array_search('-p', $_SERVER['argv'], true);
if (
$privatekeypos !== false
&& isset($_SERVER['argv'][$privatekeypos + 1])
&& is_file($_SERVER['argv'][$privatekeypos + 1])
) {
$privatekey = $_SERVER['argv'][$privatekeypos + 1];
unset($_SERVER['argv'][$privatekeypos], $_SERVER['argv'][$privatekeypos + 1]);
$_SERVER['argv'] = array_values($_SERVER['argv']);
}
// Need both or none of certificate and private key.
if (($certificate !== '' && $privatekey === '') || ($certificate === '' && $privatekey !== '')) {
echo self::red_text(
'You must set both certificate and private key files or none of them. ' .
'Use -c certificatefile and -p privatekeyfile options with valid accessible files.'
);
die();
}
// If the certificate and private key are set, then set ssl mode.
if (isset($certificate) && is_file($certificate)) {
$usessl = true;
}
// If there are arguments left, then they are unknown options.
if (count($_SERVER['argv']) > 1) {
echo self::red_text(
'Unknown options: ' . implode(' ', $_SERVER['argv']) . PHP_EOL .
'Use -c certificatefile and -p privatekeyfile options for SSL mode.' . PHP_EOL .