1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
bitrix24.php
См. документацию.
1<?
2
4
6
8{
9 const ID = "Bitrix24OAuth";
10
12 protected $entityOAuth = null;
13
14 protected $appID;
15 protected $appSecret;
16 protected $portalURI = '';
17 protected $redirectURI = '';
18
19 protected $signature = null;
20
22 {
23 $this->appID = $appID;
24 $this->appSecret = $appSecret;
25 $this->portalURI = $portalURI;
26 $this->redirectURI = $redirectURI;
27
28 return parent::__construct($userId);
29 }
30
31 public function getEntityOAuth($code = false)
32 {
33 if(!$this->entityOAuth)
34 {
35 $this->entityOAuth = new CBitrixOAuthInterface($this->appID, $this->appSecret, $this->portalURI);
36 }
37
38 if($code !== false)
39 {
40 $this->entityOAuth->setCode($code);
41 }
42
43 return $this->entityOAuth;
44 }
45
46 public function addScope($scope)
47 {
48 return $this->getEntityOAuth()->addScope($scope);
49 }
50
51 public function getRequestTokenUrl()
52 {
53 return $this->getEntityOAuth()->GetAuthUrl($this->redirectURI);
54 }
55
56 public function getAccessToken($code, $addScope = null)
57 {
58 $this->getEntityOAuth()->setCode($code);
59 if($addScope !== null)
60 {
61 $this->getEntityOAuth()->addScope($addScope);
62 }
63
64 $this->getEntityOAuth()->GetAccessToken($this->redirectURI);
65
66 return $this->getEntityOAuth()->getToken();
67 }
68
69 public function getStorageToken()
70 {
71 $accessToken = null;
72 $userId = intval($this->userId);
73 if($userId > 0)
74 {
75 $dbSocservUser = UserTable::getList([
76 'filter' => [
77 '=USER_ID' => $userId,
78 '=XML_ID' => $this->appID,
79 "=EXTERNAL_AUTH_ID" => "Bitrix24OAuth",
80 '=PERSONAL_WWW' => $this->portalURI
81 ],
82 'select' => ["OATOKEN", "REFRESH_TOKEN", "OATOKEN_EXPIRES", "OASECRET"]
83 ]);
84 if($arOauth = $dbSocservUser->fetch())
85 {
86 $accessToken = $arOauth["OATOKEN"];
87 if(
88 empty($accessToken)
89 || (
90 (intval($arOauth["OATOKEN_EXPIRES"]) > 0)
91 && (intval($arOauth["OATOKEN_EXPIRES"] < intval(time())))
92 )
93 )
94 {
95 if(isset($arOauth['REFRESH_TOKEN']))
96 {
97 $this->getEntityOAuth()->getNewAccessToken($arOauth['REFRESH_TOKEN'], $userId, true);
98 }
99 if(($accessToken = $this->getEntityOAuth()->getToken()) === false)
100 {
101 return null;
102 }
103
104 $this->getEntityOAuth()->saveDataDB();
105 }
106 }
107 }
108
109 return $accessToken;
110 }
111
112 public function Authorize()
113 {
114 global $APPLICATION;
115 $APPLICATION->RestartBuffer();
116 if((isset($_REQUEST["code"]) && $_REQUEST["code"] <> '') && CSocServAuthManager::CheckUniqueKey())
117 {
118 $redirect_uri = \CHTTP::URN2URI('/bitrix/tools/oauth/bitrix24.php');
119 $userId = intval($_REQUEST['uid']);
120 $appID = trim(COption::GetOptionString("socialservices", "bitrix24_gadget_appid", ''));
121 $appSecret = trim(COption::GetOptionString("socialservices", "bitrix24_gadget_appsecret", ''));
122 $portalURI = $_REQUEST['domain'];
123 if(mb_strpos($portalURI, "http://") === false && mb_strpos($portalURI, "https://") === false)
124 $portalURI = "https://".$portalURI;
126
127 $this->entityOAuth = $gAuth;
128 $gAuth->addScope(explode(',', $_REQUEST["scope"]));
129 if($gAuth->GetAccessToken($redirect_uri) !== false)
130 {
131 $gAuth->saveDataDB();
132 }
133 }
135 $mode = 'opener';
136 $url = CUtil::JSEscape($url);
137 $location = ($mode == "opener") ? 'if(window.opener) window.opener.location = \''.$url.'\'; window.close();' : ' window.location = \''.$url.'\';';
138 $JSScript = '
139 <script>
140 '.$location.'
141 </script>
142 ';
143
144 echo $JSScript;
145
146 CMain::FinalActions();
147 }
148
149 public static function gadgetAuthorize()
150 {
151 global $APPLICATION;
152 $APPLICATION->RestartBuffer();
153
154 if((isset($_REQUEST["code"]) && $_REQUEST["code"] <> '') && CSocServAuthManager::CheckUniqueKey())
155 {
156 CUserOptions::SetOption('socialservices', 'bitrix24_task_planer_gadget_code', $_REQUEST["code"]);
157 }
158
159 $url = \CHTTP::URN2URI(BX_ROOT);
160 $mode = 'opener';
161 $url = CUtil::JSEscape($url);
162 $location = ($mode == "opener") ? 'if(window.opener) window.opener.location = \''.$url.'\'; window.close();' : ' window.location = \''.$url.'\';';
163 $JSScript = '
164 <script>
165 '.$location.'
166 </script>
167 ';
168
169 echo $JSScript;
170
171 die();
172 }
173}
174
175class CBitrixOAuthInterface extends CSocServOAuthTransport
176{
177 const SERVICE_ID = 'Bitrix24OAuth';
178
179 protected $appID;
180 protected $appSecret;
181 protected $code = false;
182 protected $access_token = false;
183 protected $member_id = false;
184
185 protected $signatureKey = false;
186
187 protected $accessTokenExpires = 0;
188 protected $refresh_token = '';
189 protected $portalURI = '';
190 protected $scope = array();
191
192 public function __construct($appID, $appSecret, $portalURI, $code = false)
193 {
194 $this->portalURI = $portalURI;
195
196 return parent::__construct($appID, $appSecret, $code);
197 }
198
199 public function getMemberId()
200 {
201 return $this->member_id;
202 }
203
204 public function GetAuthUrl($redirect_uri, $state = '')
205 {
206 return $this->portalURI.'/oauth/authorize/'.
207 "?client_id=".urlencode($this->appID).
208 "&redirect_uri=".urlencode($redirect_uri).
209 "&scope=".$this->getScopeEncode().
210 "&response_type=code".
211 ($state != '' ? '&state='.urlencode($state) : '');
212 }
213
214 public function GetAccessToken($redirect_uri)
215 {
216 if($this->code === false)
217 {
218 return false;
219 }
220
221 $httpClient = new \Bitrix\Main\Web\HttpClient(array(
222 "socketTimeout" => $this->httpTimeout
223 ));
224
225 $result = $httpClient->get($this->portalURI.'/oauth/token/'.
226 '?code='.$this->code.
227 '&client_id='.$this->appID.
228 '&client_secret='.$this->appSecret.
229 '&redirect_uri='.$redirect_uri.
230 '&scope='.$this->getScopeEncode().
231 '&grant_type=authorization_code');
232
233 $arResult = \Bitrix\Main\Web\Json::decode($result);
234
235 if(isset($arResult["access_token"]) && $arResult["access_token"] <> '')
236 {
237 $this->access_token = $arResult["access_token"];
238 $this->accessTokenExpires = time() + $arResult["expires_in"];
239 $this->member_id = $arResult["member_id"];
240
241 if(isset($arResult["refresh_token"]) && $arResult["refresh_token"] <> '')
242 {
243 $this->refresh_token = $arResult["refresh_token"];
244 }
245
246 return true;
247 }
248 return false;
249 }
250
251 public function getNewAccessToken($refreshToken, $userId = 0, $save = false, $scope = array())
252 {
253 if($this->appID == false || $this->appSecret == false)
254 {
255 return false;
256 }
257
258 if($scope != null)
259 {
260 $this->addScope($scope);
261 }
262
263 $httpClient = new \Bitrix\Main\Web\HttpClient(array(
264 "socketTimeout" => $this->httpTimeout
265 ));
266
267 $result = $httpClient->get($this->portalURI."/oauth/token/".
268 "?client_id=".urlencode($this->appID).
269 "&grant_type=refresh_token".
270 "&client_secret=".$this->appSecret.
271 "&refresh_token=".$refreshToken.
272 '&scope='.$this->getScopeEncode());
273
274 $arResult = \Bitrix\Main\Web\Json::decode($result);
275
276 if(isset($arResult["access_token"]) && $arResult["access_token"] <> '')
277 {
278 $this->access_token = $arResult["access_token"];
279 $this->accessTokenExpires = $arResult["expires_in"];
280 $this->member_id = $arResult["member_id"];
281
282 if(isset($arResult["refresh_token"]) && $arResult["refresh_token"] <> '')
283 {
284 $this->refresh_token = $arResult["refresh_token"];
285 }
286
287 if($save && intval($userId) > 0)
288 {
289 CUserOptions::SetOption('socialservices', 'bitrix24_task_planer_gadget_token', $this->access_token, false, $userId);
290 CUserOptions::SetOption('socialservices', 'bitrix24_task_planer_gadget_token_expire', $this->accessTokenExpires + time(), false, $userId);
291 CUserOptions::SetOption('socialservices', 'bitrix24_task_planer_gadget_refresh_token', $this->refresh_token, false, $userId);
292 }
293
294 return true;
295 }
296 return false;
297 }
298
299
300 public function saveDataDB()
301 {
302 global $USER;
303
304 $dbSocUser = UserTable::getList([
305 'filter' => [
306 '=XML_ID' => $this->appID,
307 '=PERSONAL_WWW' => $this->portalURI,
308 '=EXTERNAL_AUTH_ID' => 'Bitrix24OAuth'
309 ],
310 'select' => ['ID']
311 ]);
312
313 if($USER->IsAuthorized())
314 {
315 $arFields = array(
316 'PERSONAL_WWW' => $this->portalURI,
317 'XML_ID' => $this->appID,
318 'EXTERNAL_AUTH_ID' => static::SERVICE_ID,
319 'USER_ID' => $USER->GetID(),
320 'OATOKEN' => $this->access_token,
321 'OATOKEN_EXPIRES' => $this->accessTokenExpires,
322 'OASECRET' => $this->getSignatureKey(),
323 'LOGIN' => $this->appID,
324 );
325
326 if($this->refresh_token <> '')
327 {
328 $arFields['REFRESH_TOKEN'] = $this->refresh_token;
329 }
330
331 if($arUser = $dbSocUser->fetch())
332 {
333 $result = UserTable::update($arUser["ID"], $arFields);
334 return $result->isSuccess() ? $arUser["ID"] : false;
335 }
336 else
337 {
338 $result = UserTable::add($arFields);
339 return $result->isSuccess() ? $result->getId() : false;
340 }
341 }
342 return true;
343 }
344
345 public function getSignatureKey()
346 {
347 if($this->member_id && $this->appSecret)
348 {
349 $this->signatureKey = md5($this->member_id.$this->appSecret);
350 }
351
352 return $this->signatureKey;
353 }
354}
355
356class CBitrixPHPAppTransport
357{
358 protected $access_token = '';
359 protected $signatureKey = false;
360
361 protected $portalURI = '';
362 protected $httpTimeout = SOCSERV_DEFAULT_HTTP_TIMEOUT;
363
364 public function __construct($access_token, $portalURI, $signatureKey = false)
365 {
366 $this->access_token = $access_token;
367 $this->portalURI = $portalURI;
368 $this->signatureKey = $signatureKey;
369 }
370
371 public function setSignatureKey($signatureKey)
372 {
373 $this->signatureKey = $signatureKey;
374 }
375
376 protected function prepareAnswer($result)
377 {
378 return \Bitrix\Main\Web\Json::decode($result);
379 }
380
381 protected function prepareRequest($params)
382 {
383 if(is_array($params))
384 {
385 $params = CHTTP::PrepareData($params);
386 }
387
388 return $params;
389 }
390
391 public function call($methodName, $additionalParams = '')
392 {
393 $httpClient = new \Bitrix\Main\Web\HttpClient(array(
394 "socketTimeout" => $this->httpTimeout
395 ));
396
397 $result = $httpClient->post($this->portalURI.'/rest/'.$methodName, 'auth='.$this->access_token.'&'.static::prepareRequest($additionalParams));
398
399 return $this->prepareAnswer($result);
400 }
401
402 public function callSigned($methodName, $additionalParams = '')
403 {
404 if($this->signatureKey)
405 {
406 $state = RandString(32);
407
408 $result = $this->call($methodName, 'state=' . $state . "&" . static::prepareRequest($additionalParams));
409
410 if(is_array($result) && isset($result["signature"]))
411 {
412 $signer = new Bitrix\Socialservices\Bitrix24Signer();
413 $signer->setKey($this->signatureKey);
414
415 //try
416 //{
417
418 $signatureCheck = $signer->unsign($result["signature"]);
419
420 if(
421 $signatureCheck["state"] === $state
422 )
423 {
424 foreach($signatureCheck as $key => $value)
425 {
426 if($key !== "state")
427 {
428 if($result['result'][$key] !== $value)
429 {
430 return false;
431 }
432 }
433 }
434
435 unset($result["signature"]);
436
437 return $result;
438 }
439
440 //}
441 //catch (Bitrix\Main\Security\Sign\BadSignatureException $e)
442 //{}
443 }
444 }
445
446 return false;
447 }
448
449 public function batch($actions)
450 {
451 $arBatch = array();
452
453 if(is_array($actions))
454 {
455 foreach($actions as $query_key => $arCmd)
456 {
457 list($cmd, $arParams) = array_values($arCmd);
458 $arBatch['cmd'][$query_key] = $cmd.'?'.CHTTP::PrepareData($arParams);
459 }
460 }
461 $arBatch['auth'] = $this->access_token;
462 $batch_url = '/rest/batch';
463
464 $httpClient = new \Bitrix\Main\Web\HttpClient();
465 $result = $httpClient->post($this->portalURI.$batch_url, $arBatch);
466
467 return $this->prepareAnswer($result);
468 }
469
470 public function getAllMethods()
471 {
472 return $this->call('methods', array('full' => 'true'));
473 }
474
475 public function getPlannerTasksId()
476 {
477 return $this->call('task.planner.getlist');
478 }
479
480 public function getCurrentUser($signatureKey = '')
481 {
482 if($signatureKey !== '')
483 {
484 $this->setSignatureKey($signatureKey);
485 }
486
487 if($this->signatureKey)
488 {
489 return $this->callSigned('user.current');
490 }
491 else
492 {
493 return $this->call('user.current');
494 }
495 }
496}
return select
Определения access_edit.php:440
const BX_ROOT
Определения bx_root.php:3
global $APPLICATION
Определения include.php:80
Определения user.php:48
batch($actions)
Определения bitrix24.php:449
static URN2URI($urn, $server_name='')
Определения http.php:39
Определения authmanager.php:985
$userId
Определения authmanager.php:991
static CheckUniqueKey($bUnset=true)
Определения authmanager.php:351
Определения bitrix24.php:8
const ID
Определения bitrix24.php:9
getAccessToken($code, $addScope=null)
Определения bitrix24.php:56
__construct($appID, $appSecret, $portalURI, $redirectURI, $userId=null)
Определения bitrix24.php:21
$appSecret
Определения bitrix24.php:15
$redirectURI
Определения bitrix24.php:17
Authorize()
Определения bitrix24.php:112
getRequestTokenUrl()
Определения bitrix24.php:51
$portalURI
Определения bitrix24.php:16
$entityOAuth
Определения bitrix24.php:12
addScope($scope)
Определения bitrix24.php:46
getEntityOAuth($code=false)
Определения bitrix24.php:31
getStorageToken()
Определения bitrix24.php:69
$signature
Определения bitrix24.php:19
$appID
Определения bitrix24.php:14
$_REQUEST["admin_mnu_menu_id"]
Определения get_menu.php:8
if(!is_null($config))($config as $configItem)(! $configItem->isVisible()) $code
Определения options.php:195
IncludeModuleLangFile($filepath, $lang=false, $bReturnArray=false)
Определения tools.php:3778
$location
Определения options.php:2729
$url
Определения iframe.php:7