forked from blindsidenetworks-ps/moodle-mod_bigbluebuttonbn
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlocallib.php
4372 lines (4161 loc) · 155 KB
/
locallib.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
// 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/>.
/**
* Internal library of functions for module BigBlueButtonBN.
*
* @package mod_bigbluebuttonbn
* @copyright 2010 onwards, Blindside Networks Inc
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @author Jesus Federico (jesus [at] blindsidenetworks [dt] com)
* @author Fred Dixon (ffdixon [at] blindsidenetworks [dt] com)
*/
use mod_bigbluebuttonbn\locallib;
use mod_bigbluebuttonbn\plugin;
use mod_bigbluebuttonbn\task;
defined('MOODLE_INTERNAL') || die;
global $CFG;
require_once(__DIR__ . '/lib.php');
const BIGBLUEBUTTONBN_MAX_CONN = 500;
const BIGBLUEBUTTONBN_MAX_ROOM_CONN = 300;
/** @var BIGBLUEBUTTONBN_UPDATE_CACHE boolean set to true indicates that cache has to be updated */
const BIGBLUEBUTTONBN_UPDATE_CACHE = true;
/** @var BIGBLUEBUTTONBN_TYPE_ALL integer set to 0 defines an instance type that inclueds room and recordings */
const BIGBLUEBUTTONBN_TYPE_ALL = 0;
/** @var BIGBLUEBUTTONBN_TYPE_ROOM_ONLY integer set to 1 defines an instance type that inclueds only room */
const BIGBLUEBUTTONBN_TYPE_ROOM_ONLY = 1;
/** @var BIGBLUEBUTTONBN_TYPE_RECORDING_ONLY integer set to 2 defines an instance type that inclueds only recordings */
const BIGBLUEBUTTONBN_TYPE_RECORDING_ONLY = 2;
/** @var BIGBLUEBUTTONBN_ROLE_VIEWER string defines the bigbluebutton viewer role */
const BIGBLUEBUTTONBN_ROLE_VIEWER = 'viewer';
/** @var BIGBLUEBUTTONBN_ROLE_MODERATOR string defines the bigbluebutton moderator role */
const BIGBLUEBUTTONBN_ROLE_MODERATOR = 'moderator';
/** @var BIGBLUEBUTTON_EVENT_ACTIVITY_VIEWED string defines the bigbluebuttonbn activity_viewed event */
const BIGBLUEBUTTON_EVENT_ACTIVITY_VIEWED = 'activity_viewed';
/** @var BIGBLUEBUTTON_EVENT_ACTIVITY_MANAGEMENT_VIEWED string defines the bigbluebuttonbn activity_management_viewed event */
const BIGBLUEBUTTON_EVENT_ACTIVITY_MANAGEMENT_VIEWED = 'activity_management_viewed';
/** @var BIGBLUEBUTTON_EVENT_LIVE_SESSION string defines the bigbluebuttonbn live_session event */
const BIGBLUEBUTTON_EVENT_LIVE_SESSION = 'live_session';
/** @var BIGBLUEBUTTON_EVENT_MEETING_CREATED string defines the bigbluebuttonbn meeting_created event */
const BIGBLUEBUTTON_EVENT_MEETING_CREATED = 'meeting_created';
/** @var BIGBLUEBUTTON_EVENT_MEETING_ENDED string defines the bigbluebuttonbn meeting_ended event */
const BIGBLUEBUTTON_EVENT_MEETING_ENDED = 'meeting_ended';
/** @var BIGBLUEBUTTON_EVENT_MEETING_JOINED string defines the bigbluebuttonbn meeting_joined event */
const BIGBLUEBUTTON_EVENT_MEETING_JOINED = 'meeting_joined';
/** @var BIGBLUEBUTTON_EVENT_MEETING_LEFT string defines the bigbluebuttonbn meeting_left event */
const BIGBLUEBUTTON_EVENT_MEETING_LEFT = 'meeting_left';
/** @var BIGBLUEBUTTON_EVENT_RECORDING_DELETED string defines the bigbluebuttonbn recording_deleted event */
const BIGBLUEBUTTON_EVENT_RECORDING_DELETED = 'recording_deleted';
/** @var BIGBLUEBUTTON_EVENT_RECORDING_IMPORTED string defines the bigbluebuttonbn recording_imported event */
const BIGBLUEBUTTON_EVENT_RECORDING_IMPORTED = 'recording_imported';
/** @var BIGBLUEBUTTON_EVENT_RECORDING_PROTECTED string defines the bigbluebuttonbn recording_protected event */
const BIGBLUEBUTTON_EVENT_RECORDING_PROTECTED = 'recording_protected';
/** @var BIGBLUEBUTTON_EVENT_RECORDING_PUBLISHED string defines the bigbluebuttonbn recording_published event */
const BIGBLUEBUTTON_EVENT_RECORDING_PUBLISHED = 'recording_published';
/** @var BIGBLUEBUTTON_EVENT_RECORDING_UNPROTECTED string defines the bigbluebuttonbn recording_unprotected event */
const BIGBLUEBUTTON_EVENT_RECORDING_UNPROTECTED = 'recording_unprotected';
/** @var BIGBLUEBUTTON_EVENT_RECORDING_UNPUBLISHED string defines the bigbluebuttonbn recording_unpublished event */
const BIGBLUEBUTTON_EVENT_RECORDING_UNPUBLISHED = 'recording_unpublished';
/** @var BIGBLUEBUTTON_EVENT_RECORDING_EDITED string defines the bigbluebuttonbn recording_edited event */
const BIGBLUEBUTTON_EVENT_RECORDING_EDITED = 'recording_edited';
/** @var BIGBLUEBUTTON_EVENT_RECORDING_VIEWED string defines the bigbluebuttonbn recording_viewed event */
const BIGBLUEBUTTON_EVENT_RECORDING_VIEWED = 'recording_viewed';
/** @var BIGBLUEBUTTON_EVENT_MEETING_START string defines the bigbluebuttonbn meeting_start event */
const BIGBLUEBUTTON_EVENT_MEETING_START = 'meeting_start';
/** @var BIGBLUEBUTTON_CLIENTTYPE_FLASH integer that defines the bigbluebuttonbn default web client based on Adobe FLASH */
const BIGBLUEBUTTON_CLIENTTYPE_FLASH = 0;
/** @var BIGBLUEBUTTON_CLIENTTYPE_HTML5 integer that defines the bigbluebuttonbn default web client based on HTML5 */
const BIGBLUEBUTTON_CLIENTTYPE_HTML5 = 1;
/** @var BIGBLUEBUTTON_ORIGIN_BASE integer set to 0 defines that the user acceded the session from activity page */
const BIGBLUEBUTTON_ORIGIN_BASE = 0;
/** @var BIGBLUEBUTTON_ORIGIN_TIMELINE integer set to 1 defines that the user acceded the session from Timeline */
const BIGBLUEBUTTON_ORIGIN_TIMELINE = 1;
/** @var BIGBLUEBUTTON_ORIGIN_INDEX integer set to 2 defines that the user acceded the session from Index */
const BIGBLUEBUTTON_ORIGIN_INDEX = 2;
/**
* Builds and retunrs a url for joining a bigbluebutton meeting.
*
* @param string $meetingid
* @param string $username
* @param string $pw
* @param string $logouturl
* @param string $configtoken
* @param string $userid
* @param string $clienttype
*
* @return string
*/
function bigbluebuttonbn_get_join_url(
$meetingid,
$username,
$pw,
$logouturl,
$server = false,
$configtoken = null,
$userid = null,
$clienttype = BIGBLUEBUTTON_CLIENTTYPE_FLASH
) {
$data = ['meetingID' => $meetingid,
'fullName' => $username,
'password' => $pw,
'logoutURL' => $logouturl,
];
// Choose between Adobe Flash or HTML5 Client.
if ($clienttype == BIGBLUEBUTTON_CLIENTTYPE_HTML5) {
$data['joinViaHtml5'] = 'true';
}
if (!is_null($configtoken)) {
$data['configToken'] = $configtoken;
}
if (!is_null($userid)) {
$data['userID'] = $userid;
}
return \mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('join', $data, array(), $server);
}
function bbb_request_fast($url) {
if (extension_loaded('curl')) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: text/xml'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT , 3);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT , 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER , true);
$ret = curl_exec($ch);
curl_close($ch);
return $ret;
} else {
return '<response><returncode>ERROR</returncode><meetings/>'.
'<message>Missing CURL extension.</message></response>';
}
}
function bbb_server_check_health($n) {
$server_url = \mod_bigbluebuttonbn\locallib\bigbluebutton::root($n);
if (extension_loaded('curl')) {
$ch = curl_init($server_url.'/index.html');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: text/html'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT , 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT , 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER , true);
$ret = curl_exec($ch);
$code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
return $code == 200 ? 1 : 0 ;
} else {
return 0;
}
}
function bbb_server_bad_trace($server) {
if(0) error_log("bbb_server_check bad server '$server'\n".
format_backtrace(debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT),1),0);
}
function bbb_server_cache_dir() {
global $CFG;
$cachedir = $CFG->dataroot.'/bbbcache';
if(!is_dir($cachedir)) {
if(!mkdir($cachedir,0755))
throw new \Exception("Cant create $cachedir");
}
return $cachedir;
}
function bbb_server_healt($n) {
global $CFG;
if(isset($CFG->bigbluebuttonbn[$n]['off']))
return 0;
$cachedir = bbb_server_cache_dir();
$sfile = $cachedir.'/server_check_'.$n;
$ctm = time();
if(file_exists($sfile) && filemtime($sfile) > $ctm - 5) {
$data = file_get_contents($sfile,0);
if($data == '1') return 1;
bbb_server_bad_trace($n);
$CFG->bigbluebuttonbn[$n]['off'] = 1;
return 0;
}
if(bbb_server_check_health($n)) {
file_put_contents($sfile,'1');
return 1;
}
$CFG->bigbluebuttonbn[$n]['off'] = 1;
file_put_contents($sfile,'0');
bbb_server_bad_trace($n);
return 0;
}
function bbb_get_server_info_real($n) {
if(!bbb_server_healt($n)) {
return array(0=>0,'MSG'=>'Error');
}
$res = bbb_request_fast(
\mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('getMeetings',[],[],$n)
);
$previous = libxml_use_internal_errors(true);
try {
$ret = simplexml_load_string($res,'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);
} catch (Exception $e) {
libxml_use_internal_errors($previous);
$error = 'Caught exception: ' . $e->getMessage();
debugging($error, DEBUG_DEVELOPER);
return array(0=>0,'MSG'=>'Bad xml response');
}
if(!(isset($ret->returncode) && $ret->returncode == 'SUCCESS')) {
return array(0=>0,'MSG'=>isset($ret->message) ? $ret->message:'Error');
}
#print_r($ret);
$m_count = 0;
$m_list = 0;
$m_list_max = 0;
$m_video = 0;
$m_video_max = 0;
$trc = 0;
$m_info = array();
foreach ($ret->meetings as $m) {
foreach ($m->meeting as $i) {
#print_r($i);
$m_count++;
$m_c = intval($i->participantCount); # $i->videoCount + $i->moderatorCount + $i->listenerCount;
$m_v = intval($i->videoCount);
$m_m = intval($i->moderatorCount);
$m_list += $m_c;
$m_video += $m_v;
if($m_list_max < $m_c ) $m_list_max = $m_c;
if($m_video_max < $m_v) $m_video_max = $m_v;
$rc = $m_c + ($m_v + ($m_v > 4 ? $m_v/3 : 0)) * 10;
$trc += $rc;
$m_info[] = array('Name'=> $i->meetingName . '',
'LMS'=>((array)$i->metadata)['bbb-origin-server-name'],
'LMSx'=>((array)$i->metadata)['bbb-origin'],
'Course'=>((array)$i->metadata)['bbb-context'],
'Name'=>((array)$i->metadata)['bbb-recording-name'],
'Users'=>$m_c,
'Videos'=>$m_v,
'Moderators'=>intval($i->moderatorCount),
'StartTime'=>date('Y-m-d H:i:s',intval(intval($i->startTime)/1000)),
'imID'=>strval($i->internalMeetingID),
'emID'=>strval($i->meetingID));
}
}
$trc += $m_count*30;
#error_log("BBB_Get_Info ($n) MC=$m_count LC=$m_list LM=$m_list_max VC=$m_video VM=$m_video_max\n",0);
return array(0=>1,'time'=>time(), 'info'=>$m_info, 'RC'=>$trc, 'MC'=>$m_count, 'LC'=>$m_list,
'LM'=>$m_list_max, 'VC'=>$m_video, 'VM'=>$m_video_max);
}
function bbb_get_server_info($n) {
global $CFG;
$cachedir = bbb_server_cache_dir();
$cachefile = $cachedir.'/server_'.$n;
clearstatcache(false,$cachefile);
$data = file_exists($cachefile) ? file_get_contents($cachefile,0): false;
if($data !== false) {
$info = unserialize($data);
if(isset($info['time']) && $info['time'] > time()-5) {
#error_log("BBB_Get_Info ($n) cache\n",0);
return $info;
}
}
$info = bbb_get_server_info_real($n);
if(file_exists($cachedir.'/timelen_'.$n)) {
$data = intval(file_get_contents($cachedir.'/timelen_'.$n,0));
$info['reclen'] = $data;
}
if($info[0]) {
file_put_contents($cachefile,serialize($info));
}
return $info;
}
function bbb_select_server() {
$server_list = bbb_server_restrict();
$load = [];
$min_rc = false;
$s_rc = false;
foreach($server_list as $k=>$s) {
if(!$k) continue;
if(isset($s['denybbbserver']) && $s['denybbbserver'])
continue;
if(isset($s['autobbbserver']) && $s['autobbbserver'])
continue;
$load[$k] = bbb_get_server_info($k);
if(!$load[$k][0]) continue;
$ratio = $load[$k]['RC'] * $s['multbbbserver'] / 100 + $s['costbbbserver'];
if($s_rc === false || $ratio < $min_rc) {
$s_rc = $k;
$min_rc = $ratio;
}
}
return $s_rc;
}
function bbb_select_server_select_sort($a,$b) {
$va = intval($a[1]) ?? 0;
$vb = intval($b[1]) ?? 0;
if($va != $vb) return $va - $vb;
return strcmp($a[2],$b[2]);
}
function bbb_select_server_select() {
$server_list = bbb_server_restrict();
$ret = [0=>'Any'];
$order = [];
$min_rc = false;
$s_rc = false;
foreach($server_list as $k=>$s) {
if(!$k) continue;
$order[$k] = [$k,$s['show_order'] ?? 0,$s['server_name']];
}
uasort($order,'bbb_select_server_select_sort');
foreach($order as $sr) {
$k = $sr[0];
if(!$k) continue;
$s = $server_list[$k];
if(isset($s['denybbbserver']) && $s['denybbbserver'])
continue;
if(!bbb_server_healt($k)) continue;
$ret[$k] = $s['server_name'];
}
return $ret;
}
function bbb_get_meeting_server_cache() {
$cache = cache::make_from_params( cache_store::MODE_APPLICATION, 'mod_bigbluebuttonbn',
'meeting_server');
if(!$cache) throw new \Exception("Can't get cache mod_bigbluebuttonbn");
return $cache;
}
function bbb_set_meeting_server($meetingid,$server,$state=0) {
if(!$server) throw new \Exception("bbb_set_meeting_server server < 1");
$cache = bbb_get_meeting_server_cache();
if($state) {
#error_log("bbb_set_meeting_server $server for $meetingid",0);
$cache->set($meetingid,$server);
} else {
#error_log("bbb_del_meeting_server $server for $meetingid",0);
$cache->delete($meetingid);
}
}
function bbb_check_events_auth($auth,&$server) {
if(intval($server) > 0) {
$key = \mod_bigbluebuttonbn\locallib\config::get('shared_secret',$server);
if(!$key)
throw new \Exception("bigbluebuttonbn bad shared key for server $server");
return \Firebase\JWT\JWT::decode($auth,$key,array('HS512'));
}
$slist = \mod_bigbluebuttonbn\locallib\config::server_list();
foreach($slist as $srv=>$s) {
if(!isset($s['shared_secret']) || !$s['shared_secret']) continue;
try {
$server = $srv;
return \Firebase\JWT\JWT::decode($auth,$s['shared_secret'],array('HS512'));
} catch (Exception $e) {
#
}
}
throw new \Exception("bigbluebuttonbn invalid auth");
}
function bbb_access_recording_update($recordingID,$server) {
global $CFG;
if(!isset($CFG->bigbluebuttonbn[$server]['restrict_view'])) return;
if($CFG->bigbluebuttonbn[$server]['restrict_view'] !== true) return;
$ckname = 'MoodleSession'.($CFG->sessioncookie ?? '');
if(!isset($_COOKIE[$ckname])) return;
if(!count($recordingID)) return;
$ca = $_COOKIE[$ckname];
$records = $recordingID;
sort($records);
$key = md5($server.implode('',$records).$ca);
$tm = time();
$cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'mod_bigbluebuttonbn', 'access_cache');
$val = $cache->get($key);
if($val !== false && $val > $tm - 10) return;
$cache->set($key,$tm);
#error_log("access_recording_update $server $key $tm $ca ".implode(' ',$records)."\n",0);
$srvurl = \mod_bigbluebuttonbn\locallib\bigbluebutton::root($server).'add_access';
$res = bigbluebuttonbn_wrap_xml_load_file_curl_request($srvurl, 'POST',
json_encode(array('rid'=>$records,'sid'=>$ca)),'application/x-www-form-urlencoded');
}
function bbb_access_ip_update($server) {
global $CFG;
if(!isset($CFG->bigbluebuttonbn[$server]['restrict_view'])) return;
if($CFG->bigbluebuttonbn[$server]['restrict_view'] !== true) return;
$srvurl = \mod_bigbluebuttonbn\locallib\bigbluebutton::root($server).'add_access';
#error_log("access_ip_update ".getremoteaddr()."\n",0);
$res = bigbluebuttonbn_wrap_xml_load_file_curl_request($srvurl, 'POST',
json_encode(array('ip'=>getremoteaddr())),'application/x-www-form-urlencoded');
}
function bbb_get_meeting_server($meetingid) {
global $DB;
$cache = bbb_get_meeting_server_cache();
$server = $cache->get($meetingid);
if($server !== false && is_array($server) && intval($server[1]) > 0) {
if(bigbluebuttonbn_is_meeting_running($meetingid,BIGBLUEBUTTONBN_UPDATE_CACHE,$server[1])) {
$cache->set($meetingid,[time(),$server[1]]);
return $server[1];
}
}
// check all servers
$server_list = bbb_server_restrict();
$servers = [];
foreach($server_list as $server=>$s) {
if(!intval($server)) continue;
if(!bbb_server_healt($server)) continue;
if(bigbluebuttonbn_is_meeting_running($meetingid,BIGBLUEBUTTONBN_UPDATE_CACHE,$server)) {
$servers[] = $server;
}
}
if(count($servers) > 1)
error_log("get_meeting_server BUG $meetingid servers '".implode(',',$servers)."'",0);
if(count($servers) > 0) {
$cache->set($meetingid,[time(),$servers[0]]);
# error_log("get_meeting_server LOST INFO {$servers[0]} $meetingid \n".
# format_backtrace(debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT),1),0);
return $servers[0];
}
# error_log("get_meeting_server $meetingid NO\n",0);
return false;
}
function bbb_tdelta2asc($ts) {
if($ts < 60)
return sprintf("%02ds",$ts);
$sec = $ts % 60; $ts = intval($ts/60);
if($ts < 60)
return sprintf("%02d:%02d",$ts, $sec);
$min = $ts % 60; $ts = intval($ts/60);
return sprintf("%02d:%02d:%02d",$ts,$min,$sec);
}
function bbb_tsc2asc($ts,$ts2 = false) {
$ts = intval($ts/1000);
if($ts2 === false)
return date("H:i:s",$ts);
$ts2 = intval($ts2/1000);
return date("H:i:s",$ts).'-'.date("H:i:s",$ts2).
' ('.bbb_tdelta2asc($ts2-$ts).')';
}
#function bbb_get_meeting_server_log($meetingid) {
# global $DB;
#
# $server = bbb_get_meeting_server($meetingid);
# if($server !== false) return $server;
#
# $sql = "select id,server,timecreated from {bigbluebuttonbn_logs} where meetingid=? ";
# $sql .= ' AND log = ? AND meta LIKE ? order by timecreated desc limit 1';
# $server_list = $DB->get_records_sql($sql,
# array($meetingid,BIGBLUEBUTTONBN_LOG_EVENT_CREATE,'%"record":"true"%'));
#
# foreach($server_list as $s) {
# $server = $s->server;
# #error_log("bbb get_meeting_server DB server: $server for $meetingid",0);
# break;
# }
## if(!$server) error_log("bbb get_meeting_server NOTFOUND server for $meetingid",0);
#
# return $server;
#}
/**
* Creates a bigbluebutton meeting and returns the response in an array.
*
* @param array $data
* @param array $metadata
* @param string $pname
* @param string $purl
*
* @return array
*/
function bigbluebuttonbn_get_create_meeting_array($data, $metadata = array(), $pname = null, $purl = null, $server=false) {
$createmeetingurl = \mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('create', $data, $metadata, $server);
$method = 'GET';
$data = null;
if (!is_null($pname) && !is_null($purl)) {
$method = 'POST';
$data = "<?xml version='1.0' encoding='UTF-8'?><modules><module name='presentation'><document url='" .
$purl . "' /></module></modules>"; // <?
}
$xml = bigbluebuttonbn_wrap_xml_load_file($createmeetingurl, $method, $data);
if ($xml) {
$response = array('returncode' => $xml->returncode, 'message' => $xml->message, 'messageKey' => $xml->messageKey);
if ($xml->meetingID) {
$response += array('meetingID' => $xml->meetingID, 'attendeePW' => $xml->attendeePW,
'moderatorPW' => $xml->moderatorPW, 'hasBeenForciblyEnded' => $xml->hasBeenForciblyEnded);
}
return $response;
}
return array('returncode' => 'FAILED', 'message' => 'unreachable', 'messageKey' => 'Server is unreachable');
}
/**
* Fetch meeting info and wrap response in array.
*
* @param string $meetingid
*
* @return array
*/
function bigbluebuttonbn_get_meeting_info_array($meetingid, $server=false) {
if(bbb_server_healt($server)) {
$xml = bigbluebuttonbn_wrap_xml_load_file(
\mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('getMeetingInfo', ['meetingID' => $meetingid],
array(),$server)
);
if ($xml && $xml->returncode == 'SUCCESS' && empty($xml->messageKey)) {
// Meeting info was returned.
return array('returncode' => $xml->returncode,
'meetingID' => $xml->meetingID,
'moderatorPW' => $xml->moderatorPW,
'attendeePW' => $xml->attendeePW,
'hasBeenForciblyEnded' => $xml->hasBeenForciblyEnded,
'running' => $xml->running,
'recording' => $xml->recording,
'startTime' => $xml->startTime,
'endTime' => $xml->endTime,
'participantCount' => $xml->participantCount,
'moderatorCount' => $xml->moderatorCount,
'attendees' => $xml->attendees,
'metadata' => $xml->metadata,
);
}
if ($xml) {
// Either failure or success without meeting info.
return (array) $xml;
}
}
// If the server is unreachable, then prompts the user of the necessary action.
return array('returncode' => 'FAILED', 'message' => 'unreachable', 'messageKey' => 'Server is unreachable');
}
/**
* Helper function to retrieve recordings from a BigBlueButton server.
*
* @param string|array $meetingids list of meetingIDs "mid1,mid2,mid3" or array("mid1","mid2","mid3")
* @param string|array $recordingids list of $recordingids "rid1,rid2,rid3" or array("rid1","rid2","rid3") for filtering
*
* @return associative array with recordings indexed by recordID, each recording is a non sequential associative array
*/
function bigbluebuttonbn_get_recordings_array($meetingids, $recordingids = [], $server = false) {
$meetingidsarray = $meetingids;
if (!is_array($meetingids)) {
$meetingidsarray = explode(',', $meetingids);
}
// If $meetingidsarray is empty there is no need to go further.
if (empty($meetingidsarray)) {
return array();
}
$recordings = bigbluebuttonbn_get_recordings_array_fetch($meetingidsarray, $server);
// Sort recordings.
uasort($recordings, 'bigbluebuttonbn_recording_build_sorter');
// Filter recordings based on recordingIDs.
$recordingidsarray = $recordingids;
if (!is_array($recordingids)) {
$recordingidsarray = explode(',', $recordingids);
}
if (empty($recordingidsarray)) {
// No recording ids, no need to filter.
return $recordings;
}
return bigbluebuttonbn_get_recordings_array_filter($recordingidsarray, $recordings);
}
/**
* Helper function to fetch recordings from a BigBlueButton server.
*
* @param array $meetingidsarray array with meeting ids in the form array("mid1","mid2","mid3")
*
* @return array (associative) with recordings indexed by recordID, each recording is a non sequential associative array
*/
function bigbluebuttonbn_get_recordings_array_fetch($meetingidsarray, $server) {
if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)
|| defined('BEHAT_SITE_RUNNING')
|| defined('BEHAT_TEST')
|| defined('BEHAT_UTIL')) {
// Just return the fake recording.
global $CFG;
require_once($CFG->libdir . '/testing/generator/lib.php');
require_once(__DIR__ . '/tests/generator/lib.php');
return mod_bigbluebuttonbn_generator::bigbluebuttonbn_get_recordings_array_fetch($meetingidsarray);
}
$recordings = array();
// Execute a paginated getRecordings request.
$pagecount = 25;
$pages = floor(count($meetingidsarray) / $pagecount) + 1;
if (count($meetingidsarray) > 0 && count($meetingidsarray) % $pagecount == 0) {
$pages--;
}
for ($page = 1; $page <= $pages; ++$page) {
$mids = array_slice($meetingidsarray, ($page - 1) * $pagecount, $pagecount);
$recordings += bigbluebuttonbn_get_recordings_array_fetch_page($mids,$server);
}
return $recordings;
}
/**
* Helper function to fetch one page of upto 25 recordings from a BigBlueButton server.
*
* @param array $mids
*
* @return array
*/
function bigbluebuttonbn_get_recordings_array_fetch_page($mids, $xserver) {
global $CFG,$DB;
$recordings = array();
$missing_rid = array();
$recID = array();
$servers = [];
if($xserver === false || !$xserver) {
$slist = \mod_bigbluebuttonbn\locallib\config::server_list();
if(!$slist) throw new \Exception('bigbluebuttonbn_get_recordings_array_fetch_page server missing');
$servers = array_keys($slist);
} else {
$servers = [$xserver];
}
$tm1 = time();
$cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'mod_bigbluebuttonbn', 'records_cache');
foreach($servers as $server) {
foreach($mids as $mid) {
$result = $cache->get($server.'_'.$mid);
if($result === false || ( isset($result['lastupdate']) && $result['lastupdate'] < $tm1 - 60)) {
$missing_rid[$mid] = 1;
} else {
foreach($result as $m => $r) {
if($m == 'lastupdate') continue;
if(!isset($r['recordID'])) continue;
$nc = $cache->get('p_'.$server.'_'.$r['recordID']);
if($nc !== false) {
if($tm1 < $nc + 3) {
$missing_rid[$mid] = 1;
} else {
$cache->delete('p_'.$server.'_'.$r['recordID']);
}
}
}
if(isset($missing_rid[$mid])) continue;
foreach($result as $m => $r) {
if($m == 'lastupdate') continue;
if(!isset($r['recordID'])) continue;
$recordings[$r['recordID']] = $r;
$recID[$r['recordID']] = 1;
}
}
}
}
if(!count(array_keys($missing_rid))) {
foreach($servers as $server)
bbb_access_recording_update(array_keys($recordings),$server);
return $recordings;
}
foreach($servers as $server) {
// Do getRecordings is executed using a method GET (supported by all versions of BBB).
$url = \mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('getRecordings',
['meetingID' => implode(',', array_keys($missing_rid))], array(),$server);
if(!bbb_server_healt($server)) continue; #return $recordings;
$xml = bigbluebuttonbn_wrap_xml_load_file($url);
if ($xml && $xml->returncode == 'SUCCESS' && isset($xml->recordings)) {
// If there were meetings already created.
$meetID = array();
foreach ($xml->recordings->recording as $recordingxml) {
$recording = bigbluebuttonbn_get_recording_array_value($recordingxml);
$recording['server'] = $server;
$mid = $recording['meetingID'];
$rid = $recording['recordID'];
$recordings[$rid] = $recording;
if(!isset($meetID[$mid])) $meetID[$mid] = array();
$meetID[$mid][$rid] = $recording;
$meetID[$mid]['lastupdate'] = $tm1;
$recID[$rid] = 1;
// Check if there is childs.
if (isset($recordingxml->breakoutRooms->breakoutRoom)) {
foreach ($recordingxml->breakoutRooms->breakoutRoom as $breakoutroom) {
$url = \mod_bigbluebuttonbn\locallib\bigbluebutton::action_url(
'getRecordings',
['recordID' => implode(',', (array) $breakoutroom)], array(), $server
);
$xml = bigbluebuttonbn_wrap_xml_load_file($url);
if ($xml && $xml->returncode == 'SUCCESS' && isset($xml->recordings)) {
// If there were meetings already created.
foreach ($xml->recordings->recording as $recordingxml) {
$recording = bigbluebuttonbn_get_recording_array_value($recordingxml);
$recordings[$rid] = $recording;
}
}
}
}
}
foreach($meetID as $m => $r) {
if($m == 'lastupdate') continue;
foreach($r as &$r2) {
if(!is_array($r2)) continue; # skip update_time
if(!isset($r2['recordID'])) continue;
#error_log("get record ".print_r($r2,1),3,"/tmp/lms.bbb-old-rec.log");
$pinfo = $DB->get_record_sql("select last_play from {bigbluebuttonbn_rec}
where meetinguid = ? and server = ?",[$r2['recordID'],$r2['server']]);
$r2['last_play'] = $pinfo->last_play ?? 0;
#error_log("get record ".print_r([$r2['recordID'],$r2['server'],$pinfo],1),3,"/tmp/lms.bbb-old-rec.log");
$cache->set($server.'_r_'.$r2['recordID'],$m);
}
$cache->set($server.'_'.$m,$r);
}
bbb_access_recording_update(array_keys($recID),$server);
}
}
return $recordings;
}
/**
* Helper function to remove a set of recordings from an array.
*
* @param array $rids
* @param array $recordings
*
* @return array
*/
function bigbluebuttonbn_get_recordings_array_filter($rids, &$recordings) {
foreach ($recordings as $key => $recording) {
if (!in_array($recording['recordID'], $rids)) {
unset($recordings[$key]);
}
}
return $recordings;
}
/**
* Helper function to retrieve imported recordings from the Moodle database.
* The references are stored as events in bigbluebuttonbn_logs.
*
* @param string $courseid
* @param string $bigbluebuttonbnid
* @param bool $subset
*
* @return associative array with imported recordings indexed by recordID, each recording
* is a non sequential associative array that corresponds to the actual recording in BBB
*/
function bigbluebuttonbn_get_recordings_imported_array($courseid = 0, $bigbluebuttonbnid = null, $subset = true) {
global $DB;
$select = bigbluebuttonbn_get_recordings_imported_sql_select($courseid, $bigbluebuttonbnid, $subset);
$recordsimported = $DB->get_records_select('bigbluebuttonbn_logs', $select);
$recordsimportedarray = array();
foreach ($recordsimported as $recordimported) {
$meta = json_decode($recordimported->meta, true);
$recording = $meta['recording'];
// Override imported flag with actual ID.
$recording['imported'] = $recordimported->id;
if (isset($recordimported->protected)) {
$recording['protected'] = (string) $recordimported->protected;
}
$recordsimportedarray[$recording['recordID']] = $recording;
}
return $recordsimportedarray;
}
/**
* Helper function to retrive the default config.xml file.
*
* @return string
*/
function bigbluebuttonbn_get_default_config_xml($sever=false) {
$xml = bigbluebuttonbn_wrap_xml_load_file(
\mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('getDefaultConfigXML',
array(),array(),$server)
);
return $xml;
}
/**
* Helper function to convert an xml recording object to an array in the format used by the plugin.
*
* @param object $recording
*
* @return array
*/
function bigbluebuttonbn_get_recording_array_value($recording) {
// Add formats.
$playbackarray = array();
foreach ($recording->playback->format as $format) {
$playbackarray[(string) $format->type] = array('type' => (string) $format->type,
'url' => trim((string) $format->url), 'length' => (string) $format->length);
// Add preview per format when existing.
if ($format->preview) {
$playbackarray[(string) $format->type]['preview'] = bigbluebuttonbn_get_recording_preview_images($format->preview);
}
}
// Add the metadata to the recordings array.
$metadataarray = bigbluebuttonbn_get_recording_array_meta(get_object_vars($recording->metadata));
$recordingarray = array('recordID' => (string) $recording->recordID,
'meetingID' => (string) $recording->meetingID, 'meetingName' => (string) $recording->name,
'published' => (string) $recording->published, 'startTime' => (string) $recording->startTime,
'endTime' => (string) $recording->endTime, 'playbacks' => $playbackarray);
if (isset($recording->protected)) {
$recordingarray['protected'] = (string) $recording->protected;
}
return $recordingarray + $metadataarray;
}
/**
* Helper function to convert an xml recording preview images to an array in the format used by the plugin.
*
* @param object $preview
*
* @return array
*/
function bigbluebuttonbn_get_recording_preview_images($preview) {
$imagesarray = array();
foreach ($preview->images->image as $image) {
$imagearray = array('url' => trim((string) $image));
foreach ($image->attributes() as $attkey => $attvalue) {
$imagearray[$attkey] = (string) $attvalue;
}
array_push($imagesarray, $imagearray);
}
return $imagesarray;
}
/**
* Helper function to convert an xml recording metadata object to an array in the format used by the plugin.
*
* @param array $metadata
*
* @return array
*/
function bigbluebuttonbn_get_recording_array_meta($metadata) {
$metadataarray = array();
foreach ($metadata as $key => $value) {
if (is_object($value)) {
$value = '';
}
$metadataarray['meta_' . $key] = $value;
}
return $metadataarray;
}
/**
* Helper function to sort an array of recordings. It compares the startTime in two recording objecs.
*
* @param object $a
* @param object $b
*
* @return array
*/
function bigbluebuttonbn_recording_build_sorter($a, $b) {
global $CFG;
$resultless = !empty($CFG->bigbluebuttonbn_recordings_sortorder) ? -1 : 1;
$resultmore = !empty($CFG->bigbluebuttonbn_recordings_sortorder) ? 1 : -1;
if ($a['startTime'] < $b['startTime']) {
return $resultless;
}
if ($a['startTime'] == $b['startTime']) {
return 0;
}
return $resultmore;
}
function bigbluebuttonbn_recordings_cache_update($recordids, $server) {
$cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'mod_bigbluebuttonbn', 'records_cache');
if(!$cache) return;
if(!is_array($recordids)) {
$r = $recordids;
$recordids = [ $r ];
}
foreach($recordids as $rid) {
$mid = $cache->get($server.'_r_'.$rid);
if($mid !== false) {
# error_log("bigbluebuttonbn_recordings_cache_update $server $rid -> $mid",0);
$cache->delete($server.'_'.$mid);
$cache->delete($server.'_r_'.$rid);
}
}
}
/**
* Perform deleteRecordings on BBB.
*
* @param string $recordids
*
* @return boolean
*/
function bigbluebuttonbn_delete_recordings($recordids, $server = false) {
if($server === false)
throw new \Exception("bigbluebuttonbn_delete_recordings server missing");
$cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'mod_bigbluebuttonbn', 'records_cache');
$ids = explode(',', $recordids);
foreach ($ids as $id) {
$xml = bigbluebuttonbn_wrap_xml_load_file(
\mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('deleteRecordings', ['recordID' => $id],
array(), $server)
);
if ($xml && $xml->returncode != 'SUCCESS') {
return false;
}
usleep(200000);
$crec = $cache->set('p_'.$server.'_'.$id,time());
}
bigbluebuttonbn_recordings_cache_update($ids, $server);
return true;
}
/**
* Perform publishRecordings on BBB.
*
* @param string $recordids
* @param string $publish
*/
function bigbluebuttonbn_publish_recordings($recordids, $publish = 'true', $server=false) {
if($server === false)
throw new \Exception("bigbluebuttonbn_publish_recordings server missing");
$cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'mod_bigbluebuttonbn', 'records_cache');
$ids = explode(',', $recordids);
foreach ($ids as $id) {
$xml = bigbluebuttonbn_wrap_xml_load_file(
\mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('publishRecordings', ['recordID' => $id, 'publish' => $publish],
array(),$server)
);
if ($xml && $xml->returncode != 'SUCCESS') {
return false;
}
usleep(200000);
$crec = $cache->set('p_'.$server.'_'.$id,time());
}
bigbluebuttonbn_recordings_cache_update($ids, $server);
return true;
}
/**
* Perform updateRecordings on BBB.
*
* @param string $recordids
* @param array $params ['key'=>param_key, 'value']
*/
function bigbluebuttonbn_update_recordings($recordids, $params, $server=false) {
if($server === false)
throw new \Exception("bigbluebuttonbn_update_recordings server missing");
$cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'mod_bigbluebuttonbn', 'records_cache');
$ids = explode(',', $recordids);
foreach ($ids as $id) {
$xml = bigbluebuttonbn_wrap_xml_load_file(
\mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('updateRecordings', ['recordID' => $id] + (array) $params,
array(), $server)
);
if ($xml && $xml->returncode != 'SUCCESS') {
return false;
}
usleep(200000);
$crec = $cache->set('p_'.$server.'_'.$id,time());
}
bigbluebuttonbn_recordings_cache_update($ids, $server);
return true;
}
/**
* Perform end on BBB.
*
* @param string $meetingid
* @param string $modpw
*/
function bigbluebuttonbn_end_meeting($meetingid, $modpw, $server=false) {
$xml = bigbluebuttonbn_wrap_xml_load_file(
\mod_bigbluebuttonbn\locallib\bigbluebutton::action_url('end', ['meetingID' => $meetingid, 'password' => $modpw],
array(), $server)
);
if ($xml) {
// If the xml packet returned failure it displays the message to the user.