1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
zoom.php
См. документацию.
1<?php
2
6use \Bitrix\Main\Localization\Loc;
11use \Bitrix\Main\Web\HttpClient;
12use \Bitrix\Main\Web\Json;
13use \Bitrix\Main\Web\JWT;
16
17IncludeModuleLangFile(__FILE__);
18
20{
21 public const ID = 'zoom';
22 private const CONTROLLER_URL = 'https://www.bitrix24.com/controller';
23 private const LOGIN_PREFIX = 'zoom_';
24 public const EMPTY_TYPE = "EMPTY";
25
26 protected $entityOAuth;
27
28 public function __construct($userId = null)
29 {
30 $this->getEntityOAuth();
31
32 parent::__construct($userId);
33 }
34
35 public function GetSettings()
36 {
37 return [
38 ['zoom_client_id', Loc::getMessage('SOCSERV_ZOOM_CLIENT_ID'), '', ['text', 40]],
39 ['zoom_client_secret', Loc::getMessage('SOCSERV_ZOOM_CLIENT_SECRET'), '', ['text', 40]],
40 [
41 'note' => Loc::getMessage(
42 'SOCSERV_ZOOM_SETT_NOTE_2',
43 ['#URL#'=>\CHTTP::URN2URI('/bitrix/tools/oauth/zoom.php')]
44 )
45 ],
46 ];
47 }
48
53 public function getEntityOAuth($code = false): CZoomInterface
54 {
55 if (!$this->entityOAuth)
56 {
57 $this->entityOAuth = new CZoomInterface();
58 }
59
60 if ($code !== false)
61 {
62 $this->entityOAuth->setCode($code);
63 }
64
65 return $this->entityOAuth;
66 }
67
68 public function GetFormHtml($arParams)
69 {
70 $url = $this->getUrl($arParams);
71
72 $phrase = ($arParams['FOR_INTRANET'])
73 ? GetMessage('SOCSERV_ZOOM_NOTE_INTRANET')
74 : GetMessage('SOCSERV_ZOOM_NOTE');
75
76 return $arParams['FOR_INTRANET']
77 ? array('ON_CLICK' => 'onclick="BX.util.popup(\'' . htmlspecialcharsbx(CUtil::JSEscape($url)) . '\', 700, 700)"')
78 : '<a href="javascript:void(0)" onclick="BX.util.popup(\'' . htmlspecialcharsbx(CUtil::JSEscape($url)) . '\', 700, 700)" class="bx-ss-button zoom-button"></a><span class="bx-spacer"></span><span>' . $phrase . '</span>';
79 }
80
81 public function GetOnClickJs($arParams): string
82 {
83 $url = $this->getUrl($arParams);
84 return "BX.util.popup('" . CUtil::JSEscape($url) . "', 460, 420)";
85 }
86
87 public function getUrl($arParams): string
88 {
89 global $APPLICATION;
90
91 if (defined('BX24_HOST_NAME') && IsModuleInstalled('bitrix24'))
92 {
93 $redirect_uri = static::CONTROLLER_URL . '/redirect.php';
94 $backurl = $APPLICATION->GetCurPageParam('', ['logout', 'auth_service_error', 'auth_service_id', 'backurl']);
95 $state = $this->getEntityOAuth()->GetRedirectURI() .
96 urlencode('?state=' . JWT::urlsafeB64Encode('backurl=' . $backurl . '&check_key=' . \CSocServAuthManager::getUniqueKey()));
97 }
98 else
99 {
100 $state = 'site_id=' . SITE_ID . '&backurl=' .
101 urlencode($APPLICATION->GetCurPageParam('check_key=' . \CSocServAuthManager::getUniqueKey(), ['logout', 'auth_service_error', 'auth_service_id', 'backurl'])) .
102 (isset($arParams['BACKURL']) ? '&redirect_url=' . urlencode($arParams['BACKURL']) : '');
103
104 $redirect_uri = $this->getEntityOAuth()->GetRedirectURI();
105 }
106
107 return $this->getEntityOAuth()->GetAuthUrl($redirect_uri, $state);
108 }
109
110 public function addScope($scope): CZoomInterface
111 {
112 return $this->getEntityOAuth()->addScope($scope);
113 }
114
115 public function prepareUser($arUser, $short = false): array
116 {
117 $entityOAuth = $this->getEntityOAuth();
118 $arFields = array(
119 'EXTERNAL_AUTH_ID' => self::ID,
120 'XML_ID' => $arUser["email"],
121 'LOGIN' => self::LOGIN_PREFIX.$arUser["email"],
122 'EMAIL' => $arUser["email"],
123 'NAME' => $arUser["first_name"],
124 'LAST_NAME' => $arUser["last_name"],
125 'OATOKEN' => $entityOAuth->getToken(),
126 'OATOKEN_EXPIRES' => $entityOAuth->getAccessTokenExpires(),
127 );
128
129 if (!$short && isset($arUser['pic_url']))
130 {
131 $picture_url = $arUser['pic_url'];
132 $temp_path = CFile::GetTempName('', 'picture.jpg');
133
134 $ob = new HttpClient(array(
135 "redirect" => true
136 ));
137 $ob->download($picture_url, $temp_path);
138
139 $arPic = CFile::MakeFileArray($temp_path);
140 if ($arPic)
141 {
142 $arFields["PERSONAL_PHOTO"] = $arPic;
143 }
144 }
145
146 if (SITE_ID <> '')
147 {
148 $arFields["SITE_ID"] = SITE_ID;
149 }
150
151 return $arFields;
152 }
153
154 public static function CheckUniqueKey($bUnset = true): bool
155 {
156 $arState = array();
157
158 if (isset($_REQUEST['state']))
159 {
160 parse_str(urldecode(JWT::urlsafeB64Decode($_REQUEST['state'])), $arState);
161
162 if (isset($arState['backurl']))
163 {
164 InitURLParam($arState['backurl']);
165 }
166 }
167
168 if (!isset($_REQUEST['check_key']) && isset($_REQUEST['backurl']))
169 {
170 InitURLParam($_REQUEST['backurl']);
171 }
172
173 $checkKey = '';
174 if (isset($_REQUEST['check_key']))
175 {
176 $checkKey = $_REQUEST['check_key'];
177 }
178 elseif (isset($arState['check_key']))
179 {
180 $checkKey = $arState['check_key'];
181 }
182
183 if ($_SESSION['UNIQUE_KEY'] !== '' && $checkKey !== '' && ($checkKey === $_SESSION['UNIQUE_KEY']))
184 {
185 if ($bUnset)
186 {
187 unset($_SESSION['UNIQUE_KEY']);
188 }
189
190 return true;
191 }
192 return false;
193 }
194
195 public function Authorize(): void
196 {
197 global $APPLICATION;
198 $APPLICATION->RestartBuffer();
199
200 $authError = SOCSERV_AUTHORISATION_ERROR;
201
202 if (
203 isset($_REQUEST['code']) && $_REQUEST['code'] <> ''
204 && self::CheckUniqueKey()
205 )
206 {
207 if (defined('BX24_HOST_NAME') && IsModuleInstalled('bitrix24'))
208 {
209 $redirect_uri = static::CONTROLLER_URL . '/redirect.php';
210 }
211 else
212 {
213 $redirect_uri = $this->getEntityOAuth()->GetRedirectURI();
214 }
215
216 $entityOAuth = $this->getEntityOAuth($_REQUEST['code']);
217 if ($entityOAuth->GetAccessToken($redirect_uri) !== false)
218 {
219 $arUser = $entityOAuth->getCurrentUser();
220 if (is_array($arUser) && isset($arUser["email"]))
221 {
222 $arFields = $this->prepareUser($arUser);
223 $authError = $this->AuthorizeUser($arFields);
224
225 $userData = [
226 'externalUserId' => $arUser['id'],
227 'externalAccountId' => $arUser['account_id'],
228 'socServLogin' => $arFields['LOGIN'],
229 ];
230 $zc = new \Bitrix\SocialServices\Integration\Zoom\ZoomController();
231 $zc->registerZoomUser($userData);
232 }
233 }
234 }
235
236 $bSuccess = $authError === true;
237
238 $url = ($APPLICATION->GetCurDir() == "/login/") ? "" : $APPLICATION->GetCurDir();
239 $aRemove = array("logout", "auth_service_error", "auth_service_id", "code", "error_reason", "error", "error_description", "check_key", "current_fieldset");
240
241 if (isset($_REQUEST["state"]))
242 {
243 $arState = array();
244
245 $decodedState = urldecode(JWT::urlsafeB64Decode($_REQUEST["state"]));
246 parse_str($decodedState, $arState);
247
248 if (isset($arState['backurl']) || isset($arState['redirect_url']))
249 {
250 $url = !empty($arState['redirect_url']) ? $arState['redirect_url'] : $arState['backurl'];
251 if (substr($url, 0, 1) !== "#")
252 {
253 $parseUrl = parse_url($url);
254
255 $urlPath = $parseUrl["path"];
256 $arUrlQuery = explode('&', $parseUrl["query"]);
257
258 foreach ($arUrlQuery as $key => $value)
259 {
260 foreach ($aRemove as $param)
261 {
262 if (strpos($value, $param . "=") === 0)
263 {
264 unset($arUrlQuery[$key]);
265 break;
266 }
267 }
268 }
269
270 $url = (!empty($arUrlQuery)) ? $urlPath . '?' . implode("&", $arUrlQuery) : $urlPath;
271 }
272 }
273 }
274
275 if ($authError === SOCSERV_REGISTRATION_DENY)
276 {
277 $url = (preg_match("/\?/", $url)) ? $url . '&' : $url . '?';
278 $url .= 'auth_service_id=' . self::ID . '&auth_service_error=' . $authError;
279 }
280 elseif ($bSuccess !== true)
281 {
282 $url = (isset($urlPath)) ? $urlPath . '?auth_service_id=' . self::ID . '&auth_service_error=' . $authError : $GLOBALS['APPLICATION']->GetCurPageParam(('auth_service_id=' . self::ID . '&auth_service_error=' . $authError), $aRemove);
283 }
284
285 if (CModule::IncludeModule("socialnetwork") && strpos($url, "current_fieldset=") === false)
286 {
287 $url .= ((strpos($url, "?") === false) ? '?' : '&') . "current_fieldset=SOCSERV";
288 }
289 ?>
290 <script>
291 if (window.opener)
292 window.opener.location.reload();
293 window.close();
294 </script>
295 <?php
296 CMain::FinalActions();
297 }
298
299 public function setUser($userId)
300 {
301 $this->getEntityOAuth()->setUser($userId);
302 }
303
304 public function getStorageToken()
305 {
306 $accessToken = null;
307 $userId = (int)$this->userId;
308 if ($userId > 0)
309 {
310 $dbSocservUser = \Bitrix\Socialservices\UserTable::getList([
311 'filter' => ['=USER_ID' => $userId, '=EXTERNAL_AUTH_ID' => static::ID],
312 'select' => ['OATOKEN', 'REFRESH_TOKEN', 'OATOKEN_EXPIRES']
313 ]);
314 if ($arOauth = $dbSocservUser->fetch())
315 {
316 $accessToken = $arOauth['OATOKEN'];
317
318 if (empty($accessToken) || (((int)$arOauth['OATOKEN_EXPIRES'] > 0) && ((int)($arOauth['OATOKEN_EXPIRES'] < (int)time()))))
319 {
320 if (isset($arOauth['REFRESH_TOKEN']))
321 {
322 $this->getEntityOAuth()->getNewAccessToken($arOauth['REFRESH_TOKEN'], $userId, true);
323 }
324
325 if (($accessToken = $this->getEntityOAuth()->getToken()) === false)
326 {
327 return null;
328 }
329 }
330 }
331 }
332
333 return $accessToken;
334 }
335
336 public function createConference($params)
337 {
338 $result = new Result();
339 $conferenceData = null;
340 if (!$this->getEntityOAuth()->GetAccessToken())
341 {
342 return $result->addError(new Error('Could not get oauth token'));
343 }
344
345 if (isset($params['ENTITY_TYPE_ID']))
346 {
347 $entityTypeId = $params['ENTITY_TYPE_ID'];
348 unset($params['ENTITY_TYPE_ID']);
349 }
350
351 if (isset($params['ENTITY_ID']))
352 {
353 $entityId = $params['ENTITY_ID'];
354 unset($params['ENTITY_ID']);
355 }
356
357 $requestConferenceResult = $this->getEntityOAuth()->requestConference($params);
358 if(!$requestConferenceResult->isSuccess())
359 {
360 return $result->addErrors($requestConferenceResult->getErrors());
361 }
362 $conferenceData = $requestConferenceResult->getData();
363
364 $userData = $this->getEntityOAuth()->getCurrentUser();
365 if(!is_array($userData))
366 {
367 return $result->addError(new Error('Cannot get user data'));
368 }
369 $conferenceData['externalUserId'] = $userData['id'];
370 $conferenceData['externalAccountId'] = $userData['account_id'];
371
372 $conference['join_url'] = $this->attachPasswordToUrl($conferenceData['join_url'], $conferenceData['encrypted_password']);
373
374 $startTimeStamp = \DateTime::createFromFormat(DATE_ATOM, $conferenceData['start_time'])->getTimestamp();
375 $startDateTime = DateTime::createFromTimestamp($startTimeStamp);
376
377 $params = [
378 'ENTITY_TYPE_ID' => ($entityTypeId ?? self::EMPTY_TYPE),
379 'ENTITY_ID' => ($entityId ?? 0),
380 'CONFERENCE_EXTERNAL_ID' => $conferenceData['id'],
381 'CONFERENCE_URL' => $conferenceData['join_url'],
382 'CONFERENCE_PASSWORD' => $conferenceData['encrypted_password'],
383 'CONFERENCE_CREATED' => (new DateTime()),
384 'CONFERENCE_STARTED' => $startDateTime,
385 'DURATION' => $conferenceData['duration'],
386 'TITLE' => $conferenceData['topic'],
387 'SHORT_LINK' => $this->getShortLink($conferenceData['id']),
388 ];
389
390 $addResult = ZoomMeetingTable::add($params);
391 if (!$addResult->isSuccess())
392 {
393 return $result->addErrors($addResult->getErrors());
394 }
395 $conferenceData['bitrix_internal_id'] = $addResult->getId();
396
397 return $result->setData($conferenceData);
398 }
399
400 private function getShortLink(int $conferenceId): string
401 {
402 $host = UrlManager::getInstance()->getHostUrl();
403 $controllerUrl = \Bitrix\Main\Engine\UrlManager::getInstance()->create(
404 'crm.api.zoomUser.registerJoinMeeting',
405 ['conferenceId' => $conferenceId]
406 )->getUri();
407
408 return $host.\CBXShortUri::GetShortUri($controllerUrl);
409 }
410
418 public function updateConference(array $updateParams): Result
419 {
420 $result = new Result();
421 $params = [];
422
423 if (!$this->getEntityOAuth()->GetAccessToken())
424 {
425 return $result->addError(new Error('Could not get oauth token'));
426 }
427
428 $preparedData = $this->prepareDataToUpdate($updateParams);
429 if (empty($preparedData))
430 {
431 return $result;
432 }
433
434 $externalConferenceId = $preparedData['id'];
435 unset($preparedData['id']);
436
437 $requestConferenceResult = $this->getEntityOAuth()->updateConference($externalConferenceId, $preparedData);
438 if (!$requestConferenceResult->isSuccess())
439 {
440 return $result->addErrors($requestConferenceResult->getErrors());
441 }
442
443 if (isset($updateParams['start_time']))
444 {
445 $params['CONFERENCE_STARTED'] = DateTime::createFromUserTime($updateParams['start_time']);
446 }
447
448 if (isset($preparedData['duration']))
449 {
450 $params['DURATION'] = $preparedData['duration'];
451 }
452
453 if (!empty($params))
454 {
455 $addResult = ZoomMeetingTable::update($updateParams['meeting_id'], $params);
456 if (!$addResult->isSuccess())
457 {
458 return $result->addErrors($addResult->getErrors());
459 }
460 }
461
462 return $result;
463 }
464
474 private function prepareDataToUpdate(array $updateParams): ?array
475 {
476 $preparedDataToUpdate = [];
477
478 //get activity start and end timestamps
479 $activityStartTimeStamp = DateTime::createFromUserTime($updateParams['start_time'])->getTimestamp();
480 $activityEndTimeStamp = DateTime::createFromUserTime($updateParams['end_time'])->getTimestamp();
481
482 $meetingData = ZoomMeetingTable::getRowById($updateParams['meeting_id']);
483 if (!$meetingData)
484 {
485 return null;
486 }
487
488 //Prepare start_time only if the activity start_time does not match the conference start_time.
489 $meetingStartTimeStamp = $meetingData['CONFERENCE_STARTED']->getTimestamp();
490 if ($meetingStartTimeStamp !== $activityStartTimeStamp)
491 {
492 $preparedDataToUpdate['start_time'] = DateTime::createFromUserTime($updateParams['start_time'])
493 ->setTimeZone(new \DateTimeZone('UTC'))
494 ->format(DATE_ATOM);
495 }
496
497 //Prepare duration only if the activity duration does not match the conference duration.
498 $currentActivityDuration = ($activityEndTimeStamp - $activityStartTimeStamp) / 60;
499 if ($currentActivityDuration !== (int)$meetingData['DURATION'])
500 {
501 $preparedDataToUpdate['duration'] = $currentActivityDuration;
502 }
503
504 //Continue only if duration or start_time has been changed ($preparedDataToUpdate is not empty).
505 if (!empty($preparedDataToUpdate))
506 {
507 $preparedDataToUpdate['id'] = $meetingData['CONFERENCE_EXTERNAL_ID'];
508 }
509
510 return $preparedDataToUpdate;
511 }
512
513 public function getConferenceById(int $confId): ?array
514 {
515 $conference = null;
516 if ($this->getEntityOAuth()->GetAccessToken())
517 {
518 $conference = $this->getEntityOAuth()->getConferenceById($confId);
519 }
520
521 return $conference;
522 }
523
524 private function attachPasswordToUrl(string $conferenceUrl, string $password): string
525 {
526 $url = new \Bitrix\Main\Web\Uri($conferenceUrl);
527 $queryParams = $url->getQuery();
528 $parsedParams = [];
529 parse_str($queryParams, $parsedParams);
530 if (!isset($parsedParams['pwd']))
531 {
532 $url->addParams(['pwd' => $password]);
533 $conferenceUrl = $url->getUri();
534 }
535
536 return $conferenceUrl;
537 }
538
548 public function sendComplianceRequest(array $payload): Result
549 {
550 return $this->getEntityOAuth()->sendComplianceNotify($payload);
551 }
552}
553
554class CZoomInterface extends CSocServOAuthTransport
555{
556 const SERVICE_ID = "zoom";
557
558 const AUTH_URL = 'https://zoom.us/oauth/authorize';
559 const TOKEN_URL = 'https://zoom.us/oauth/token';
560 const COMPLIANCE_URL = 'https://api.zoom.us/oauth/data/compliance';
561
562 private const API_ENDPOINT = 'https://api.zoom.us/v2/';
563
564 private const USER_INFO_URL = 'users/me';
565 private const CREATE_MEETING_ENDPOINT = 'users/me/meetings';
566 private const UPDATE_MEETING_ENDPOINT = 'meetings/';
567
568 private const CACHE_TIME_CONNECT_INFO = "86400"; //One day
569 public const CACHE_DIR_CONNECT_INFO = "/socialservices/zoom/";
570
571 protected $userId = false;
572 protected $responseData = array();
573 protected $idToken;
574
575 protected $scope = [
576 'meeting:write', 'user:read:admin', 'meeting:read', 'recording:read'
577 ];
578
579 public function __construct($appID = false, $appSecret = false, $code = false)
580 {
581 if ($appID === false)
582 {
583 $appID = trim(CSocServAuth::GetOption("zoom_client_id"));
584 }
585
586 if ($appSecret === false)
587 {
588 $appSecret = trim(CSocServAuth::GetOption("zoom_client_secret"));
589 }
590
591 parent::__construct($appID, $appSecret, $code);
592 }
593
594 public function GetRedirectURI(): string
595 {
596 return \CHTTP::URN2URI('/bitrix/tools/oauth/zoom.php');
597 }
598
599 public function GetAuthUrl($redirect_uri, $state = ''): string
600 {
601 return self::AUTH_URL .
602 '?client_id=' . $this->appID .
603 '&redirect_uri=' . urlencode($redirect_uri) .
604 '&response_type=' . 'code' .
605 '&response_mode=' . 'form_post' .
606 ($state <> '' ? '&state=' . JWT::urlsafeB64Encode($state) : '');
607 }
608
609 public function getResult()
610 {
611 return $this->responseData;
612 }
613
614 public function GetAccessToken($redirect_uri = ''): bool
615 {
616 $token = $this->getStorageTokens();
617 if (is_array($token))
618 {
619 $this->access_token = $token['OATOKEN'];
620 $this->accessTokenExpires = $token['OATOKEN_EXPIRES'];
621
622 if (!$this->code)
623 {
624 if ($this->checkAccessToken())
625 {
626 return true;
627 }
628
629 if (isset($token['REFRESH_TOKEN']) && $this->getNewAccessToken($token['REFRESH_TOKEN'], $this->userId, true))
630 {
631 return true;
632 }
633 }
634
635 $this->deleteStorageTokens();
636 }
637
638 if ($this->code === false)
639 {
640 return false;
641 }
642
643 $query = [
644 'code' => $this->code,
645 'grant_type' => 'authorization_code',
646 'redirect_uri' => $redirect_uri,
647 ];
648
649 $httpClient = new HttpClient([
650 'socketTimeout' => $this->httpTimeout,
651 'streamTimeout' => $this->httpTimeout,
652 ]);
653 $httpClient->setAuthorization($this->appID, $this->appSecret);
654
655 $result = $httpClient->post(self::TOKEN_URL, $query);
656 try
657 {
658 $result = \Bitrix\Main\Web\Json::decode($result);
659 }
660 catch (\Bitrix\Main\ArgumentException $e)
661 {
662 $result = [];
663 }
664
665 if ((isset($result['access_token']) && $result['access_token'] <> ''))
666 {
667 $this->access_token = $result['access_token'];
668 $this->accessTokenExpires = time() + $result['expires_in'];
669 $this->refresh_token = $result['refresh_token'];
670
671 $_SESSION["OAUTH_DATA"] = [
672 "OATOKEN" => $this->access_token,
673 "OATOKEN_EXPIRES" => $this->accessTokenExpires,
674 "REFRESH_TOKEN" => $this->refresh_token,
675 ];
676 return true;
677 }
678
679 return false;
680 }
681
682 public function getNewAccessToken($refreshToken = false, $userId = 0, $save = false): bool
683 {
684 if (!$this->appID || !$this->appSecret)
685 {
686 return false;
687 }
688
689 if (!$refreshToken)
690 {
691 $refreshToken = $this->refresh_token;
692 }
693
694 $httpClient = new HttpClient(array(
695 'socketTimeout' => $this->httpTimeout,
696 'streamTimeout' => $this->httpTimeout,
697 ));
698 $httpClient->setAuthorization($this->appID, $this->appSecret);
699 $queryPrams = http_build_query([
700 'refresh_token' => $refreshToken,
701 'grant_type' => 'refresh_token',
702 ]);
703 $url = static::TOKEN_URL.'?'.$queryPrams;
704 $result = $httpClient->post($url);
705
706 try
707 {
708 $arResult = Json::decode($result);
709 }
710 catch (\Bitrix\Main\ArgumentException $e)
711 {
712 $arResult = array();
713 }
714
715 if (!empty($arResult['access_token']))
716 {
717 $this->access_token = $arResult['access_token'];
718 $this->accessTokenExpires = $arResult['expires_in'] + time();
719 $this->refresh_token = $arResult['refresh_token'];
720
721 if ($save && (int)$userId > 0)
722 {
723 $dbSocservUser = \Bitrix\Socialservices\UserTable::getList(array(
724 'filter' => array(
725 '=EXTERNAL_AUTH_ID' => static::SERVICE_ID,
726 '=USER_ID' => $userId,
727 ),
728 'select' => array('ID')
729 ));
730 if ($arOauth = $dbSocservUser->fetch())
731 {
732 \Bitrix\Socialservices\UserTable::update($arOauth['ID'], array(
733 'OATOKEN' => $this->access_token,
734 'REFRESH_TOKEN' => $this->refresh_token,
735 'OATOKEN_EXPIRES' => $this->accessTokenExpires,
736 )
737 );
738 }
739 }
740
741 return true;
742 }
743
744 return false;
745 }
746
747 public function getCurrentUser()
748 {
749 if ($this->access_token === false)
750 {
751 return false;
752 }
753
754 $endPoint = self::API_ENDPOINT . self::USER_INFO_URL;
755 $requestResult = $this->sendRequest(HttpClient::HTTP_GET, $endPoint);
756
757 if (!$requestResult->isSuccess())
758 {
759 return null;
760 }
761
762 return $requestResult->getData();
763 }
764
765 public function requestConference($params): Result
766 {
767 $result = new Result();
768
769 $endPoint = self::API_ENDPOINT . self::CREATE_MEETING_ENDPOINT;
770 $requestResult = $this->sendRequest(HttpClient::HTTP_POST, $endPoint, $params);
771
772 if (!$requestResult->isSuccess())
773 {
774 return $result->addErrors($requestResult->getErrors());
775 }
776 $response = $requestResult->getData();
777
778 if (isset($response['code']) && $response['code'] != 200)
779 {
780 // zoom api error
781 return $result->addError(new Error($response['message'], $response['code']));
782 }
783
784 return $result->setData($response);
785 }
786
787 public function updateConference(int $conferenceId, array $params): Result
788 {
789 $endPoint = self::API_ENDPOINT . self::UPDATE_MEETING_ENDPOINT . $conferenceId;
790
791 return $this->sendRequest(HttpClient::HTTP_PATCH, $endPoint, $params);
792 }
793
794 public function getConferenceById($confId): ?array
795 {
796 $newMeetingEndpoint = self::API_ENDPOINT. 'meetings/' . $confId;
797 $conferenceDataResult = $this->sendRequest(HttpClient::HTTP_GET, $newMeetingEndpoint);
798
799 if (!$conferenceDataResult->isSuccess())
800 {
801 return null;
802 }
803
804 $conferenceData = $conferenceDataResult->getData();
805 if (!is_array($conferenceData) || $conferenceData['id'] <= 0)
806 {
807 return null;
808 }
809
810 return $conferenceData;
811 }
812
813 public function getConferenceFiles($confId): ?array
814 {
815 $endPoint = self::API_ENDPOINT . "/meetings/{$confId}/recordings";
816 $requestResult = $this->sendRequest(HttpClient::HTTP_GET, $endPoint);
817 if (!$requestResult->isSuccess())
818 {
819 return null;
820 }
821
822 return $requestResult->getData();
823 }
824
832 public function sendComplianceNotify(array $params): Result
833 {
834 $requestParams = [
835 'client_id' => $this->appID,
836 'user_id' => $params['user_id'],
837 'account_id' => $params['account_id'],
838 'deauthorization_event_received' => $params,
839 'compliance_completed' => true,
840 ];
841
842 $result = new Result();
843 $http = new HttpClient([
844 'socketTimeout' => $this->httpTimeout,
845 'streamTimeout' => $this->httpTimeout,
846 ]);
847
848 $http->setAuthorization($this->appID, $this->appSecret);
849 $http->setHeader('Content-type', 'application/json');
850 $requestResult = $http->post(self::COMPLIANCE_URL, Json::encode($requestParams));
851
852 try
853 {
854 $decodedData = Json::decode($requestResult);
855 $result->setData($decodedData);
856 }
857 catch (ArgumentException $e)
858 {
859 return $result->addError(new Error('Could not decode service response'));
860 }
861
862 return $result;
863 }
864
865 private function sendRequest(string $method, string $endPoint, array $params = []): Result
866 {
867 $result = new Result();
868
869 $http = new HttpClient(array(
870 'socketTimeout' => $this->httpTimeout,
871 'streamTimeout' => $this->httpTimeout,
872 ));
873 $http->setHeader('Authorization', 'Bearer '.$this->access_token);
874
875 switch ($method)
876 {
877 case HttpClient::HTTP_PATCH:
878 $http->setHeader('Content-type', 'application/json');
879 $http->query(HttpClient::HTTP_PATCH, $endPoint, Json::encode($params));
880 if ($http->getStatus() != 204)
881 {
882 // zoom api error
883 $requestResult = $http->getResult();
884 $response = Json::decode($requestResult);
885 return $result->addError(new Error($response['message'], $response['code']));
886 }
887 return $result;
888
889 case HttpClient::HTTP_POST:
890 $http->setHeader('Content-type', 'application/json');
891 $requestResult = $http->post($endPoint, Json::encode($params));
892 break;
893
894 case HttpClient::HTTP_GET:
895 $requestResult = $http->get($endPoint);
896 break;
897
898 default:
899 return $result->addError(new Error('Unsupported request method'));
900 }
901
902 try
903 {
904 $decodedData = Json::decode($requestResult);
905 $result->setData($decodedData);
906 }
907 catch (ArgumentException $e)
908 {
909 return $result->addError(new Error('Could not decode service response'));
910 }
911
912 return $result;
913 }
914
924 public static function isConnected(int $userId): bool
925 {
926 $cache = \Bitrix\Main\Data\Cache::createInstance();
927 $cacheId = self::SERVICE_ID .'|'. $userId;
928 $user = null;
929 if ($cache->initCache(self::CACHE_TIME_CONNECT_INFO, $cacheId, self::CACHE_DIR_CONNECT_INFO))
930 {
931 $user = $cache->getVars()['user'];
932 }
933 elseif ($cache->startDataCache())
934 {
935 $user = UserTable::getRow([
936 'filter' => [
937 '=USER_ID' => $userId,
938 '=EXTERNAL_AUTH_ID' => self::SERVICE_ID
939 ]
940 ]);
941
942 $cache->endDataCache(['user' => $user]);
943 }
944
945 return $user !== null;
946 }
947
948 public function GetAppInfo(): bool
949 {
950 return false;
951 }
952
953 public function getScopeEncode(): string
954 {
955 return implode(' ', array_map('urlencode', array_unique($this->getScope())));
956 }
957}
$arParams
Определения access_dialog.php:21
change_password_forgot_link login popup forget pas AUTH_GOTO_FORGOT_FORM login btn wrap change_password_button login popup link login popup return auth javascript
Определения change_password.php:57
Определения error.php:15
Определения user.php:48
static URN2URI($urn, $server_name='')
Определения http.php:39
Определения authmanager.php:985
$userId
Определения authmanager.php:991
Определения zoom.php:20
const ID
Определения zoom.php:21
GetSettings()
Определения zoom.php:35
$entityOAuth
Определения zoom.php:26
getEntityOAuth($code=false)
Определения zoom.php:53
const EMPTY_TYPE
Определения zoom.php:24
getUrl($arParams)
Определения zoom.php:87
__construct($userId=null)
Определения zoom.php:28
GetFormHtml($arParams)
Определения zoom.php:68
Определения zoom.php:555
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
if(!is_null($config))($config as $configItem)(! $configItem->isVisible()) $code
Определения options.php:195
htmlspecialcharsbx($string, $flags=ENT_COMPAT, $doubleEncode=true)
Определения tools.php:2701
IncludeModuleLangFile($filepath, $lang=false, $bReturnArray=false)
Определения tools.php:3778
GetMessage($name, $aReplace=null)
Определения tools.php:3397
const SITE_ID
Определения sonet_set_content_view.php:12
path
Определения template_copy.php:201
$url
Определения iframe.php:7