Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
network.php
1<?php
10
17
18Loc::loadMessages(__FILE__);
19
26{
27 const ERROR_SEARCH_STRING_TO_SHORT = 'ERROR_SEARCH_STRING_TO_SHORT';
28 const ERROR_SEARCH_USER_NOT_FOUND = 'ERROR_SEARCH_USER_NOT_FOUND';
29 const ERROR_REGISTER_USER = 'ERROR_REGISTER_USER';
30 const ERROR_SOCSERV_TRANSPORT = 'ERROR_SOCSERV_TRANSPORT';
31 const ERROR_NETWORK_IN_NOT_ENABLED = 'ERROR_NETWORK_IN_NOT_ENABLED';
32 const ERROR_INCORRECT_PARAMS = 'ERROR_INCORRECT_PARAMS';
33
34 const EXTERNAL_AUTH_ID = 'replica';
35
36 const ADMIN_SESSION_KEY = "SS_B24NET_STATE";
37
39 public $errorCollection = null;
40
41 protected static $lastUserStatus = null;
42
43 function __construct()
44 {
45 $this->errorCollection = new ErrorCollection();
46 }
47
54 public function isOptionEnabled()
55 {
56 return false;
57 }
58
65 public function isEnabled()
66 {
67 return false;
68 }
69
77 public function setEnable($enable = true)
78 {
79 if ($this->isOptionEnabled() && $enable)
80 return true;
81
82 if (!$this->isOptionEnabled() && !$enable)
83 return true;
84
85 $this->errorCollection[] = new Error(Loc::getMessage('B24NET_NETWORK_IN_NOT_ENABLED'), self::ERROR_NETWORK_IN_NOT_ENABLED);
86
87 return false;
88 }
89
99 public function searchUser($search)
100 {
101 $this->errorCollection[] = new Error(Loc::getMessage('B24NET_NETWORK_IN_NOT_ENABLED'), self::ERROR_NETWORK_IN_NOT_ENABLED);
102 return null;
103 }
104
105 public static function sendMobileApplicationLink($phone, $language_id)
106 {
107 $query = \CBitrix24NetPortalTransport::init();
108 if ($query)
109 {
110 $query->call('profile.send', array(
111 'TYPE' => 'mobile_application_link',
112 'PHONE' => $phone,
113 'LANGUAGE_ID' => $language_id,
114 ));
115 }
116 }
117
123 public static function sendPhoneVerificationCode(string $phone, string $language_id)
124 {
125 if (! self::isPhoneNumberValid($phone))
126 {
127 return ['error' => 'ERROR_CODE_INVALID_NUMBER'];
128 }
129
130 $phone = self::normalizePhoneNumber($phone);
131 $query = \CBitrix24NetPortalTransport::init();
132 if ($query)
133 {
134 global $USER;
135 $userId = $USER instanceof \CUser ? $USER->getId() : 0;
136 return $query->call('portal.verify.send', array(
137 'PHONE' => $phone,
138 'LANGUAGE_ID' => $language_id,
139 'USER_ID' => $userId,
140 ));
141 }
142
143 return false;
144 }
145
152 public static function checkPhoneVerificationCode(string $phone, int $code)
153 {
154 $phone = self::normalizePhoneNumber($phone);
155 $query = \CBitrix24NetPortalTransport::init();
156 if ($query)
157 {
158 global $USER;
159 $userId = $USER instanceof \CUser ? $USER->getId() : 0;
160 return $query->call('portal.verify.check', array(
161 'PHONE' => $phone,
162 'CODE' => $code,
163 'USER_ID' => $userId,
164 ));
165 }
166
167 return false;
168 }
169
176 public static function getPortalVerificationStatus(): bool
177 {
178 $query = \CBitrix24NetPortalTransport::init();
179 if ($query)
180 {
181 $result = $query->call('portal.verify.status');
182 return (bool)$result['result'];
183 }
184 return false;
185 }
186
193 public function getUser($networkId, $lastSearch = '')
194 {
195 $result = $this->getUsers(Array($networkId), $lastSearch);
196
197 return $result && isset($result[$networkId])? $result[$networkId]: null;
198 }
199
206 public function getUsers($networkIds, $lastSearch = '')
207 {
208 if (!$this->isEnabled())
209 {
210 $this->errorCollection[] = new Error(Loc::getMessage('B24NET_NETWORK_IN_NOT_ENABLED'), self::ERROR_NETWORK_IN_NOT_ENABLED);
211 return null;
212 }
213
214 $query = \CBitrix24NetPortalTransport::init();
215 if (!$query)
216 {
217 $this->errorCollection[] = new Error(Loc::getMessage('B24NET_SOCSERV_TRANSPORT_ERROR'), self::ERROR_SOCSERV_TRANSPORT);
218 return null;
219 }
220
221 if (!is_array($networkIds) || empty($networkIds))
222 {
223 $this->errorCollection[] = new Error(Loc::getMessage('B24NET_ERROR_INCORRECT_PARAMS'), self::ERROR_INCORRECT_PARAMS);
224 return null;
225 }
226
227 $queryResult = $query->call('profile.search', array(
228 'ID' => array_values($networkIds),
229 'QUERY' => trim($lastSearch)
230 ));
231
232 $result = null;
233 foreach ($queryResult['result'] as $user)
234 {
235 if (!$user = self::formatUserParam($user))
236 {
237 continue;
238 }
239 $result[$user['NETWORK_ID']] = $user;
240 }
241
242 if (!$result)
243 {
244 $this->errorCollection[] = new Error(Loc::getMessage('B24NET_SEARCH_USER_NOT_FOUND'), self::ERROR_SEARCH_USER_NOT_FOUND);
245 return null;
246 }
247
248 return $result;
249 }
250
257 public function addUserById($networkId, $lastSearch = '')
258 {
259 $userId = $this->getUserId($networkId);
260 if ($userId)
261 {
262 return $userId;
263 }
264
265 $user = $this->getUser($networkId, $lastSearch);
266 if (!$user)
267 {
268 return false;
269 }
270
271 return $this->addUser($user);
272 }
273
280 public function addUsersById($networkIds, $lastSearch = '')
281 {
282 $result = Array();
283
284 $users = $this->getUsersId($networkIds);
285 if ($users)
286 {
287 foreach ($users as $networkId => $userId)
288 {
289 $result[$networkId] = $userId;
290 }
291 $networkIds = array_diff($networkIds, array_keys($users));
292 }
293 if (!empty($networkIds))
294 {
295 $users = $this->getUsers($networkIds, $lastSearch);
296 if (!$users)
297 {
298 return false;
299 }
300
301 foreach ($users as $networkId => $userParams)
302 {
303 $userId = $this->addUser($userParams);
304 if ($userId)
305 {
306 $result[$networkId] = $userId;
307 }
308 }
309 }
310
311 return $result;
312 }
313
322 public function addUser($params)
323 {
324 $password = md5($params['XML_ID'].'|'.$params['CLIENT_DOMAIN'].'|'.rand(1000,9999).'|'.time().'|'.uniqid());
325 $photo = \CFile::MakeFileArray($params['PERSONAL_PHOTO_ORIGINAL']);
326 $groups = Array();
327
328 if(Loader::includeModule('extranet'))
329 {
330 $groups[] = \CExtranet::GetExtranetUserGroupID();
331 }
332
333 $addParams = Array(
334 'LOGIN' => $params['NETWORK_USER_ID'].'@'.$params['CLIENT_DOMAIN'],
335 'NAME' => $params['NAME'],
336 'EMAIL' => $params['EMAIL'],
337 'LAST_NAME' => $params['LAST_NAME'],
338 'SECOND_NAME' => $params['SECOND_NAME'],
339 'PERSONAL_GENDER' => $params['PERSONAL_GENDER'],
340 'PERSONAL_PHOTO' => $photo,
341 'WORK_POSITION' => $params['CLIENT_DOMAIN'],
342 'XML_ID' => $params['XML_ID'],
343 'EXTERNAL_AUTH_ID' => self::EXTERNAL_AUTH_ID,
344 "ACTIVE" => "Y",
345 "PASSWORD" => $password,
346 "CONFIRM_PASSWORD" => $password,
347 "GROUP_ID" => $groups
348 );
349 if (isset($params['EMAIL']))
350 {
351 $addParams['EMAIL'] = $params['EMAIL'];
352 }
353
354 $user = new \CUser;
355 $userId = $user->Add($addParams);
356 if (intval($userId) <= 0)
357 {
358 $this->errorCollection[] = new Error($user->LAST_ERROR, self::ERROR_REGISTER_USER);
359 return false;
360 }
361
362 $event = new Event("socialservices", "OnAfterRegisterUserByNetwork", array($userId, $params['NETWORK_USER_ID'], $params['CLIENT_DOMAIN']));
363 $event->send();
364
365 return $userId;
366 }
367
373 public static function getNetworkId($userId)
374 {
375 $result = \Bitrix\Main\UserTable::getById($userId);
376 $user = $result->fetch();
377 if (!$user || $user['EXTERNAL_AUTH_ID'] != self::EXTERNAL_AUTH_ID)
378 {
379 return null;
380 }
381
382 list($networkId, ) = explode('|', $user['XML_ID']);
383
384 return $networkId;
385 }
386
392 public static function getUserId($networkId)
393 {
394 $result = self::getUsersId(Array($networkId));
395
396 return $result && isset($result[$networkId])? $result[$networkId]: null;
397 }
398
404 public static function getUsersId($networkIds)
405 {
406 if (!is_array($networkIds))
407 return null;
408
409 $searchArray = Array();
410 foreach ($networkIds as $networkId)
411 {
412 $searchArray[] = mb_substr($networkId, 0, 1).intval(mb_substr($networkId, 1))."|%";
413 }
414
415 $result = \Bitrix\Main\UserTable::getList(Array(
416 'select' => Array('ID', 'WORK_PHONE', 'PERSONAL_PHONE', 'PERSONAL_MOBILE', 'UF_PHONE_INNER', 'XML_ID'),
417 'filter' => Array('=%XML_ID' => $searchArray, '=EXTERNAL_AUTH_ID' => self::EXTERNAL_AUTH_ID),
418 'order' => 'ID'
419 ));
420
421 $users = Array();
422 while($user = $result->fetch())
423 {
424 list($networkId, ) = explode("|", $user['XML_ID']);
425 $users[$networkId] = $user['ID'];
426 }
427
428 if (empty($users))
429 {
430 $users = null;
431 }
432
433 return $users;
434 }
435
441 public static function formatUserParam($params)
442 {
443 if (empty($params['NAME']))
444 {
445 if (!empty($params['PUBLIC_NAME']))
446 {
447 $params['NAME'] = $params['PUBLIC_NAME'];
448 }
449 else if (!empty($params['EMAIL']))
450 {
451 $params['NAME'] = $params['EMAIL'];
452 }
453 else
454 {
455 return false;
456 }
457 }
458
459 $result = Array(
460 'LOGIN' => $params['LOGIN'],
461 'EMAIL' => $params['EMAIL'],
462 'NAME' => $params['NAME'],
463 'LAST_NAME' => $params['LAST_NAME'],
464 'SECOND_NAME' => $params['SECOND_NAME'],
465 'PUBLIC_NAME' => $params['PUBLIC_NAME'],
466 'PERSONAL_GENDER' => $params['PERSONAL_GENDER'],
467 'PERSONAL_PHOTO' => $params['PERSONAL_PHOTO_RESIZE'],
468 'PERSONAL_PHOTO_ORIGINAL' => $params['PERSONAL_PHOTO'],
469 'XML_ID' => $params['ID'].'|'.$params['USER_ID'],
470 'NETWORK_ID' => $params['ID'],
471 'NETWORK_USER_ID' => $params['USER_ID'],
472 'REMOTE_USER_ID' => $params['PROFILE_ID'],
473 'CLIENT_DOMAIN' => $params['CLIENT_DOMAIN'],
474 );
475
476 return $result;
477 }
478
482 public static function displayAdminPopup(array $params = array())
483 {
484 global $USER;
485 if(static::getAdminPopupSession()) // duplicated check, just to be clear
486 {
487 $dbRes = UserTable::getList(array(
488 'filter' => array(
489 '=USER_ID' => $USER->GetID(),
490 '=EXTERNAL_AUTH_ID' => \CSocServBitrix24Net::ID
491 )
492 ));
493 if(!$dbRes->fetch())
494 {
495 static::initAdminPopup($params);
496 }
497 else
498 {
499 static::setAdminPopupSession();
500 }
501 }
502 }
503
504 public static function initAdminPopup(array $params = array())
505 {
506 $option = static::getShowOptions();
507 \CJSCore::registerExt("socialservices_admin", array(
508 'js' => "/bitrix/js/socialservices/ss_admin.js",
509 'css' => "/bitrix/js/socialservices/css/ss_admin.css",
510 'rel' => array("ajax", "window"),
511 'lang_additional' => array(
512 "SS_NETWORK_DISPLAY" => $params["SHOW"] ? "Y" : "N",
513 "SS_NETWORK_URL" => static::getAuthUrl("popup", array("admin")),
514 "SS_NETWORK_POPUP_TITLE" => Loc::getMessage('B24NET_POPUP_TITLE'),
515 "SS_NETWORK_POPUP_CONNECT" => Loc::getMessage('B24NET_POPUP_CONNECT'),
516 "SS_NETWORK_POPUP_TEXT" => Loc::getMessage('B24NET_POPUP_TEXT'),
517 "SS_NETWORK_POPUP_DONTSHOW" => Loc::getMessage('B24NET_POPUP_DONTSHOW'),
518 "SS_NETWORK_POPUP_COUNT" => $option["showcount"],
519 )
520 ));
521 \CJSCore::init(array("socialservices_admin"));
522 }
523
524 public static function getAuthUrl($mode = "page", $addScope = null)
525 {
526 if(Option::get("socialservices", "bitrix24net_id", "") != "")
527 {
528 $o = new \CSocServBitrix24Net();
529
530 if($addScope !== null)
531 {
532 $o->addScope($addScope);
533 }
534
535 return $o->getUrl($mode);
536 }
537
538 return false;
539 }
540
541 public static function setAdminPopupSession()
542 {
543 global $USER;
544 $_SESSION[static::ADMIN_SESSION_KEY] = $USER->GetID();
545 }
546
547 public static function clearAdminPopupSession($userId)
548 {
549 global $USER, $CACHE_MANAGER;
550
551 $CACHE_MANAGER->Clean("sso_portal_list_".$userId);
552 if($userId == $USER->GetID())
553 {
554 unset($_SESSION[static::ADMIN_SESSION_KEY]);
555 }
556 }
557
558 protected static function getShowOptions()
559 {
560 return \CUserOptions::GetOption("socialservices", "networkPopup", array("dontshow" => "N", "showcount" => 0));
561 }
562
563 public static function getAdminPopupSession()
564 {
565 global $USER;
566
567 $result = !isset($_SESSION[static::ADMIN_SESSION_KEY]) || $_SESSION[static::ADMIN_SESSION_KEY] !== $USER->GetID();
568 if($result)
569 {
570 $option = static::getShowOptions();
571 $result = $option["dontshow"] !== "Y";
572 if(!$result)
573 {
574 static::setAdminPopupSession();
575 }
576 }
577
578 return $result;
579 }
580
581 public static function setRegisterSettings($settings = array())
582 {
583 if(isset($settings["REGISTER"]))
584 {
585 Option::set("socialservices", "new_user_registration_network", $settings["REGISTER"] == "Y" ? "Y" : "N");
586 }
587
588 if(isset($settings["REGISTER_CONFIRM"]))
589 {
590 Option::set("socialservices", "new_user_registration_confirm", $settings["REGISTER_CONFIRM"] == "Y" ? "Y" : "N");
591 }
592
593 if(isset($settings["REGISTER_WHITELIST"]))
594 {
595 $value = preg_split("/[^a-z0-9\-\.]+/", ToLower($settings["REGISTER_WHITELIST"]));
596 Option::set("socialservices", "new_user_registration_whitelist", serialize($value));
597 }
598
599 if(isset($settings["REGISTER_TEXT"]))
600 {
601 Option::set("socialservices", "new_user_registration_text", trim($settings["REGISTER_TEXT"]));
602 }
603
604 if(isset($settings["REGISTER_SECRET"]))
605 {
606 Option::set("socialservices", "new_user_registration_secret", trim($settings["REGISTER_SECRET"]));
607 }
608
609 static::updateRegisterSettings();
610 }
611
612 public static function getRegisterSettings()
613 {
614 return array(
615 "REGISTER" => Option::get("socialservices", "new_user_registration_network", "N"),
616 "REGISTER_CONFIRM" => Option::get("socialservices", "new_user_registration_confirm", "N"),
617 "REGISTER_WHITELIST" => implode(';', unserialize(Option::get("socialservices", "new_user_registration_whitelist", serialize(array())))),
618 "REGISTER_TEXT" => Option::get("socialservices", "new_user_registration_text", ""),
619 "REGISTER_SECRET" => Option::get("socialservices", "new_user_registration_secret", ""),
620 );
621 }
622
623 protected static function updateRegisterSettings()
624 {
625 $query = \CBitrix24NetPortalTransport::init();
626 if($query)
627 {
628 $options = static::getRegisterSettings();
629
630 $query->call("portal.option.set", array('options' => array(
631 'REGISTER' => $options["REGISTER"] === "Y",
632 'REGISTER_TEXT' => $options["REGISTER_TEXT"],
633 "REGISTER_SECRET" => $options["REGISTER_SECRET"],
634 )));
635 }
636 }
637
638 public static function getLastBroadcastCheck()
639 {
640 return Option::get("socialservices", "network_last_update_check", 0);
641 }
642
643 public static function setLastBroadcastCheck()
644 {
645 Option::set("socialservices", "network_last_update_check", time());
646 }
647
648 public static function checkBroadcastData()
649 {
650 $query = \CBitrix24NetPortalTransport::init();
651 if ($query)
652 {
653 $query->call(
654 "broadcast.check",
655 array(
656 "broadcast_last_check" => static::getLastBroadcastCheck()
657 )
658 );
659 }
660 }
661
662 public static function processBroadcastData($data)
663 {
665
666 foreach(GetModuleEvents("socialservices", "OnNetworkBroadcast", true) as $eventHandler)
667 {
668 ExecuteModuleEventEx($eventHandler, array($data));
669 }
670
671 static::setLastBroadcastCheck();
672 }
673
674 public static function setLastUserStatus($status)
675 {
676 static::$lastUserStatus = $status;
677 }
678
679 public static function getLastUserStatus()
680 {
681 return static::$lastUserStatus;
682 }
683
684
685 private static function normalizePhoneNumber(string $number, $defaultCountry = '')
686 {
687 $phoneNumber = \Bitrix\Main\PhoneNumber\Parser::getInstance()->parse($number, $defaultCountry);
688 return $phoneNumber->format(\Bitrix\Main\PhoneNumber\Format::E164);
689 }
690
695 private static function isPhoneNumberValid(string $number): bool
696 {
697 $phoneNumber = \Bitrix\Main\PhoneNumber\Parser::getInstance()->parse($number);
698 return $phoneNumber->isValid();
699 }
700}
static loadMessages($file)
Definition loc.php:64
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
addUserById($networkId, $lastSearch='')
Definition network.php:257
static getUsersId($networkIds)
Definition network.php:404
static displayAdminPopup(array $params=array())
Definition network.php:482
static checkPhoneVerificationCode(string $phone, int $code)
Definition network.php:152
addUsersById($networkIds, $lastSearch='')
Definition network.php:280
static getAuthUrl($mode="page", $addScope=null)
Definition network.php:524
static sendMobileApplicationLink($phone, $language_id)
Definition network.php:105
static getUserId($networkId)
Definition network.php:392
static formatUserParam($params)
Definition network.php:441
static initAdminPopup(array $params=array())
Definition network.php:504
getUsers($networkIds, $lastSearch='')
Definition network.php:206
static processBroadcastData($data)
Definition network.php:662
static setRegisterSettings($settings=array())
Definition network.php:581
static clearAdminPopupSession($userId)
Definition network.php:547
static getNetworkId($userId)
Definition network.php:373
getUser($networkId, $lastSearch='')
Definition network.php:193
static setLastUserStatus($status)
Definition network.php:674
static sendPhoneVerificationCode(string $phone, string $language_id)
Definition network.php:123