1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
bitrix24net.php
См. документацию.
1<?
2
3use Bitrix\Bitrix24\Integration\Network\Broadcast;
4use Bitrix\Bitrix24\License;
12
13Loc::loadMessages(__FILE__);
14
15if(!defined('B24NETWORK_NODE'))
16{
17 $defaultValue = \Bitrix\Main\Config\Option::get('socialservices', 'network_url', '');
18
19 if($defaultValue <> '')
20 {
21 define('B24NETWORK_NODE', $defaultValue);
22 }
23 elseif(defined('B24NETWORK_URL'))
24 {
25 define('B24NETWORK_NODE', B24NETWORK_URL);
26 }
27 elseif (in_array(Application::getInstance()->getLicense()->getRegion(), ['ru','by','kz','uz']))
28 {
29 define('B24NETWORK_NODE', 'https://auth2.bitrix24.net');
30 }
31 else
32 {
33 define('B24NETWORK_NODE', 'https://www.bitrix24.net');
34 }
35}
36
38{
47 public static function log(string $message, array $additionalParams = []): void
48 {
49 if (!empty($additionalParams))
50 {
51 $postfix = ' |';
52 foreach ($additionalParams as $key => $value)
53 {
54 if (is_array($value))
55 {
56 if (empty($value))
57 {
58 $value = '';
59 }
60 else
61 {
62 $value = Json::encode($value);
63 }
64 }
65 else
66 {
67 $value = (string)$value;
68 }
69
70 $postfix .= " {$key}[{$value}];";
71 }
72
73 $message .= $postfix;
74 }
75
76 AddMessage2Log("SocServBitrix24Net: {$message}", 'socialservices');
77 }
78}
79
81{
82 const ID = "Bitrix24Net";
83 const NETWORK_URL = B24NETWORK_NODE;
84
85 protected $entityOAuth = null;
86
87 public function GetSettings()
88 {
89 return array(
90 array("bitrix24net_domain", Loc::getMessage("socserv_b24net_domain"), "", array("statictext")),
91 array("bitrix24net_id", Loc::getMessage("socserv_b24net_id"), "", array("text", 40)),
92 array("bitrix24net_secret", Loc::getMessage("socserv_b24net_secret"), "", array("text", 40)),
93 array("note"=>GetMessage("socserv_b24net_sett_note"))
94 );
95 }
96
97 public function CheckSettings()
98 {
99 return self::GetOption('bitrix24net_id') !== '' && self::GetOption('bitrix24net_secret') !== '';
100 }
101
102
103 public function getFormHtml($arParams)
104 {
105 $url = $this->getUrl("popup");
106
107 $phrase = ($arParams["FOR_INTRANET"]) ? Loc::getMessage("socserv_b24net_note_intranet") : Loc::getMessage("socserv_b24net_note");
108
109 return $arParams["FOR_INTRANET"]
110 ? array("ON_CLICK" => 'onclick="BX.util.popup(\''.htmlspecialcharsbx(CUtil::JSEscape($url)).'\', 800, 600)"')
111 : '<a href="javascript:void(0)" onclick="BX.util.popup(\''.htmlspecialcharsbx(CUtil::JSEscape($url)).'\', 800, 600)" class="bx-ss-button bitrix24net-button bitrix24net-button-'.LANGUAGE_ID.'"></a><span class="bx-spacer"></span><span>'.$phrase.'</span>';
112 }
113
114 public function GetOnClickJs()
115 {
116 $url = $this->getUrl("popup");
117 return "BX.util.popup('".CUtil::JSEscape($url)."', 800, 600)";
118 }
119
120 public function getEntityOAuth($code = false)
121 {
122 if(!$this->entityOAuth)
123 {
124 $this->entityOAuth = new CBitrix24NetOAuthInterface();
125 }
126
127 if($code !== false)
128 {
129 $this->entityOAuth->setCode($code);
130 }
131
132 return $this->entityOAuth;
133 }
134
135 public function getUrl($mode = "page")
136 {
137 $redirectUri = CSocServUtil::GetCurUrl(
138 'auth_service_id='.self::ID,
139 [
140 'invite_token',
141 ],
142 );
143 $backUrl = $GLOBALS["APPLICATION"]->GetCurPageParam(
144 'check_key=' . CSocServAuthManager::GetUniqueKey(),
145 array_merge(
146 [
147 'auth_service_error',
148 'auth_service_id',
149 'check_key',
150 'error_message',
151 'invite_token',
152 ],
153 \Bitrix\Main\HttpRequest::getSystemParameters(),
154 )
155 );
156
157 $stateFields = [
158 'check_key' => \CSocServAuthManager::getUniqueKey(),
159 'redirect_url' => $backUrl,
160 'mode' => $mode,
161 ];
162 if (defined("ADMIN_SECTION") && ADMIN_SECTION == true)
163 {
164 $stateFields['admin'] = 1;
165 }
166 else
167 {
168 $stateFields['site_id'] = SITE_ID;
169 }
170 $state = StateService::getInstance()->createState($stateFields);
171
172 return $this->getEntityOAuth()->GetAuthUrl($redirectUri, $state, $mode);
173 }
174
175 public function getInviteUrl($userId, $checkword)
176 {
177 return $this->getEntityOAuth()->GetInviteUrl($userId, $checkword);
178 }
179
180 public function addScope($scope)
181 {
182 return $this->getEntityOAuth()->addScope($scope);
183 }
184
185 public function Authorize($skipCheck = false)
186 {
187 global $APPLICATION;
188 $APPLICATION->RestartBuffer();
189
190 $bProcessState = false;
191 $authError = SOCSERV_AUTHORISATION_ERROR;
192 $errorMessage = '';
193
194 if (
195 $skipCheck
196 || (
197 (isset($_REQUEST["code"]) && $_REQUEST["code"] <> '')
198 && CSocServAuthManager::CheckUniqueKey()
199 )
200 )
201 {
202 $redirect_uri = \CHTTP::URN2URI('/bitrix/tools/oauth/bitrix24net.php');
203 $bProcessState = true;
204 $bAdmin = false;
205
206 if (isset($_REQUEST["state"]))
207 {
208 $arState = StateService::getInstance()->getPayload((string)$_REQUEST["state"]);
209 $bAdmin = isset($arState['admin']);
210 }
211 if ($bAdmin)
212 {
213 $this->checkRestrictions = false;
214 $this->addScope("admin");
215 }
216
217 if (!$skipCheck)
218 {
219 $this->getEntityOAuth()->setCode($_REQUEST["code"]);
220 }
221
222 if (isset($_REQUEST['saml']) && is_string($_REQUEST['saml']))
223 {
224 $this->getEntityOAuth()->setSamlEncodedValue($_REQUEST['saml']);
225 }
226
227 if ($this->getEntityOAuth()->GetAccessToken($redirect_uri) !== false)
228 {
229 $arB24NetUser = $this->getEntityOAuth()->GetCurrentUser();
230 if ($arB24NetUser)
231 {
232 $authError = true;
233
234 $arFields = array(
235 'EXTERNAL_AUTH_ID' => self::ID,
236 'XML_ID' => $arB24NetUser["ID"],
237 'LOGIN' => isset($arB24NetUser['LOGIN']) ? $arB24NetUser['LOGIN'] : "B24_".$arB24NetUser["ID"],
238 'NAME' => $arB24NetUser["NAME"],
239 'LAST_NAME' => $arB24NetUser["LAST_NAME"],
240 'EMAIL' => $arB24NetUser["EMAIL"],
241 'PERSONAL_WWW' => $arB24NetUser["PROFILE"],
242 'OATOKEN' => $this->getEntityOAuth()->getToken(),
243 'REFRESH_TOKEN' => $this->getEntityOAuth()->getRefreshToken(),
244 'OATOKEN_EXPIRES' => $this->getEntityOAuth()->getAccessTokenExpires(),
245 );
246
247 foreach(GetModuleEvents("socialservices", "OnBeforeNetworkUserAuthorize", true) as $arEvent)
248 {
249 if (ExecuteModuleEventEx($arEvent, array(&$arFields, $arB24NetUser, $this)) === false)
250 {
251 $authError = SOCSERV_AUTHORISATION_ERROR;
252 $errorMessage = $APPLICATION->GetException();
253
254 break;
255 }
256 }
257
258 if ($authError === true)
259 {
260 if (SITE_ID <> '')
261 {
262 $arFields["SITE_ID"] = SITE_ID;
263 }
264
265 $bSaveNetworkAuth = COption::GetOptionString("main", "allow_external_auth_stored_hash", "N") == "Y";
266 $authError = $this->AuthorizeUser($arFields, $bSaveNetworkAuth);
267 }
268 }
269
270 if ($authError !== true && !IsModuleInstalled('bitrix24'))
271 {
272 $this->getEntityOAuth()->RevokeAuth();
273 }
274 elseif ($bAdmin)
275 {
276 global $CACHE_MANAGER, $USER;
277 $CACHE_MANAGER->Clean("sso_portal_list_".$USER->GetID());
278 }
279 }
280 }
281
282 $bSuccess = $authError === true;
283
284 if ($bSuccess)
285 {
286 CSocServAuthManager::SetAuthorizedServiceId(self::ID);
287 }
288
289 // hack to update option used for visualization in module options
290 if ($bSuccess && !self::GetOption("bitrix24net_domain"))
291 {
292 $request = \Bitrix\Main\Context::getCurrent()->getRequest();
293 self::SetOption("bitrix24net_domain", ($request->isHttps() ? "https://" : "http://").$request->getHttpHost());
294 }
295
296 $aRemove = array_merge(array("auth_service_error", "auth_service_id", "code", "error_reason", "error", "error_description", "check_key", "current_fieldset", "checkword"), \Bitrix\Main\HttpRequest::getSystemParameters());
297
298 $url = ($APPLICATION->GetCurDir() == "/login/") ? "" : $APPLICATION->GetCurDir();
299
300 $mode = 'page';
301
302 if (!$bProcessState)
303 {
304 unset($_REQUEST["state"]);
305 }
306
307 if (isset($_REQUEST["state"]))
308 {
309 $arState = StateService::getInstance()->getPayload((string)$_REQUEST["state"]) ?? [];
310 if (isset($arState['backurl']) || isset($arState['redirect_url']))
311 {
312 $parseUrl = parse_url(isset($arState['redirect_url']) ? $arState['redirect_url'] : $arState['backurl']);
313
314 $urlPath = $parseUrl["path"];
315 $arUrlQuery = explode('&', $parseUrl["query"]);
316
317 foreach($arUrlQuery as $key => $value)
318 {
319 foreach($aRemove as $param)
320 {
321 if (mb_strpos($value, $param."=") === 0)
322 {
323 unset($arUrlQuery[$key]);
324 break;
325 }
326 }
327 }
328
329 $url = (!empty($arUrlQuery)) ? $urlPath.'?'.implode("&", $arUrlQuery) : $urlPath;
330 }
331
332 if (isset($arState['mode']))
333 {
334 $mode = $arState['mode'];
335 }
336 }
337
338 if ($url == '' || preg_match("'^(http://|https://|ftp://|//)'i", $url))
339 {
340 $url = \CHTTP::URN2URI('/');
341 }
342
344
345 if ($bSuccess)
346 {
347 unset($_SESSION['B24_NETWORK_REDIRECT_TRY']);
348 }
349 else
350 {
351 if (IsModuleInstalled('bitrix24'))
352 {
353 if (isset($_SESSION['B24_NETWORK_REDIRECT_TRY']))
354 {
355 unset($_SESSION['B24_NETWORK_REDIRECT_TRY']);
356 $url = self::getUrl();
357 $url .= (mb_strpos($url, '?') >= 0 ? '&' : '?').'skip_redirect=1&error_message='.urlencode($errorMessage);
358 }else
359 {
360 $_SESSION['B24_NETWORK_REDIRECT_TRY'] = true;
361 $url = '/';
362 }
363 }
364 else
365 {
366 if ($authError === SOCSERV_REGISTRATION_DENY)
367 {
368 $url = (preg_match("/\?/", $url)) ? $url.'&' : $url.'?';
369 $url .= 'auth_service_id='.self::ID.'&auth_service_error='.$authError;
370 }
371 elseif ($bSuccess !== true)
372 {
373 $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);
374 }
375 if ($errorMessage <> '')
376 {
377 $url .= '&error_message='.urlencode($errorMessage);
378 }
379 }
380 }
381
382 if (CModule::IncludeModule("socialnetwork") && mb_strpos($url, "current_fieldset=") === false)
383 {
384 $url .= ((mb_strpos($url, "?") === false) ? '?' : '&')."current_fieldset=SOCSERV";
385 }
386
387 if ($url === $APPLICATION->GetCurPageParam())
388 {
389 $url = "/";
390 }
391
392 $location = ($mode == "popup")
393 ? 'if(window.opener) window.opener.location = \''.$url.'\'; window.close();'
394 : 'window.location = \''.$url.'\';';
395?>
396<script>
397<?=$location?>
398</script>
399<?
400
401 CMain::FinalActions();
402 }
403
404 public static function registerSite($domain)
405 {
406 if (defined("LICENSE_KEY") && LICENSE_KEY !== "DEMO")
407 {
408 $query = new HttpClient();
409 $result = $query->get(static::NETWORK_URL.'/client.php?action=register&redirect_uri='.urlencode($domain.'/bitrix/tools/oauth/bitrix24net.php').'&key='.urlencode(LICENSE_KEY));
410
411 $arResult = null;
412 if ($result)
413 {
414 try
415 {
416 $arResult = Json::decode($result);
417 }
418 catch(\Bitrix\Main\ArgumentException $e)
419 {
420
421 }
422 }
423
424 if (is_array($arResult))
425 {
426 return $arResult;
427 }
428 else
429 {
430 return array("error" => "Unknown response", "error_details" => $result);
431 }
432 }
433 else
434 {
435 return array("error" => "License check failed");
436 }
437 }
438}
439
440class CBitrix24NetOAuthInterface
441{
442 const NET_URL = B24NETWORK_NODE;
443
444 const INVITE_URL = "/invite/";
445 const PASSPORT_URL = "/id/";
446 const AUTH_URL = "/oauth/authorize/";
447 const TOKEN_URL = "/oauth/token/";
448
449 protected $appID;
450 protected $appSecret;
451 protected $code = false;
452 protected $access_token = false;
453 protected $accessTokenExpires = 0;
454 protected $lastAuth = null;
455 protected $refresh_token = '';
456 protected $httpTimeout;
457 protected string $samlEncodedValue;
458 protected $scope = array(
459 'auth',
460 );
461 protected ?int $samlStatus;
462
463 protected $arResult = array();
464 protected $networkNode;
465
466 public function __construct($appID = false, $appSecret = false, $code = false)
467 {
468 if($appID === false)
469 {
470 $appID = trim(CSocServBitrix24Net::GetOption("bitrix24net_id"));
471 }
472
473 if($appSecret === false)
474 {
475 $appSecret = trim(CSocServBitrix24Net::GetOption("bitrix24net_secret"));
476 }
477
478 list($prefix, $suffix) = explode(".", $appID, 2);
479
480 if($prefix === 'site')
481 {
482 $this->addScope("client");
483 }
484 elseif($prefix == 'b24')
485 {
486 $this->addScope('profile');
487 }
488
489 $this->httpTimeout = SOCSERV_DEFAULT_HTTP_TIMEOUT;
490
491 $this->appID = $appID;
492 $this->appSecret = $appSecret;
493 $this->code = $code;
494
495 $this->networkNode = self::NET_URL;
496 }
497
498 public function getAppID()
499 {
500 return $this->appID;
501 }
502
503 public function getAppSecret()
504 {
505 return $this->appSecret;
506 }
507
508 public function getAccessTokenExpires()
509 {
510 return $this->accessTokenExpires;
511 }
512
513 public function setAccessTokenExpires($accessTokenExpires)
514 {
515 $this->accessTokenExpires = $accessTokenExpires;
516 }
517
518 public function getToken()
519 {
520 return $this->access_token;
521 }
522
523 public function setToken($access_token)
524 {
525 $this->access_token = $access_token;
526 }
527
528 public function getRefreshToken()
529 {
530 return $this->refresh_token;
531 }
532
533 public function setRefreshToken($refresh_token)
534 {
535 $this->refresh_token = $refresh_token;
536 }
537
538 public function setCode($code)
539 {
540 $this->code = $code;
541 }
542
543 public function setScope($scope)
544 {
545 $this->scope = $scope;
546 }
547
548 public function getScope()
549 {
550 return $this->scope;
551 }
552
553 public function addScope($scope)
554 {
555 if(is_array($scope))
556 $this->scope = array_merge($this->scope, $scope);
557 else
558 $this->scope[] = $scope;
559 return $this;
560 }
561
562 public function getScopeEncode()
563 {
564 return implode(',', array_map('urlencode', array_unique($this->getScope())));
565 }
566
567 public function getSamlEncodedValue(): string
568 {
569 return $this->samlEncodedValue;
570 }
571
572 public function setSamlEncodedValue(string $samlEncodedValue): void
573 {
574 $this->samlEncodedValue = $samlEncodedValue;
575 }
576
577 public function getResult()
578 {
579 return $this->arResult;
580 }
581
582 public function getError()
583 {
584 return is_array($this->arResult) && isset($this->arResult['error'])
585 ? $this->arResult['error']
586 : '';
587 }
588
589 public function GetAuthUrl($redirect_uri, $state = '', $mode = 'popup')
590 {
591 return $this->networkNode . self::AUTH_URL.
592 "?user_lang=".LANGUAGE_ID.
593 "&client_id=".urlencode($this->appID).
594 "&redirect_uri=".urlencode($redirect_uri).
595 "&scope=".$this->getScopeEncode().
596 "&response_type=code".
597 "&mode=".$mode.
598 //($this->refresh_token <> '' ? '' : '&approval_prompt=force').
599 ($state <> '' ? '&state='.urlencode($state) : '');
600 }
601
602 public function getInviteUrl($userId, $checkword)
603 {
604 return $this->networkNode . self::INVITE_URL.
605 "?user_lang=".LANGUAGE_ID.
606 "&client_id=".urlencode($this->appID).
607 "&profile_id=".$userId.
608 "&checkword=".$checkword;
609 }
610
611 public function getLastAuth()
612 {
613 return $this->lastAuth;
614 }
615
616 public function GetAccessToken($redirect_uri = '')
617 {
618 if ($this->code === false)
619 {
620 $token = $this->getStorageTokens();
621
622 // getStorageTokens returns null for unauthorized user
623 if (is_array($token))
624 {
625 $this->access_token = $token["OATOKEN"];
626 $this->accessTokenExpires = $token["OATOKEN_EXPIRES"];
627 }
628
629 if ($this->access_token && $this->checkAccessToken())
630 {
631 return true;
632 }
633 elseif (isset($token["REFRESH_TOKEN"]))
634 {
635 if ($this->getNewAccessToken($token["REFRESH_TOKEN"], $token["USER_ID"], true))
636 {
637 return true;
638 }
639 }
640
641 return false;
642 }
643
644 $http = new HttpClient([
645 'socketTimeout' => $this->httpTimeout,
646 'streamTimeout' => $this->httpTimeout,
647 ]);
648
649 $result = $http->get($this->networkNode . self::TOKEN_URL . '?' . http_build_query([
650 'code' => $this->code,
651 'client_id' => $this->appID,
652 'client_secret' => $this->appSecret,
653 'redirect_uri' => $redirect_uri,
654 'scope' => implode(',',$this->getScope()),
655 'grant_type' => 'authorization_code',
656 ]));
657
658 try
659 {
660 if (empty($result))
661 {
662 throw new \Bitrix\Main\ArgumentException('Empty result');
663 }
664
665 $arResult = Json::decode($result);
666 }
667 catch(\Bitrix\Main\ArgumentException $e)
668 {
669 CSocServBitrix24NetLogger::log("GetAccessToken", [
670 'status' => $http->getStatus(),
671 'error' => $http->getError(),
672 'response' => $result,
673 ]);
674
675 $arResult = [];
676 }
677
678 if (isset($arResult["access_token"]) && $arResult["access_token"] <> '')
679 {
680 if (isset($arResult["refresh_token"]) && $arResult["refresh_token"] <> '')
681 {
682 $this->refresh_token = $arResult["refresh_token"];
683 }
684
685 $this->access_token = $arResult["access_token"];
686 $this->accessTokenExpires = time() + $arResult["expires_in"];
687
688 $this->lastAuth = $arResult;
689
690 return true;
691 }
692
693 return false;
694 }
695
696 public function getNewAccessToken($refreshToken = false, $userId = 0, $save = false, $scope = array())
697 {
698 if ($this->appID == false || $this->appSecret == false)
699 {
700 return false;
701 }
702
703 if ($refreshToken == false)
704 {
705 $refreshToken = $this->refresh_token;
706 }
707
708 if ($scope != null)
709 {
710 $this->addScope($scope);
711 }
712
713 $http = new HttpClient(array(
714 'socketTimeout' => $this->httpTimeout,
715 'streamTimeout' => $this->httpTimeout,
716 ));
717
718 $result = $http->get($this->networkNode . self::TOKEN_URL . '?' . http_build_query([
719 'client_id' => $this->appID,
720 'client_secret' => $this->appSecret,
721 'refresh_token' => $refreshToken,
722 'scope' => implode(',',$this->getScope()),
723 'grant_type' => 'refresh_token',
724 ]));
725
726 try
727 {
728 if (empty($result))
729 {
730 throw new \Bitrix\Main\ArgumentException('Empty result');
731 }
732
733 $arResult = Json::decode($result);
734 }
735 catch(\Bitrix\Main\ArgumentException $e)
736 {
737 CSocServBitrix24NetLogger::log("GetNewAccessToken", [
738 'status' => $http->getStatus(),
739 'error' => $http->getError(),
740 'response' => $result,
741 ]);
742
743 $arResult = [];
744 }
745
746 if (isset($arResult["access_token"]) && $arResult["access_token"] <> '')
747 {
748 $this->access_token = $arResult["access_token"];
749 $this->accessTokenExpires = time() + $arResult["expires_in"];
750 $this->refresh_token = $arResult["refresh_token"];
751
752 if ($save && intval($userId) > 0)
753 {
754 $dbSocservUser = UserTable::getList([
755 'filter' => [
756 "=USER_ID" => intval($userId),
757 "=EXTERNAL_AUTH_ID" => CSocServBitrix24Net::ID
758 ],
759 'select' => ['ID']
760 ]);
761
762 $arOauth = $dbSocservUser->fetch();
763 if ($arOauth)
764 {
765 UserTable::update(
766 $arOauth["ID"], array(
767 "OATOKEN" => $this->access_token,
768 "OATOKEN_EXPIRES" => $this->accessTokenExpires,
769 "REFRESH_TOKEN" => $this->refresh_token,
770 )
771 );
772 }
773 }
774
775 return true;
776 }
777
778 return false;
779 }
780
781 public function GetCurrentUser()
782 {
783 if ($this->access_token)
784 {
785 $ob = new CBitrix24NetTransport($this->access_token);
786 $res = $ob->getProfile();
787
788 if ($res && !isset($res['error']))
789 {
790 return $res['result'];
791 }
792 }
793
794 return false;
795 }
796
797 public function RevokeAuth()
798 {
799 if ($this->access_token)
800 {
801 $ob = new CBitrix24NetTransport($this->access_token);
802 $ob->call('profile.revoke');
803 }
804 }
805
806 public function UpdateCurrentUser($arFields)
807 {
808 if ($this->access_token)
809 {
810 $ob = new CBitrix24NetTransport($this->access_token);
811 $res = $ob->updateProfile($arFields);
812
813 if (!isset($res['error']))
814 {
815 return $res['result'];
816 }
817 }
818
819 return false;
820 }
821
822 private function getStorageTokens()
823 {
824 global $USER;
825
826 $accessToken = '';
827 if (is_object($USER) && $USER->IsAuthorized())
828 {
829 $dbSocservUser = UserTable::getList([
830 'filter' => [
831 '=USER_ID' => $USER->GetID(),
832 '=EXTERNAL_AUTH_ID' => CSocServBitrix24Net::ID
833 ],
834 'select' => ["USER_ID", "OATOKEN", "OATOKEN_EXPIRES", "REFRESH_TOKEN"]
835 ]);
836
837 $accessToken = $dbSocservUser->fetch();
838 }
839 return $accessToken;
840 }
841
842 public function checkAccessToken()
843 {
844 return (($this->accessTokenExpires - 30) < time()) ? false : true;
845 }
846
847 public function getNetworkNode(): string
848 {
849 return $this->networkNode;
850 }
851
852 public function setNetworkNode(string $hostWithScheme): void
853 {
854 $this->networkNode = $hostWithScheme;
855 }
856
857 public function getSamlStatus(): ?int
858 {
859 return $this->samlStatus;
860 }
861}
862
866class CBitrix24NetTransport
867{
868 const SERVICE_URL = "/rest/";
869
870 const METHOD_METHODS = 'methods';
871 const METHOD_BATCH = 'batch';
872 const METHOD_PROFILE = 'profile';
873 const METHOD_PROFILE_ADD = 'profile.add';
874 const METHOD_PROFILE_ADD_CHECK = 'profile.add.check';
875 const METHOD_PROFILE_UPDATE = 'profile.update';
876 const METHOD_PROFILE_DELETE = 'profile.delete';
877 const METHOD_PROFILE_CONTACTS = 'profile.contacts';
878 const METHOD_PROFILE_RESTORE_PASSWORD = 'profile.password.restore';
879 const METHOD_PROFILE_PUSH_QRCODE_AUTH_TOKEN = 'profile.pushqrcodeauthtoken';
880
881 const RESTORE_PASSWORD_METHOD_EMAIL = 'EMAIL';
882 const RESTORE_PASSWORD_METHOD_PHONE = 'PHONE';
883
884 const REPONSE_KEY_BROADCAST = "broadcast";
885
886 protected $access_token = '';
887 protected $httpTimeout = SOCSERV_DEFAULT_HTTP_TIMEOUT;
888 protected $networkNode;
889
890 public static function init($networkNode = null)
891 {
892 $ob = new CBitrix24NetOAuthInterface();
893 if($networkNode)
894 {
895 $ob->setNetworkNode($networkNode);
896 }
897 if($ob->GetAccessToken() !== false)
898 {
899 $token = $ob->getToken();
900 $transport = new self($token);
901 $transport->setNetworkNode($ob->getNetworkNode());
902
903 return $transport;
904 }
905
906 return false;
907 }
908
909 public function __construct($access_token)
910 {
911 $this->access_token = $access_token;
912 $this->networkNode = CBitrix24NetOAuthInterface::NET_URL;
913 }
914
915 public function getNetworkNode(): string
916 {
917 return $this->networkNode;
918 }
919
920 public function setNetworkNode(string $hostWithScheme): void
921 {
922 $this->networkNode = $hostWithScheme;
923 }
924
925 protected function prepareResponse($result)
926 {
927 if (empty($result))
928 {
929 throw new \Bitrix\Main\ArgumentException('Empty result');
930 }
931
932 $result = Json::decode($result);
933
934 if(is_array($result) && isset($result["result"]) && is_array($result["result"]) && array_key_exists(static::REPONSE_KEY_BROADCAST, $result["result"]))
935 {
936 try
937 {
938 if (Loader::includeModule('bitrix24') && class_exists(Broadcast::class))
939 {
940 Broadcast::processBroadcastData($result["result"][static::REPONSE_KEY_BROADCAST]);
941 }
942 }
943 catch(Exception $e)
944 {
945 CSocServBitrix24NetLogger::log('prepareResponse', [
946 'error' => $e->getMessage(),
947 'file' => "{$e->getFile()}:{$e->getLine()}",
948 ]);
949 }
950 unset($result["result"][static::REPONSE_KEY_BROADCAST]);
951 }
952
953 return $result;
954 }
955
956 protected function prepareRequest(array $request, $lang = null)
957 {
958 if (Loader::includeModule('bitrix24'))
959 {
960 $license = License::getCurrent();
961 $request['license'] = $license->getCode();
962 $request['license_partner'] = $license->getPartnerId();
963 if (class_exists(Broadcast::class))
964 {
965 $request["broadcast_last_check"] = Broadcast::getLastBroadcastCheck();
966 }
967 }
968
969 $request["user_lang"] = $lang ?? LANGUAGE_ID;
970 $request["auth"] = $this->access_token;
971
972 return $request;
973 }
974
975 public function call($methodName, $additionalParams = null, $lang = null)
976 {
977 if(!is_array($additionalParams))
978 {
979 $additionalParams = [];
980 }
981
982 $request = $this->prepareRequest($additionalParams, $lang);
983
984 $http = new HttpClient([
985 'socketTimeout' => $this->httpTimeout,
986 'streamTimeout' => $this->httpTimeout,
987 ]);
988 if ($lang)
989 {
990 $http->setCookies(['USER_LANG' => $lang]);
991 }
992 $result = $http->post(
993 $this->networkNode . self::SERVICE_URL . $methodName,
994 $request
995 );
996
997 try
998 {
999 $res = $this->prepareResponse($result);
1000 }
1001 catch(\Bitrix\Main\ArgumentException $e)
1002 {
1003 $res = false;
1004 }
1005
1006 if(!$res)
1007 {
1008 CSocServBitrix24NetLogger::log("CBitrix24NetTransport:call", [
1009 'method' => $methodName,
1010 'status' => $http->getStatus(),
1011 'error' => $http->getError(),
1012 'response' => $result,
1013 ]);
1014 }
1015
1016 return $res;
1017 }
1018
1019 public function batch($actions)
1020 {
1021 $arBatch = array();
1022
1023 if (is_array($actions))
1024 {
1025 foreach ($actions as $query_key => $arCmd)
1026 {
1027 list($cmd, $arParams) = array_values($arCmd);
1028 $arBatch['cmd'][$query_key] = $cmd.(is_array($arParams) ? '?'.http_build_query($arParams) : '');
1029 }
1030 }
1031
1032 return $this->call(self::METHOD_BATCH, $arBatch);
1033 }
1034
1035 public function getMethods()
1036 {
1037 return $this->call(self::METHOD_METHODS);
1038 }
1039
1040 public function getProfile()
1041 {
1042 return $this->call(self::METHOD_PROFILE);
1043 }
1044
1045 public function addProfile($arFields)
1046 {
1047 return $this->call(self::METHOD_PROFILE_ADD, $arFields);
1048 }
1049
1050 public function checkProfile($arFields)
1051 {
1052 return $this->call(self::METHOD_PROFILE_ADD_CHECK, $arFields);
1053 }
1054
1055 public function updateProfile($arFields)
1056 {
1057 return $this->call(self::METHOD_PROFILE_UPDATE, $arFields);
1058 }
1059
1060 public function deleteProfile($ID)
1061 {
1062 return $this->call(self::METHOD_PROFILE_DELETE, array("ID" => $ID));
1063 }
1064
1065 public function getProfileContacts($userId)
1066 {
1067 return $this->call(self::METHOD_PROFILE_CONTACTS, array("USER_ID" => $userId));
1068 }
1069
1076 public function restoreProfilePassword($userId, $restoreMethod)
1077 {
1078 return $this->call(self::METHOD_PROFILE_RESTORE_PASSWORD, array("USER_ID" => $userId, 'RESTORE_METHOD' => $restoreMethod, 'LANGUAGE_ID' => LANGUAGE_ID));
1079 }
1080
1086 public function pushQrCodeAuthToken(array $params)
1087 {
1088 return $this->call(self::METHOD_PROFILE_PUSH_QRCODE_AUTH_TOKEN, $params, LANGUAGE_ID);
1089 }
1090}
1091
1097class CBitrix24NetPortalTransport extends CBitrix24NetTransport
1098{
1099 protected $clientId = null;
1100 protected $clientSecret = null;
1101
1102 public static function init($networkNode = null)
1103 {
1104 $result = parent::init($networkNode);
1105
1106 if (!$result)
1107 {
1108 $interface = new CBitrix24NetOAuthInterface();
1109 if ($networkNode)
1110 {
1111 $interface->setNetworkNode($networkNode);
1112 }
1113 if ($interface->getAppID())
1114 {
1115 $result = new self($interface->getAppID(), $interface->getAppSecret());
1116 $result->setNetworkNode($interface->getNetworkNode());
1117 }
1118 }
1119
1120 return $result;
1121 }
1122
1123 public function __construct($clientId, $clientSecret)
1124 {
1125 $this->clientId = $clientId;
1126 $this->clientSecret = $clientSecret;
1127
1128 return parent::__construct('');
1129 }
1130
1131 protected function prepareRequest(array $request, $lang = null)
1132 {
1133 $request = parent::prepareRequest($request, $lang);
1134
1135 $request["client_id"] = $this->clientId;
1136 $request["client_secret"] = $this->clientSecret;
1137 unset($request['auth']);
1138
1139 return $request;
1140 }
1141
1142}
$arParams
Определения access_dialog.php:21
return select
Определения access_edit.php:440
if($_SERVER $defaultValue['REQUEST_METHOD']==="GET" &&!empty($RestoreDefaults) && $bizprocPerms==="W" &&check_bitrix_sessid())
Определения options.php:32
global $APPLICATION
Определения include.php:80
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
static get($moduleId, $name, $default="", $siteId=false)
Определения option.php:30
Определения loader.php:13
Определения user.php:48
Определения json.php:9
prepareResponse($result)
Определения bitrix24net.php:925
batch($actions)
Определения bitrix24net.php:1019
Определения authmanager.php:985
static GetOption($opt)
Определения authmanager.php:1339
getFormHtml($arParams)
Определения bitrix24net.php:103
const ID
Определения bitrix24net.php:82
CheckSettings()
Определения bitrix24net.php:97
const NETWORK_URL
Определения bitrix24net.php:83
GetSettings()
Определения bitrix24net.php:87
$entityOAuth
Определения bitrix24net.php:85
getUrl($mode="page")
Определения bitrix24net.php:135
static log(string $message, array $additionalParams=[])
Определения bitrix24net.php:47
static JSEscape($s)
Определения util.php:48
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
$_REQUEST["admin_mnu_menu_id"]
Определения get_menu.php:8
while($arParentIBlockProperty=$dbParentIBlockProperty->Fetch()) $errorMessage
const EMAIL
Определения idea_notify.php:6
AddMessage2Log($text, $module='', $traceDepth=6, $showArgs=false)
Определения tools.php:3941
IsModuleInstalled($module_id)
Определения tools.php:5301
htmlspecialcharsbx($string, $flags=ENT_COMPAT, $doubleEncode=true)
Определения tools.php:2701
GetMessage($name, $aReplace=null)
Определения tools.php:3397
$message
Определения payment.php:8
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
if(empty($signedUserToken)) $key
Определения quickway.php:257
const ADMIN_SECTION
Определения rss.php:2
$location
Определения options.php:2729
const SOCSERV_REGISTRATION_DENY
Определения include.php:4
const SITE_ID
Определения sonet_set_content_view.php:12
$GLOBALS['_____370096793']
Определения update_client.php:1
$url
Определения iframe.php:7