-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathwebservice.php
1304 lines (1139 loc) · 46.7 KB
/
webservice.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 the Zoom plugin for 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/>.
/**
* Handles API calls to Zoom REST API.
*
* @package mod_zoom
* @copyright 2015 UC Regents
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_zoom;
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/mod/zoom/lib.php');
require_once($CFG->dirroot . '/mod/zoom/locallib.php');
require_once($CFG->libdir . '/filelib.php');
use cache;
use core_user;
use curl;
use moodle_exception;
use stdClass;
/**
* Web service class.
*/
class webservice {
/**
* API calls: maximum number of retries.
* @var int
*/
public const MAX_RETRIES = 5;
/**
* Default meeting_password_requirement object.
* @var array
*/
public const DEFAULT_MEETING_PASSWORD_REQUIREMENT = [
'length' => 0,
'consecutive_characters_length' => 0,
'have_letter' => false,
'have_number' => false,
'have_upper_and_lower_characters' => false,
'have_special_character' => false,
'only_allow_numeric' => false,
'weak_enhance_detection' => false,
];
/**
* Client ID
* @var string
*/
protected $clientid;
/**
* Client secret
* @var string
*/
protected $clientsecret;
/**
* Account ID
* @var string
*/
protected $accountid;
/**
* API base URL.
* @var string
*/
protected $apiurl;
/**
* Whether to recycle licenses.
* @var bool
*/
protected $recyclelicenses;
/**
* Whether to check instance users
* @var bool
*/
protected $instanceusers;
/**
* Maximum limit of paid users
* @var int
*/
protected $numlicenses;
/**
* List of users
* @var array
*/
protected static $userslist;
/**
* Number of retries we've made for make_call
* @var int
*/
protected $makecallretries = 0;
/**
* Granted OAuth scopes
* @var array
*/
protected $scopes;
/**
* The constructor for the webservice class.
* @throws moodle_exception Moodle exception is thrown for missing config settings.
*/
public function __construct() {
$config = get_config('zoom');
$requiredfields = [
'clientid',
'clientsecret',
'accountid',
];
try {
// Get and remember each required field.
foreach ($requiredfields as $requiredfield) {
if (!empty($config->$requiredfield)) {
$this->$requiredfield = $config->$requiredfield;
} else {
throw new moodle_exception('zoomerr_field_missing', 'mod_zoom', '', get_string($requiredfield, 'mod_zoom'));
}
}
// Get and remember the API URL.
$this->apiurl = zoom_get_api_url();
// Get and remember the plugin settings to recycle licenses.
if (!empty($config->utmost)) {
$this->recyclelicenses = $config->utmost;
$this->instanceusers = !empty($config->instanceusers);
}
if ($this->recyclelicenses) {
if (!empty($config->licensesnumber)) {
$this->numlicenses = $config->licensesnumber;
} else {
throw new moodle_exception('zoomerr_licensesnumber_missing', 'mod_zoom');
}
}
} catch (moodle_exception $exception) {
throw new moodle_exception('errorwebservice', 'mod_zoom', '', $exception->getMessage());
}
}
/**
* Makes the call to curl using the specified method, url, and parameter data.
* This has been moved out of make_call to make unit testing possible.
*
* @param \curl $curl The curl object used to make the request.
* @param string $method The HTTP method to use.
* @param string $url The URL to append to the API URL
* @param array|string $data The data to attach to the call.
* @return stdClass The call's result.
*/
protected function make_curl_call(&$curl, $method, $url, $data) {
return $curl->$method($url, $data);
}
/**
* Gets a curl object in order to make API calls. This function was created
* to enable unit testing for the webservice class.
* @return curl The curl object used to make the API calls
*/
protected function get_curl_object() {
global $CFG;
$proxyhost = get_config('zoom', 'proxyhost');
if (!empty($proxyhost)) {
$cfg = new stdClass();
$cfg->proxyhost = $CFG->proxyhost;
$cfg->proxyport = $CFG->proxyport;
$cfg->proxyuser = $CFG->proxyuser;
$cfg->proxypassword = $CFG->proxypassword;
$cfg->proxytype = $CFG->proxytype;
// Parse string as host:port, delimited by a colon (:).
[$host, $port] = explode(':', $proxyhost);
// Temporarily set new values on the global $CFG.
$CFG->proxyhost = $host;
$CFG->proxyport = $port;
$CFG->proxytype = 'HTTP';
$CFG->proxyuser = '';
$CFG->proxypassword = '';
}
// Create $curl, which implicitly uses the proxy settings from $CFG.
$curl = new curl();
if (!empty($proxyhost)) {
// Restore the stored global proxy settings from above.
$CFG->proxyhost = $cfg->proxyhost;
$CFG->proxyport = $cfg->proxyport;
$CFG->proxyuser = $cfg->proxyuser;
$CFG->proxypassword = $cfg->proxypassword;
$CFG->proxytype = $cfg->proxytype;
}
return $curl;
}
/**
* Makes a REST call.
*
* @param string $path The path to append to the API URL
* @param array|string $data The data to attach to the call.
* @param string $method The HTTP method to use.
* @return stdClass The call's result in JSON format.
* @throws moodle_exception Moodle exception is thrown for curl errors.
*/
private function make_call($path, $data = [], $method = 'get') {
$url = $this->apiurl . $path;
$method = strtolower($method);
$token = $this->get_access_token();
$curl = $this->get_curl_object();
$curl->setHeader('Authorization: Bearer ' . $token);
$curl->setHeader('Accept: application/json');
if ($method != 'get') {
$curl->setHeader('Content-Type: application/json');
$data = is_array($data) ? json_encode($data) : $data;
}
$attempts = 0;
do {
if ($attempts > 0) {
sleep(1);
debugging('retrying after curl error 35, retry attempt ' . $attempts);
}
$rawresponse = $this->make_curl_call($curl, $method, $url, $data);
$attempts++;
} while ($curl->get_errno() === 35 && $attempts <= self::MAX_RETRIES);
if ($curl->get_errno()) {
throw new moodle_exception('errorwebservice', 'mod_zoom', '', $curl->error);
}
$response = json_decode($rawresponse);
$httpstatus = $curl->get_info()['http_code'];
if ($httpstatus >= 400) {
switch ($httpstatus) {
case 400:
$errorstring = '';
if (!empty($response->errors)) {
foreach ($response->errors as $error) {
$errorstring .= ' ' . $error->message;
}
}
throw new bad_request_exception($response->message . $errorstring, $response->code);
case 404:
throw new not_found_exception($response->message, $response->code);
case 429:
$this->makecallretries += 1;
if ($this->makecallretries > self::MAX_RETRIES) {
throw new retry_failed_exception($response->message, $response->code);
}
$header = $curl->getResponse();
// Header can have mixed case, normalize it.
$header = array_change_key_case($header, CASE_LOWER);
// Default to 1 second for max requests per second limit.
$timediff = 1;
// Check if we hit the max requests per minute (only for Dashboard API).
if (
array_key_exists('x-ratelimit-type', $header) &&
$header['x-ratelimit-type'] == 'QPS' &&
strpos($path, 'metrics') !== false
) {
$timediff = 60; // Try the next minute.
} else if (array_key_exists('retry-after', $header)) {
$retryafter = strtotime($header['retry-after']);
$timediff = $retryafter - time();
// If we have no API calls remaining, save retry-after.
if ($header['x-ratelimit-remaining'] == 0 && !empty($retryafter)) {
set_config('retry-after', $retryafter, 'zoom');
throw new api_limit_exception($response->message, $response->code, $retryafter);
} else if (!(defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
// When running CLI we might want to know how many calls remaining.
debugging('x-ratelimit-remaining = ' . $header['x-ratelimit-remaining']);
}
}
debugging('Received 429 response, sleeping ' . strval($timediff) .
' seconds until next retry. Current retry: ' . $this->makecallretries);
if ($timediff > 0 && !(defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
sleep($timediff);
}
return $this->make_call($path, $data, $method);
default:
if ($response) {
throw new webservice_exception(
$response->message,
$response->code,
'errorwebservice',
'mod_zoom',
'',
$response->message
);
} else {
throw new moodle_exception('errorwebservice', 'mod_zoom', '', "HTTP Status $httpstatus");
}
}
}
$this->makecallretries = 0;
return $response;
}
/**
* Makes a paginated REST call.
* Makes a call like make_call() but specifically for GETs with paginated results.
*
* @param string $url The URL to append to the API URL
* @param array $data The data to attach to the call.
* @param string $datatoget The name of the array of the data to get.
* @return array The retrieved data.
* @see make_call()
*/
private function make_paginated_call($url, $data, $datatoget) {
$aggregatedata = [];
$data['page_size'] = ZOOM_MAX_RECORDS_PER_CALL;
do {
$callresult = null;
$moredata = false;
$callresult = $this->make_call($url, $data);
if ($callresult) {
$aggregatedata = array_merge($aggregatedata, $callresult->$datatoget);
if (!empty($callresult->next_page_token)) {
$data['next_page_token'] = $callresult->next_page_token;
$moredata = true;
} else if (!empty($callresult->page_number) && $callresult->page_number < $callresult->page_count) {
$data['page_number'] = $callresult->page_number + 1;
$moredata = true;
}
}
} while ($moredata);
return $aggregatedata;
}
/**
* Autocreate a user on Zoom.
*
* @param stdClass $user The user to create.
* @return bool Whether the user was succesfully created.
* @deprecated Has never been used by internal code.
*/
public function autocreate_user($user) {
// Classic: user:write:admin.
// Granular: user:write:user:admin.
$url = 'users';
$data = ['action' => 'autocreate'];
$data['user_info'] = [
'email' => zoom_get_api_identifier($user),
'type' => ZOOM_USER_TYPE_PRO,
'first_name' => $user->firstname,
'last_name' => $user->lastname,
'password' => base64_encode(random_bytes(16)),
];
try {
$this->make_call($url, $data, 'post');
} catch (moodle_exception $error) {
// If the user already exists, the error will contain 'User already in the account'.
if (strpos($error->getMessage(), 'User already in the account') === true) {
return false;
} else {
throw $error;
}
}
return true;
}
/**
* Get users list.
*
* @return array An array of users.
*/
public function list_users() {
if (empty(self::$userslist)) {
// Classic: user:read:admin.
// Granular: user:read:list_users:admin.
self::$userslist = $this->make_paginated_call('users', [], 'users');
}
return self::$userslist;
}
/**
* Checks whether the paid user license limit has been reached.
*
* Incrementally retrieves the active paid users and compares against $numlicenses.
* @see $numlicenses
* @return bool Whether the paid user license limit has been reached.
*/
private function paid_user_limit_reached() {
$userslist = $this->list_users();
$numusers = 0;
foreach ($userslist as $user) {
if ($user->type != ZOOM_USER_TYPE_BASIC) {
// Count the user if we're including all users or if the user is on this instance.
if (!$this->instanceusers || core_user::get_user_by_email($user->email)) {
$numusers++;
if ($numusers >= $this->numlicenses) {
return true;
}
}
}
}
return false;
}
/**
* Gets the ID of the user, of all the paid users, with the oldest last login time.
*
* @return string|false If user is found, returns the User ID. Otherwise, returns false.
*/
private function get_least_recently_active_paid_user_id() {
$usertimes = [];
// Classic: user:read:admin.
// Granular: user:read:list_users:admin.
$userslist = $this->list_users();
foreach ($userslist as $user) {
if ($user->type != ZOOM_USER_TYPE_BASIC && isset($user->last_login_time)) {
// Count the user if we're including all users or if the user is on this instance.
if (!$this->instanceusers || core_user::get_user_by_email($user->email)) {
$usertimes[$user->id] = strtotime($user->last_login_time);
}
}
}
if (!empty($usertimes)) {
return array_search(min($usertimes), $usertimes);
}
return false;
}
/**
* Gets a user's settings.
*
* @param string $userid The user's ID.
* @return stdClass The call's result in JSON format.
*/
public function get_user_settings($userid) {
// Classic: user:read:admin.
// Granular: user:read:settings:admin.
return $this->make_call('users/' . $userid . '/settings');
}
/**
* Gets the user's meeting security settings, including password requirements.
*
* @param string $userid The user's ID.
* @return stdClass The call's result in JSON format.
*/
public function get_account_meeting_security_settings($userid) {
// Classic: user:read:admin.
// Granular: user:read:settings:admin.
$url = 'users/' . $userid . '/settings?option=meeting_security';
try {
$response = $this->make_call($url);
$meetingsecurity = $response->meeting_security;
} catch (moodle_exception $error) {
// Only available for Paid account, return default settings.
$meetingsecurity = new stdClass();
// If some other error, show debug message.
if (isset($error->zoomerrorcode) && $error->zoomerrorcode != 200) {
debugging($error->getMessage());
}
}
// Set a default meeting password requirment if it is not present.
if (!isset($meetingsecurity->meeting_password_requirement)) {
$meetingsecurity->meeting_password_requirement = (object) self::DEFAULT_MEETING_PASSWORD_REQUIREMENT;
}
// Set a default encryption setting if it is not present.
if (!isset($meetingsecurity->end_to_end_encrypted_meetings)) {
$meetingsecurity->end_to_end_encrypted_meetings = false;
}
return $meetingsecurity;
}
/**
* Gets a user.
*
* @param string|int $identifier The user's email or the user's ID per Zoom API.
* @return stdClass|false If user is found, returns the User object. Otherwise, returns false.
*/
public function get_user($identifier) {
$founduser = false;
// Classic: user:read:admin.
// Granular: user:read:user:admin.
$url = 'users/' . $identifier;
try {
$founduser = $this->make_call($url);
} catch (webservice_exception $error) {
if (zoom_is_user_not_found_error($error)) {
return false;
} else {
throw $error;
}
}
return $founduser;
}
/**
* Gets a list of users that the given person can schedule meetings for.
*
* @param string $identifier The user's email or the user's ID per Zoom API.
* @return array|false If schedulers are returned array of {id,email} objects. Otherwise returns false.
*/
public function get_schedule_for_users($identifier) {
// Classic: user:read:admin.
// Granular: user:read:list_schedulers:admin.
$url = "users/{$identifier}/schedulers";
$schedulerswithoutkey = [];
$schedulers = [];
try {
$response = $this->make_call($url);
if (is_array($response->schedulers)) {
$schedulerswithoutkey = $response->schedulers;
}
foreach ($schedulerswithoutkey as $s) {
$schedulers[$s->id] = $s;
}
} catch (moodle_exception $error) {
// We don't care if this throws an exception.
$schedulers = [];
}
return $schedulers;
}
/**
* Converts a zoom object from database format to API format.
*
* The database and the API use different fields and formats for the same information. This function changes the
* database fields to the appropriate API request fields.
*
* @param stdClass $zoom The zoom meeting to format.
* @param ?int $cmid The cmid if available.
* @return array The formatted meetings for the meeting.
*/
private function database_to_api($zoom, $cmid) {
global $CFG;
$options = [];
if (!empty($cmid)) {
$options['context'] = \context_module::instance($cmid);
}
$data = [
// Process the meeting topic with proper filter.
'topic' => zoom_apply_filter_on_meeting_name($zoom->name, $options),
'settings' => [
'host_video' => (bool) ($zoom->option_host_video),
'audio' => $zoom->option_audio,
],
];
if (isset($zoom->intro)) {
// Process the description text with proper filter and then convert to plain text.
$data['agenda'] = substr(content_to_text(format_text(
$zoom->intro,
FORMAT_MOODLE,
$options
), false), 0, 2000);
}
if (isset($CFG->timezone) && !empty($CFG->timezone)) {
$data['timezone'] = $CFG->timezone;
} else {
$data['timezone'] = date_default_timezone_get();
}
if (isset($zoom->password)) {
$data['password'] = $zoom->password;
}
if (isset($zoom->schedule_for)) {
$data['schedule_for'] = $zoom->schedule_for;
}
if (isset($zoom->alternative_hosts)) {
$data['settings']['alternative_hosts'] = $zoom->alternative_hosts;
}
if (isset($zoom->option_authenticated_users)) {
$data['settings']['meeting_authentication'] = (bool) $zoom->option_authenticated_users;
}
if (isset($zoom->registration)) {
$data['settings']['approval_type'] = $zoom->registration;
}
if (!empty($zoom->webinar)) {
if ($zoom->recurring) {
if ($zoom->recurrence_type == ZOOM_RECURRINGTYPE_NOTIME) {
$data['type'] = ZOOM_RECURRING_WEBINAR;
} else {
$data['type'] = ZOOM_RECURRING_FIXED_WEBINAR;
}
} else {
$data['type'] = ZOOM_SCHEDULED_WEBINAR;
}
} else {
if ($zoom->recurring) {
if ($zoom->recurrence_type == ZOOM_RECURRINGTYPE_NOTIME) {
$data['type'] = ZOOM_RECURRING_MEETING;
} else {
$data['type'] = ZOOM_RECURRING_FIXED_MEETING;
}
} else {
$data['type'] = ZOOM_SCHEDULED_MEETING;
}
}
if (!empty($zoom->option_auto_recording)) {
$data['settings']['auto_recording'] = $zoom->option_auto_recording;
} else {
$recordingoption = get_config('zoom', 'recordingoption');
if ($recordingoption === ZOOM_AUTORECORDING_USERDEFAULT) {
if (isset($zoom->schedule_for)) {
$zoomuser = zoom_get_user($zoom->schedule_for);
$zoomuserid = $zoomuser->id;
} else {
$zoomuserid = zoom_get_user_id();
}
$autorecording = zoom_get_user_settings($zoomuserid)->recording->auto_recording;
$data['settings']['auto_recording'] = $autorecording;
} else {
$data['settings']['auto_recording'] = $recordingoption;
}
}
// Add fields which are effective for meetings only, but not for webinars.
if (empty($zoom->webinar)) {
$data['settings']['participant_video'] = (bool) ($zoom->option_participants_video);
$data['settings']['join_before_host'] = (bool) ($zoom->option_jbh);
$data['settings']['encryption_type'] = (isset($zoom->option_encryption_type) &&
$zoom->option_encryption_type === ZOOM_ENCRYPTION_TYPE_E2EE) ?
ZOOM_ENCRYPTION_TYPE_E2EE : ZOOM_ENCRYPTION_TYPE_ENHANCED;
$data['settings']['waiting_room'] = (bool) ($zoom->option_waiting_room);
$data['settings']['mute_upon_entry'] = (bool) ($zoom->option_mute_upon_entry);
}
// Add recurrence object.
if ($zoom->recurring && $zoom->recurrence_type != ZOOM_RECURRINGTYPE_NOTIME) {
$data['recurrence']['type'] = (int) $zoom->recurrence_type;
$data['recurrence']['repeat_interval'] = (int) $zoom->repeat_interval;
if ($zoom->recurrence_type == ZOOM_RECURRINGTYPE_WEEKLY) {
$data['recurrence']['weekly_days'] = $zoom->weekly_days;
}
if ($zoom->recurrence_type == ZOOM_RECURRINGTYPE_MONTHLY) {
if ($zoom->monthly_repeat_option == ZOOM_MONTHLY_REPEAT_OPTION_DAY) {
$data['recurrence']['monthly_day'] = (int) $zoom->monthly_day;
} else {
$data['recurrence']['monthly_week'] = (int) $zoom->monthly_week;
$data['recurrence']['monthly_week_day'] = (int) $zoom->monthly_week_day;
}
}
if ($zoom->end_date_option == ZOOM_END_DATE_OPTION_AFTER) {
$data['recurrence']['end_times'] = (int) $zoom->end_times;
} else {
$data['recurrence']['end_date_time'] = gmdate('Y-m-d\TH:i:s\Z', $zoom->end_date_time);
}
}
if (
$data['type'] === ZOOM_SCHEDULED_MEETING ||
$data['type'] === ZOOM_RECURRING_FIXED_MEETING ||
$data['type'] === ZOOM_SCHEDULED_WEBINAR ||
$data['type'] === ZOOM_RECURRING_FIXED_WEBINAR
) {
// Convert timestamp to ISO-8601. The API seems to insist that it end with 'Z' to indicate UTC.
$data['start_time'] = gmdate('Y-m-d\TH:i:s\Z', $zoom->start_time);
$data['duration'] = (int) ceil($zoom->duration / 60);
}
// Add tracking field to data.
$defaulttrackingfields = zoom_clean_tracking_fields();
$tfarray = [];
foreach ($defaulttrackingfields as $key => $defaulttrackingfield) {
if (isset($zoom->$key)) {
$tf = new stdClass();
$tf->field = $defaulttrackingfield;
$tf->value = $zoom->$key;
$tfarray[] = $tf;
}
}
$data['tracking_fields'] = $tfarray;
if (isset($zoom->breakoutrooms)) {
$breakoutroom = ['enable' => true, 'rooms' => $zoom->breakoutrooms];
$data['settings']['breakout_room'] = $breakoutroom;
}
return $data;
}
/**
* Provide a user with a license if needed and recycling is enabled.
*
* @param stdClass $zoomuserid The Zoom user to upgrade.
* @return void
*/
public function provide_license($zoomuserid) {
// Checks whether we need to recycle licenses and acts accordingly.
// Classic: user:read:admin.
// Granular: user:read:user:admin.
if ($this->recyclelicenses && $this->make_call("users/$zoomuserid")->type == ZOOM_USER_TYPE_BASIC) {
if ($this->paid_user_limit_reached()) {
$leastrecentlyactivepaiduserid = $this->get_least_recently_active_paid_user_id();
// Changes least_recently_active_user to a basic user so we can use their license.
$this->make_call("users/$leastrecentlyactivepaiduserid", ['type' => ZOOM_USER_TYPE_BASIC], 'patch');
}
// Changes current user to pro so they can make a meeting.
// Classic: user:write:admin.
// Granular: user:update:user:admin.
$this->make_call("users/$zoomuserid", ['type' => ZOOM_USER_TYPE_PRO], 'patch');
}
}
/**
* Create a meeting/webinar on Zoom.
* Take a $zoom object as returned from the Moodle form and respond with an object that can be saved to the database.
*
* @param stdClass $zoom The meeting to create.
* @param ?int $cmid The cmid if available.
* @return stdClass The call response.
*/
public function create_meeting($zoom, $cmid) {
// Provide license if needed.
$this->provide_license($zoom->host_id);
// Classic: meeting:write:admin.
// Granular: meeting:write:meeting:admin.
// Classic: webinar:write:admin.
// Granular: webinar:write:webinar:admin.
$url = "users/$zoom->host_id/" . (!empty($zoom->webinar) ? 'webinars' : 'meetings');
return $this->make_call($url, $this->database_to_api($zoom, $cmid), 'post');
}
/**
* Update a meeting/webinar on Zoom.
*
* @param stdClass $zoom The meeting to update.
* @param ?int $cmid The cmid if available.
* @return void
*/
public function update_meeting($zoom, $cmid) {
// Classic: meeting:write:admin.
// Granular: meeting:update:meeting:admin.
// Classic: webinar:write:admin.
// Granular: webinar:update:webinar:admin.
$url = ($zoom->webinar ? 'webinars/' : 'meetings/') . $zoom->meeting_id;
$this->make_call($url, $this->database_to_api($zoom, $cmid), 'patch');
}
/**
* Delete a meeting or webinar on Zoom.
*
* @param int $id The meeting_id or webinar_id of the meeting or webinar to delete.
* @param bool $webinar Whether the meeting or webinar you want to delete is a webinar.
* @return void
*/
public function delete_meeting($id, $webinar) {
// Classic: meeting:write:admin.
// Granular: meeting:delete:meeting:admin.
// Classic: webinar:write:admin.
// Granular: webinar:delete:webinar:admin.
$url = ($webinar ? 'webinars/' : 'meetings/') . $id . '?schedule_for_reminder=false';
$this->make_call($url, null, 'delete');
}
/**
* Get a meeting or webinar's information from Zoom.
*
* @param int $id The meeting_id or webinar_id of the meeting or webinar to retrieve.
* @param bool $webinar Whether the meeting or webinar whose information you want is a webinar.
* @return stdClass The meeting's or webinar's information.
*/
public function get_meeting_webinar_info($id, $webinar) {
// Classic: meeting:read:admin.
// Granular: meeting:read:meeting:admin.
// Classic: webinar:read:admin.
// Granular: webinar:read:webinar:admin.
$url = ($webinar ? 'webinars/' : 'meetings/') . $id;
$response = $this->make_call($url);
return $response;
}
/**
* Get the meeting invite note that was sent for a specific meeting from Zoom.
*
* @param stdClass $zoom The zoom meeting
* @return \mod_zoom\invitation The meeting's invitation.
*/
public function get_meeting_invitation($zoom) {
global $CFG;
require_once($CFG->dirroot . '/mod/zoom/classes/invitation.php');
// Webinar does not have meeting invite info.
if ($zoom->webinar) {
return new invitation(null);
}
// Classic: meeting:read:admin.
// Granular: meeting:read:invitation:admin.
$url = 'meetings/' . $zoom->meeting_id . '/invitation';
try {
$response = $this->make_call($url);
} catch (moodle_exception $error) {
debugging($error->getMessage());
return new invitation(null);
}
return new invitation($response->invitation);
}
/**
* Retrieve ended meetings report for a specified user and period. Handles multiple pages.
*
* @param string $userid Id of user of interest
* @param string $from Start date of period in the form YYYY-MM-DD
* @param string $to End date of period in the form YYYY-MM-DD
* @return array The retrieved meetings.
*/
public function get_user_report($userid, $from, $to) {
// Classic: report:read:admin.
// Granular: report:read:user:admin.
$url = 'report/users/' . $userid . '/meetings';
$data = ['from' => $from, 'to' => $to];
return $this->make_paginated_call($url, $data, 'meetings');
}
/**
* List all meeting or webinar information for a user.
*
* @param string $userid The user whose meetings or webinars to retrieve.
* @param boolean $webinar Whether to list meetings or to list webinars.
* @return array An array of meeting information.
* @deprecated Has never been used by internal code.
*/
public function list_meetings($userid, $webinar) {
// Classic: meeting:read:admin.
// Granular: meeting:read:list_meetings:admin.
// Classic: webinar:read:admin.
// Granular: webinar:read:list_webinars:admin.
$url = 'users/' . $userid . ($webinar ? '/webinars' : '/meetings');
$instances = $this->make_paginated_call($url, [], ($webinar ? 'webinars' : 'meetings'));
return $instances;
}
/**
* Get the participants who attended a meeting
* @param string $meetinguuid The meeting or webinar's UUID.
* @param bool $webinar Whether the meeting or webinar whose information you want is a webinar.
* @return array An array of meeting participant objects.
*/
public function get_meeting_participants($meetinguuid, $webinar) {
$meetinguuid = $this->encode_uuid($meetinguuid);
$meetingtype = ($webinar ? 'webinars' : 'meetings');
$meetingtypesingular = ($webinar ? 'webinar' : 'meeting');
$reportscopes = [
// Classic.
'report:read:admin',
// Granular.
'report:read:list_' . $meetingtypesingular . '_participants:admin',
];
$dashboardscopes = [
// Classic.
'dashboard_' . $meetingtype . ':read:admin',
// Granular.
'dashboard:read:list_' . $meetingtypesingular . '_participants:admin',
];
if ($this->has_scope($reportscopes)) {
$apitype = 'report';
} else if ($this->has_scope($dashboardscopes)) {
$apitype = 'metrics';
} else {
mtrace('Missing OAuth scopes required for reports.');
return [];
}
$url = $apitype . '/' . $meetingtype . '/' . $meetinguuid . '/participants';
return $this->make_paginated_call($url, [], 'participants');
}
/**
* Retrieve the UUIDs of hosts that were active in the last 30 days.
*
* @param int $from The time to start the query from, in Unix timestamp format.
* @param int $to The time to end the query at, in Unix timestamp format.
* @return array An array of UUIDs.
*/
public function get_active_hosts_uuids($from, $to) {
// Classic: report:read:admin.
// Granular: report:read:list_users:admin.
$users = $this->make_paginated_call('report/users', ['type' => 'active', 'from' => $from, 'to' => $to], 'users');
$uuids = [];
foreach ($users as $user) {
$uuids[] = $user->id;
}
return $uuids;
}
/**
* Retrieve past meetings that occurred in specified time period.
*
* Ignores meetings that were attended only by one user.
*
* NOTE: Requires Business or a higher plan and have "Dashboard" feature
* enabled. This query is rated "Resource-intensive"
*
* @param int $from Start date in YYYY-MM-DD format.
* @param int $to End date in YYYY-MM-DD format.
* @return array An array of meeting objects.
*/
public function get_meetings($from, $to) {
// Classic: dashboard_meetings:read:admin.
// Granular: dashboard:read:list_meetings:admin.
return $this->make_paginated_call(
'metrics/meetings',
[
'type' => 'past',
'from' => $from,
'to' => $to,
'query_date_type' => 'end_time',
],
'meetings'
);
}
/**
* Retrieve past meetings that occurred in specified time period.
*
* Ignores meetings that were attended only by one user.
*
* NOTE: Requires Business or a higher plan and have "Dashboard" feature