1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
mailru2.php
См. документацию.
1<?
2
7
9
11{
12 const ID = "MailRu2";
13 const CONTROLLER_URL = "https://www.bitrix24.ru/controller";
14
15 private static bool $isCloudPortal;
16 protected $entityOAuth;
17
18 public function GetSettings()
19 {
20 return array(
21 array("mailru2_client_id", GetMessage("socserv_mailru2_id"), "", Array("text", 40)),
22 array("mailru2_client_secret", GetMessage("socserv_mailru2_key"), "", Array("text", 40)),
23 array(
24 'note' => getMessage(
25 'socserv_mailru2_sett_note_2',
26 array(
27 '#URL#' => $this->getEntityOAuth()->getRedirectUri(),
28 '#MAIL_URL#' => \CHttp::urn2uri('/bitrix/tools/mail_oauth.php'),
29 )
30 ),
31 ),
32 );
33 }
34
39 public function getEntityOAuth($code = false)
40 {
41 if (!$this->entityOAuth)
42 {
43 $this->entityOAuth = new CMailRu2Interface();
44 }
45
46 if ($code !== false)
47 {
48 $this->entityOAuth->setCode($code);
49 }
50
51 return $this->entityOAuth;
52 }
53
54 public function GetFormHtml($arParams)
55 {
56 $url = $this->getUrl($arParams);
57
58 $phrase = ($arParams["FOR_INTRANET"])
59 ? GetMessage("socserv_mailru2_note_intranet")
60 : GetMessage("socserv_mailru2_note");
61
62 return $arParams["FOR_INTRANET"]
63 ? array("ON_CLICK" => 'onclick="BX.util.popup(\'' . htmlspecialcharsbx(CUtil::JSEscape($url)) . '\', 460, 420)"')
64 : '<a href="javascript:void(0)" onclick="BX.util.popup(\'' . htmlspecialcharsbx(CUtil::JSEscape($url)) . '\', 460, 420)" class="bx-ss-button mailru-button"></a><span class="bx-spacer"></span><span>' . $phrase . '</span>';
65 }
66
67 public function GetOnClickJs($arParams)
68 {
69 $url = $this->getUrl($arParams);
70 return "BX.util.popup('" . CUtil::JSEscape($url) . "', 460, 420)";
71 }
72
73 public function getUrl($arParams)
74 {
75 global $APPLICATION;
76
80
81 $backUrl = (string)(
82 $arParams['BACKURL']
83 ?? $APPLICATION->GetCurPageParam('', [
84 'logout', 'auth_service_error', 'auth_service_id', 'backurl',
85 ])
86 );
87 $state = StateService::getInstance()->createState([
88 'site_id' => SITE_ID,
89 'check_key' => \CSocServAuthManager::getUniqueKey(),
90 'redirect_url' => $backUrl,
91 ]);
92
93 if ($this->isCloudPortal())
94 {
95 $portalRedirectUri = new Uri(
96 $this->getEntityOAuth()->GetRedirectURI()
97 );
98 $portalRedirectUri->addParams([
99 'state' => $state,
100 ]);
101
102 $state = (string)$portalRedirectUri;
103 $redirectUri = new Uri(
104 static::CONTROLLER_URL . '/redirect.php'
105 );
106 }
107 else
108 {
109 $redirectUri = $this->getEntityOAuth()->GetRedirectURI();
110 }
111
112 return $this->getEntityOAuth()->GetAuthUrl($redirectUri, $state);
113 }
114
115 public function addScope($scope)
116 {
117 return $this->getEntityOAuth()->addScope($scope);
118 }
119
120 public function prepareUser($arUser, $short = false)
121 {
122 $entityOAuth = $this->getEntityOAuth();
123 $arFields = array(
124 'EXTERNAL_AUTH_ID' => self::ID,
125 'XML_ID' => $arUser["email"],
126 'LOGIN' => $arUser["email"],
127 'EMAIL' => $arUser["email"],
128 'NAME' => $arUser["first_name"],
129 'LAST_NAME' => $arUser["last_name"],
130 'OATOKEN' => $entityOAuth->getToken(),
131 'OATOKEN_EXPIRES' => $entityOAuth->getAccessTokenExpires(),
132 );
133
134 if (!$short && isset($arUser['image']))
135 {
136 $picture_url = $arUser['image'];
137 $temp_path = CFile::GetTempName('', 'picture.jpg');
138
139 $ob = new HttpClient(array(
140 "redirect" => true
141 ));
142 $ob->download($picture_url, $temp_path);
143
144 $arPic = CFile::MakeFileArray($temp_path);
145 if ($arPic)
146 {
147 $arFields["PERSONAL_PHOTO"] = $arPic;
148 }
149 }
150
151 if (isset($arUser['birthday']))
152 {
153 if ($date = MakeTimeStamp($arUser['birthday'], "MM/DD/YYYY"))
154 {
155 $arFields["PERSONAL_BIRTHDAY"] = ConvertTimeStamp($date);
156 }
157 }
158
159 if (isset($arUser['gender']) && $arUser['gender'] != '')
160 {
161 if ($arUser['gender'] == 'm')
162 {
163 $arFields["PERSONAL_GENDER"] = 'M';
164 }
165 elseif ($arUser['gender'] == 'f')
166 {
167 $arFields["PERSONAL_GENDER"] = 'F';
168 }
169 }
170
171 if (SITE_ID <> '')
172 {
173 $arFields["SITE_ID"] = SITE_ID;
174 }
175
176 return $arFields;
177 }
178
179 private function isCloudPortal(): bool
180 {
181 self::$isCloudPortal ??= IsModuleInstalled('bitrix24') && defined('BX24_HOST_NAME');
182
183 return self::$isCloudPortal;
184 }
185
186 private function getRequestState(string $state = null): ?array
187 {
188 if (empty($state))
189 {
190 if (isset($_REQUEST['state']))
191 {
192 $state = $_REQUEST['state'];
193 }
194 else
195 {
196 return null;
197 }
198 }
199
200 return StateService::getInstance()->getPayload($state);
201 }
202
203 private function getAuthorizeRedirectUrl($authError): string
204 {
205 global $APPLICATION;
206
210
211 $bSuccess = $authError === true;
212
213 $url = $APPLICATION->GetCurDir();
214 if ($url === '/login/')
215 {
216 $url = '';
217 }
218
219 $aRemove = array("logout", "auth_service_error", "auth_service_id", "code", "error_reason", "error", "error_description", "check_key", "current_fieldset");
220 $arState = $this->getRequestState();
221
222 if (
223 $bSuccess
224 && (
225 isset($arState['backurl'])
226 || isset($arState['redirect_url'])
227 )
228 )
229 {
230 $url = !empty($arState['redirect_url']) ? $arState['redirect_url'] : $arState['backurl'];
231 if (mb_substr($url, 0, 1) !== "#")
232 {
233 $parseUrl = parse_url($url);
234
235 $urlPath = $parseUrl["path"];
236 $arUrlQuery = explode('&', $parseUrl["query"]);
237
238 foreach ($arUrlQuery as $key => $value)
239 {
240 foreach ($aRemove as $param)
241 {
242 if (mb_strpos($value, $param."=") === 0)
243 {
244 unset($arUrlQuery[$key]);
245 break;
246 }
247 }
248 }
249
250 $url = (!empty($arUrlQuery)) ? $urlPath . '?' . implode("&", $arUrlQuery) : $urlPath;
251 }
252 }
253
254 if ($authError === SOCSERV_REGISTRATION_DENY)
255 {
256 $url = (preg_match("/\?/", $url)) ? $url . '&' : $url . '?';
257 $url .= 'auth_service_id=' . self::ID . '&auth_service_error=' . $authError;
258 }
259 elseif ($bSuccess !== true)
260 {
261 $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);
262 }
263
264 if (CModule::IncludeModule("socialnetwork") && mb_strpos($url, "current_fieldset=") === false)
265 {
266 $url .= ((mb_strpos($url, "?") === false) ? '?' : '&') . "current_fieldset=SOCSERV";
267 }
268
269 return $url;
270 }
271
272 public function Authorize()
273 {
274 global $APPLICATION;
275
276 $APPLICATION->RestartBuffer();
277 $authError = SOCSERV_AUTHORISATION_ERROR;
278
279 if (
280 isset($_REQUEST["code"])
281 && $_REQUEST["code"] <> ''
282 && CSocServAuthManager::CheckUniqueKey()
283 )
284 {
285 if ($this->isCloudPortal())
286 {
287 $redirect_uri = static::CONTROLLER_URL . "/redirect.php";
288 }
289 else
290 {
291 $redirect_uri = $this->getEntityOAuth()->GetRedirectURI();
292 }
293
294 $entityOAuth = $this->getEntityOAuth($_REQUEST['code']);
295 if ($entityOAuth->GetAccessToken($redirect_uri) !== false)
296 {
297 $arUser = $entityOAuth->GetCurrentUser();
298 if (is_array($arUser) && isset($arUser["email"]))
299 {
300 $authError = $this->AuthorizeUser(
301 $this->prepareUser($arUser)
302 );
303 }
304 }
305 }
306
307 $url = $this->getAuthorizeRedirectUrl($authError);
308 ?>
309 <script>
310 if (window.opener)
311 window.opener.location = '<?=CUtil::JSEscape($url)?>';
312 window.close();
313 </script>
314 <?
315 CMain::FinalActions();
316 }
317
318 public function setUser($userId)
319 {
320 $this->getEntityOAuth()->setUser($userId);
321 }
322}
323
324
325class CMailRu2Interface extends CSocServOAuthTransport
326{
327 const SERVICE_ID = "MailRu2";
328
329 const AUTH_URL = "https://oauth.mail.ru/login";
330 const TOKEN_URL = "https://oauth.mail.ru/token";
331 const USER_INFO_URL = "https://oauth.mail.ru/userinfo";
332
333 protected $userId = false;
334 protected $responseData = array();
335
336 protected $scope = array(
337 "userinfo",
338 );
339
340 public function __construct($appID = false, $appSecret = false, $code = false)
341 {
342 if ($appID === false)
343 {
344 $appID = trim(CSocServAuth::GetOption("mailru2_client_id"));
345 }
346
347 if ($appSecret === false)
348 {
349 $appSecret = trim(CSocServAuth::GetOption("mailru2_client_secret"));
350 }
351
352 parent::__construct($appID, $appSecret, $code);
353 }
354
358 public function GetRedirectURI()
359 {
360 return \CHTTP::URN2URI("/bitrix/tools/oauth/mailru2.php");
361 }
362
366 public function GetAuthUrl($redirect_uri, $state = '')
367 {
368 return self::AUTH_URL
369 ."?client_id=".$this->appID
370 ."&redirect_uri=".urlencode($redirect_uri)
371 ."&scope=".$this->getScopeEncode()
372 ."&response_type="."code"
373 .($state <> '' ? '&state='.urlencode($state) : '')
374 .'&prompt_force=1';
375 }
376
380 public function getResult()
381 {
382 return $this->responseData;
383 }
384
390 public function GetAccessToken($redirect_uri)
391 {
392 $token = $this->getStorageTokens();
393 if (is_array($token))
394 {
395 $this->access_token = $token["OATOKEN"];
396 $this->accessTokenExpires = $token["OATOKEN_EXPIRES"];
397
398 if (!$this->code)
399 {
400 if ($this->checkAccessToken())
401 {
402 return true;
403 }
404 else if (isset($token['REFRESH_TOKEN']))
405 {
406 if ($this->getNewAccessToken($token['REFRESH_TOKEN'], $this->userId, true))
407 {
408 return true;
409 }
410 }
411 }
412
413 $this->deleteStorageTokens();
414 }
415
416 if ($this->code === false)
417 {
418 return false;
419 }
420
421 $query = array(
422 "code" => $this->code,
423 "grant_type" => "authorization_code",
424 "redirect_uri" => $redirect_uri,
425 );
426
427 $h = new \Bitrix\Main\Web\HttpClient(array(
428 "socketTimeout" => $this->httpTimeout,
429 "streamTimeout" => $this->httpTimeout,
430 ));
431 $h->setAuthorization($this->appID, $this->appSecret);
432 $h->setHeader('User-Agent', 'Bitrix'); // Mail.ru requires User-Agent to be set
433
434 $result = $h->post(self::TOKEN_URL, $query);
435
436 try
437 {
439 }
440 catch (\Bitrix\Main\ArgumentException $e)
441 {
442 $arResult = array();
443 }
444
445 if ((isset($arResult["access_token"]) && $arResult["access_token"] <> ''))
446 {
447 $this->access_token = $arResult["access_token"];
448 $this->accessTokenExpires = time() + $arResult["expires_in"];
449 $this->refresh_token = $arResult['refresh_token'];
450
451 $_SESSION["OAUTH_DATA"] = array(
452 "OATOKEN" => $this->access_token,
453 "OATOKEN_EXPIRES" => $this->accessTokenExpires,
454 "REFRESH_TOKEN" => $this->refresh_token
455 );
456 return true;
457 }
458
459 return false;
460 }
461
469 public function getNewAccessToken($refreshToken = false, $userId = 0, $save = false)
470 {
471 if ($this->appID == false || $this->appSecret == false)
472 {
473 return false;
474 }
475
476 if ($refreshToken == false)
477 {
478 $refreshToken = $this->refresh_token;
479 }
480
481 $http = new HttpClient(array(
482 'socketTimeout' => $this->httpTimeout,
483 'streamTimeout' => $this->httpTimeout,
484 ));
485 $http->setHeader('User-Agent', 'Bitrix');
486
487 $result = $http->post(static::TOKEN_URL, array(
488 'refresh_token' => $refreshToken,
489 'client_id' => $this->appID,
490 'client_secret' => $this->appSecret,
491 'grant_type' => 'refresh_token',
492 ));
493
494 try
495 {
496 $arResult = Json::decode($result);
497 }
498 catch (\Bitrix\Main\ArgumentException $e)
499 {
500 $arResult = array();
501 }
502
503 if (!empty($arResult['access_token']))
504 {
505 $this->access_token = $arResult['access_token'];
506 $this->accessTokenExpires = $arResult['expires_in'] + time();
507 if ($save && intval($userId) > 0)
508 {
509 $dbSocservUser = \Bitrix\Socialservices\UserTable::getList(array(
510 'filter' => array(
511 '=EXTERNAL_AUTH_ID' => static::SERVICE_ID,
512 '=USER_ID' => $userId,
513 ),
514 'select' => array('ID')
515 ));
516 if ($arOauth = $dbSocservUser->fetch())
517 {
518 \Bitrix\Socialservices\UserTable::update($arOauth['ID'], array(
519 'OATOKEN' => $this->access_token,
520 'OATOKEN_EXPIRES' => $this->accessTokenExpires)
521 );
522 }
523 }
524
525 return true;
526 }
527
528 return false;
529 }
530
534 public function GetCurrentUser()
535 {
536 if ($this->access_token === false)
537 {
538 return false;
539 }
540
541 $http = new HttpClient();
542 $http->setTimeout($this->httpTimeout);
543
544 $result = $http->get(self::USER_INFO_URL . '?access_token=' . $this->access_token);
545
546 try
547 {
548 return Json::decode($result);
549 }
550 catch (\Bitrix\Main\ArgumentException $e)
551 {
552 return false;
553 }
554 }
555
559 public function GetAppInfo()
560 {
561 return false;
562 }
563
567 public function getScopeEncode()
568 {
569 return implode(' ', array_map('urlencode', array_unique($this->getScope())));
570 }
571
572}
$arParams
Определения access_dialog.php:21
$arResult
Определения generate_coupon.php:16
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
Определения json.php:9
static decode($data)
Определения json.php:50
Определения uri.php:17
Определения mailru2.php:326
__construct($appID=false, $appSecret=false, $code=false)
Определения mailru2.php:340
getNewAccessToken($refreshToken=false, $userId=0, $save=false)
Определения mailru2.php:469
const TOKEN_URL
Определения mailru2.php:330
const USER_INFO_URL
Определения mailru2.php:331
$scope
Определения mailru2.php:336
GetAccessToken($redirect_uri)
Определения mailru2.php:390
GetCurrentUser()
Определения mailru2.php:534
getScopeEncode()
Определения mailru2.php:567
GetRedirectURI()
Определения mailru2.php:358
GetAuthUrl($redirect_uri, $state='')
Определения mailru2.php:366
$userId
Определения mailru2.php:333
GetAppInfo()
Определения mailru2.php:559
$responseData
Определения mailru2.php:334
getResult()
Определения mailru2.php:380
Определения authmanager.php:985
static GetOption($opt)
Определения authmanager.php:1339
Определения mailru2.php:11
const ID
Определения mailru2.php:12
GetSettings()
Определения mailru2.php:18
$entityOAuth
Определения mailru2.php:16
getEntityOAuth($code=false)
Определения mailru2.php:39
const CONTROLLER_URL
Определения mailru2.php:13
GetFormHtml($arParams)
Определения mailru2.php:54
getStorageTokens()
Определения oauthtransport.php:116
deleteStorageTokens()
Определения oauthtransport.php:134
checkAccessToken()
Определения oauthtransport.php:153
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
$result
Определения get_property_values.php:14
$query
Определения get_search.php:11
$save
Определения iblock_catalog_edit.php:365
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