Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
user.php
1<?php
2namespace Bitrix\Rest\Api;
3
4use Bitrix\Intranet\Invitation;
13
14class User extends \IRestService
15{
16 public const SCOPE_USER = 'user';
17 public const SCOPE_USER_BASIC = 'user_basic';
18 public const SCOPE_USER_BRIEF = 'user_brief';
19
20 private const ALLOWED_USER_NAME_FIELDS = [
21 'ID',
22 'XML_ID',
23 'ACTIVE',
24 'NAME',
25 'LAST_NAME',
26 'SECOND_NAME',
27 'TITLE',
28 'IS_ONLINE',
29 'TIME_ZONE',
30 'TIME_ZONE_OFFSET',
31 'TIME_ZONE_OFFSET',
32 'TIMESTAMP_X',
33 'DATE_REGISTER',
34 'PERSONAL_PROFESSION',
35 'PERSONAL_GENDER',
36 'PERSONAL_BIRTHDAY',
37 'PERSONAL_PHOTO',
38 'PERSONAL_CITY',
39 'PERSONAL_STATE',
40 'PERSONAL_COUNTRY',
41 'WORK_POSITION',
42 'WORK_CITY',
43 'WORK_STATE',
44 'WORK_COUNTRY',
45 'LAST_ACTIVITY_DATE',
46 'UF_EMPLOYMENT_DATE',
47 'UF_TIMEMAN',
48 'UF_SKILLS',
49 'UF_INTERESTS',
50 'UF_DEPARTMENT',
51 'UF_PHONE_INNER',
52 ];
53
54 private const ALLOWED_USER_BASIC_FIELDS = [
55 'ID',
56 'XML_ID',
57 'ACTIVE',
58 'NAME',
59 'LAST_NAME',
60 'SECOND_NAME',
61 'TITLE',
62 'EMAIL',
63 'PERSONAL_PHONE',
64 'WORK_PHONE',
65 'WORK_POSITION',
66 'WORK_COMPANY',
67 'IS_ONLINE',
68 'TIME_ZONE',
69 'TIMESTAMP_X',
70 'TIME_ZONE_OFFSET',
71 'DATE_REGISTER',
72 'LAST_ACTIVITY_DATE',
73 'PERSONAL_PROFESSION',
74 'PERSONAL_GENDER',
75 'PERSONAL_BIRTHDAY',
76 'PERSONAL_PHOTO',
77 'PERSONAL_PHOTO',
78 'PERSONAL_PHONE',
79 'PERSONAL_FAX',
80 'PERSONAL_MOBILE',
81 'PERSONAL_PAGER',
82 'PERSONAL_STREET',
83 'PERSONAL_MAILBOX',
84 'PERSONAL_CITY',
85 'PERSONAL_STATE',
86 'PERSONAL_ZIP',
87 'PERSONAL_COUNTRY',
88 'PERSONAL_NOTES',
89 'WORK_COMPANY',
90 'WORK_DEPARTMENT',
91 'WORK_POSITION',
92 'WORK_WWW',
93 'WORK_PHONE',
94 'WORK_FAX',
95 'WORK_PAGER',
96 'WORK_STREET',
97 'WORK_MAILBOX',
98 'WORK_CITY',
99 'WORK_STATE',
100 'WORK_ZIP',
101 'WORK_COUNTRY',
102 'WORK_PROFILE',
103 'WORK_LOGO',
104 'WORK_NOTES',
105 'UF_DEPARTMENT',
106 'UF_DISTRICT',
107 'UF_SKYPE',
108 'UF_SKYPE_LINK',
109 'UF_ZOOM',
110 'UF_TWITTER',
111 'UF_FACEBOOK',
112 'UF_LINKEDIN',
113 'UF_XING',
114 'UF_WEB_SITES',
115 'UF_PHONE_INNER',
116 'UF_EMPLOYMENT_DATE',
117 'UF_TIMEMAN',
118 'UF_SKILLS',
119 'UF_INTERESTS',
120 ];
121
122 private static $entityUser = 'USER';
123 private static $nameFieldFullPrefix = 'UF_USR_';
124 private static $userUserFieldList;
125
126 protected static $allowedUserFields = array(
127 'ID',
128 'XML_ID',
129 'ACTIVE',
130 'NAME',
131 'LAST_NAME',
132 'SECOND_NAME',
133 'TITLE',
134 'EMAIL',
135 'LAST_LOGIN',
136 'DATE_REGISTER',
137 'TIME_ZONE',
138 'IS_ONLINE',
139 'TIME_ZONE_OFFSET',
140 'TIMESTAMP_X',
141 'LAST_ACTIVITY_DATE',
142 'PERSONAL_GENDER',
143 'PERSONAL_PROFESSION',
144 'PERSONAL_WWW',
145 'PERSONAL_BIRTHDAY',
146 'PERSONAL_PHOTO',
147 'PERSONAL_ICQ',
148 'PERSONAL_PHONE',
149 'PERSONAL_FAX',
150 'PERSONAL_MOBILE',
151 'PERSONAL_PAGER',
152 'PERSONAL_STREET',
153 'PERSONAL_CITY',
154 'PERSONAL_STATE',
155 'PERSONAL_ZIP',
156 'PERSONAL_COUNTRY',
157 'PERSONAL_MAILBOX',
158 'PERSONAL_NOTES',
159 'PERSONAL_PROFESSION',
160 'PERSONAL_GENDER',
161 'PERSONAL_BIRTHDAY',
162
163 'WORK_PHONE',
164 'WORK_COMPANY',
165 'WORK_POSITION',
166 'WORK_DEPARTMENT',
167 'WORK_WWW',
168 'WORK_FAX',
169 'WORK_PAGER',
170 'WORK_STREET',
171 'WORK_MAILBOX',
172 'WORK_CITY',
173 'WORK_STATE',
174 'WORK_ZIP',
175 'WORK_COUNTRY',
176 'WORK_PROFILE',
177 'WORK_LOGO',
178 'WORK_NOTES',
179
180 'UF_SKYPE_LINK',
181 'UF_ZOOM',
182 'UF_EMPLOYMENT_DATE',
183 'UF_TIMEMAN',
184 'UF_DEPARTMENT',
185 'UF_INTERESTS',
186 'UF_SKILLS',
187 'UF_WEB_SITES',
188 'UF_XING',
189 'UF_LINKEDIN',
190 'UF_FACEBOOK',
191 'UF_TWITTER',
192 'UF_SKYPE',
193 'UF_DISTRICT',
194 'UF_PHONE_INNER',
195 );
196
197 protected static $holdEditFields = [
198 "LAST_LOGIN",
199 "DATE_REGISTER",
200 "IS_ONLINE",
201 "TIME_ZONE_OFFSET",
202 ];
203
204 public static function getDefaultAllowedUserFields()
205 {
206 $result = static::$allowedUserFields;
207
208 if (Loader::includeModule('intranet'))
209 {
210 $result[] = 'USER_TYPE';
211 }
212
213 return $result;
214 }
215
216 private static function isMainScope(\CRestServer $server)
217 {
218 return in_array(static::SCOPE_USER, $server->getAuthScope());
219 }
220
221 private static function getErrorScope()
222 {
223 return [
224 'error' => 'insufficient_scope',
225 'error_description' => 'The request requires higher privileges than provided by the access token',
226 ];
227 }
228
229 private static function getAllowedUserFields($scopeList): array
230 {
231 $result = [];
232 if (in_array(static::SCOPE_USER, $scopeList))
233 {
234 $result = static::getDefaultAllowedUserFields();
235 }
236 else
237 {
238 if (in_array(static::SCOPE_USER_BASIC, $scopeList))
239 {
240 $result = static::ALLOWED_USER_BASIC_FIELDS;
241 }
242 elseif (in_array(static::SCOPE_USER_BRIEF, $scopeList))
243 {
244 $result = static::ALLOWED_USER_NAME_FIELDS;
245 }
246
247 if (Loader::includeModule('intranet'))
248 {
249 $result[] = 'USER_TYPE';
250 }
251
252 if (in_array(UserField::SCOPE_USER_USERFIELD, $scopeList))
253 {
254 $result = array_merge($result, static::getUserFields());
255 }
256 }
257
258 return $result;
259 }
260
261 public static function unsetDefaultAllowedUserField($key)
262 {
263 unset(static::$allowedUserFields[$key]);
264 }
265
266 public static function setDefaultAllowedUserField($field)
267 {
268 static::$allowedUserFields[] = $field;
269 }
270
271 public static function onRestServiceBuildDescription()
272 {
273 $result = array(
274 \CRestUtil::GLOBAL_SCOPE => array(
275 'user.admin' => array(__CLASS__, 'isAdmin'),
276 'user.access' => array(__CLASS__, 'hasAccess'),
277 'access.name' => array(__CLASS__, 'getAccess'),
278 )
279 );
280
282 {
283 $result[static::SCOPE_USER] = array(
284 'user.fields' => array(__CLASS__, 'getFields'),
285 'user.current' => array(__CLASS__, 'userCurrent'),
286 'user.get' => array(__CLASS__, 'userGet'),
287 'user.search' => array(__CLASS__, 'userGet'),
288 'user.add' => array(__CLASS__, 'userAdd'),
289 'user.update' => array(__CLASS__, 'userUpdate'),
290 'user.online' => array(__CLASS__, 'userOnline'),
291 'user.counters' => array(__CLASS__, 'userCounters'),
292 \CRestUtil::EVENTS => array(
293 'OnUserAdd' => array('main', 'OnUserInitialize', array(__CLASS__, 'onUserInitialize')),
294 ),
295 );
296 $result[static::SCOPE_USER_BRIEF] = [
297 'user.fields' => array(__CLASS__, 'getFields'),
298 'user.current' => array(__CLASS__, 'userCurrent'),
299 'user.get' => array(__CLASS__, 'userGet'),
300 'user.search' => array(__CLASS__, 'userGet'),
301 'user.online' => array(__CLASS__, 'userOnline'),
302 'user.counters' => array(__CLASS__, 'userCounters'),
303 \CRestUtil::EVENTS => array(
304 'OnUserAdd' => array('main', 'OnUserInitialize', array(__CLASS__, 'onUserInitialize')),
305 ),
306 ];
307 $result[static::SCOPE_USER_BASIC] = [
308 'user.fields' => array(__CLASS__, 'getFields'),
309 'user.current' => array(__CLASS__, 'userCurrent'),
310 'user.get' => array(__CLASS__, 'userGet'),
311 'user.search' => array(__CLASS__, 'userGet'),
312 'user.online' => array(__CLASS__, 'userOnline'),
313 'user.counters' => array(__CLASS__, 'userCounters'),
314 \CRestUtil::EVENTS => array(
315 'OnUserAdd' => array('main', 'OnUserInitialize', array(__CLASS__, 'onUserInitialize')),
316 ),
317 ];
319 'user.userfield.add' => [UserField::class, 'addRest'],
320 'user.userfield.update' => [UserField::class, 'updateRest'],
321 'user.userfield.delete' => [UserField::class, 'deleteRest'],
322 'user.userfield.list' => [UserField::class, 'getListRest'],
323 'user.userfield.file.get' => [__CLASS__, 'getFile'],
324 ];
325 }
326
327 return $result;
328 }
329
330 private static function getUserFields()
331 {
332 if (is_null(static::$userUserFieldList))
333 {
334 static::$userUserFieldList = [];
335 global $USER_FIELD_MANAGER;
336
337 $fields = $USER_FIELD_MANAGER->GetUserFields("USER");
338
339 foreach ($fields as $code => $field)
340 {
341 if (mb_strpos($code, static::$nameFieldFullPrefix) === 0)
342 {
343 static::$userUserFieldList[] = $code;
344 }
345 }
346 }
347
348 return static::$userUserFieldList;
349 }
350
351 protected static function checkAllowedFields()
352 {
353 global $USER_FIELD_MANAGER;
354
355 $fields = $USER_FIELD_MANAGER->GetUserFields("USER");
356
357 foreach(static::getDefaultAllowedUserFields() as $key => $field)
358 {
359 if(mb_substr($field, 0, 3) === 'UF_' && !array_key_exists($field, $fields))
360 {
361 static::unsetDefaultAllowedUserField($key);
362 }
363 }
364
365 foreach ($fields as $code => $field)
366 {
367 if (mb_strpos($code, static::$nameFieldFullPrefix) === 0)
368 {
369 static::setDefaultAllowedUserField($code);
370 }
371 }
372 }
373
374 public static function onUserInitialize($arParams, $arHandler)
375 {
376 $ID = $arParams[0];
377
378 $dbRes = \CUser::GetByID($ID);
379 $arUser = $dbRes->Fetch();
380
381 if(in_array($arUser['EXTERNAL_AUTH_ID'], UserTable::getExternalUserTypes()))
382 {
383 throw new RestException('Unnecessary event call for this user type');
384 }
385
386 $allowedFields = null;
387 if ($arHandler['APP_ID'] > 0)
388 {
389 $app = AppTable::getByClientId($arHandler['APP_CODE']);
390 if ($app['SCOPE'])
391 {
392 $scope = explode(',', $app['SCOPE']);
393 $allowedFields = static::getAllowedUserFields($scope);
394 }
395 }
396
397 $arRes = self::getUserData($arUser, $allowedFields);
398 if($arUser['PERSONAL_PHOTO'] > 0)
399 {
400 $arRes['PERSONAL_PHOTO'] = \CRestUtil::GetFile($arUser["PERSONAL_PHOTO"]);
401 }
402
403 return $arRes;
404 }
405
406 public static function isAdmin()
407 {
408 return \CRestUtil::isAdmin();
409 }
410
411 public static function hasAccess($params)
412 {
413 global $USER;
414
415 $params = array_change_key_case($params, CASE_UPPER);
416
417 if(!is_array($params['ACCESS']))
418 {
419 $params['ACCESS'] = array($params['ACCESS']);
420 }
421
422 return self::isAdmin() || $USER->canAccess($params['ACCESS']);
423 }
424
425 public static function getAccess($params)
426 {
427 $params = array_change_key_case($params, CASE_UPPER);
428
429 if(!is_array($params['ACCESS']) || count($params['ACCESS']) <= 0)
430 {
431 return false;
432 }
433 else
434 {
435 $ob = new \CAccess();
436 $res = $ob->getNames($params['ACCESS']);
437 foreach($res as $key => $value)
438 {
439 if(!in_array($key, $params['ACCESS']))
440 unset($res[$key]);
441 }
442
443 return $res;
444 }
445 }
446
447 public static function getFields($query = [], $nav = 0, \CRestServer $server = null)
448 {
449 global $USER_FIELD_MANAGER;
450
451 static::checkAllowedFields();
452
453 $res = array();
454
455 $langMessages = array_merge(
456 IncludeModuleLangFile('/bitrix/modules/main/admin/user_edit.php', false, true),
457 IncludeModuleLangFile('/bitrix/modules/main/admin/user_admin.php', false, true)
458 );
459 $fieldsList = $USER_FIELD_MANAGER->getUserFields('USER', 0, LANGUAGE_ID);
460 if (!is_null($server))
461 {
462 $allowedFields = static::getAllowedUserFields($server->getAuthScope());
463 }
464 else
465 {
466 $allowedFields = static::getDefaultAllowedUserFields();
467 }
468 foreach ($allowedFields as $key)
469 {
470 if(mb_substr($key, 0, 3) != 'UF_')
471 {
472 $lkey = isset($langMessages[$key]) ? $key : str_replace('PERSONAL_', 'USER_', $key);
473 $res[$key] = isset($langMessages[$lkey]) ? $langMessages[$lkey] : $key;
474 if(mb_substr($res[$key], -1) == ':')
475 {
476 $res[$key] = mb_substr($res[$key], 0, -1);
477 }
478 }
479 else
480 {
481 $res[$key] = $fieldsList[$key]['EDIT_FORM_LABEL'];
482 }
483 }
484
485 return $res;
486 }
487
488 public static function userCurrent($query, $n, \CRestServer $server)
489 {
490 global $USER;
491
492 static::checkAllowedFields();
493
494 $dbRes = \CUser::getByID($USER->getID());
495 $userFields = $dbRes->fetch();
496
497 $allowedFields = static::getAllowedUserFields($server->getAuthScope());
498 $result = self::getUserData($userFields, $allowedFields);
499 if($userFields['PERSONAL_PHOTO'] > 0)
500 {
501 $result['PERSONAL_PHOTO'] = \CRestUtil::GetFile($userFields["PERSONAL_PHOTO"]);
502 }
503
504 $server->setSecurityState(array(
505 "ID" => $result['ID'],
506 "EMAIL" => $result['EMAIL'] ?? '',
507 "NAME" => $result['NAME'],
508 ));
509
510 return $result;
511 }
512
513 public static function userGet($query, $nav = 0, \CRestServer $server)
514 {
515 global $USER;
516
517 static::checkAllowedFields();
518
519 static $moduleAdminList = false;
520
521 $query = array_change_key_case($query, CASE_UPPER);
522
523 $sort = $query['SORT'];
524 $order = $query['ORDER'];
525 $adminMode = false;
526
527 //getting resize preset before user data preparing
528 $resizePresets = [
529 "small"=>["width"=>150, "height" => 150],
530 "medium"=>["width"=>300, "height" => 300],
531 "large"=>["width"=>1000, "height" => 1000],
532 ];
533
534 $presetName = $query["IMAGE_RESIZE"];
535 $resize = ($presetName && $resizePresets[$presetName]
536 ? $resizePresets[$presetName]
537 : false);
538
539 if (isset($query['ADMIN_MODE']) && $query['ADMIN_MODE'])
540 {
541 if ($moduleAdminList === false && Loader::includeModule('socialnetwork'))
542 {
543 $moduleAdminList = \Bitrix\Socialnetwork\User::getModuleAdminList(array(SITE_ID, false));
544 }
545
546 if (is_array($moduleAdminList))
547 {
548 $adminMode = (array_key_exists($USER->getID(), $moduleAdminList));
549 }
550 }
551
552 $allowedUserFields = static::getAllowedUserFields($server->getAuthScope());
553 $allowedUserFields[] = 'IS_ONLINE';
554 $allowedUserFields[] = 'HAS_DEPARTAMENT';
555 $allowedUserFields[] = 'NAME_SEARCH';
556 $allowedUserFields[] = 'EXTERNAL_AUTH_ID';
557 if ($server->getMethod() == "user.search")
558 {
559 $allowedUserFields[] = 'FIND';
560 $allowedUserFields[] = 'UF_DEPARTMENT_NAME';
561 $allowedUserFields[] = 'CONFIRM_CODE';
562 }
563
564 if (isset($query['FILTER']) && is_array($query['FILTER']))
565 {
570 $query = array_change_key_case($query['FILTER'], CASE_UPPER);
571 }
572
573 $filter = self::prepareUserFilter(
574 $query,
576 [
577 'HAS_DEPARTAMENT',
578 'NAME_SEARCH',
579 'FIND'
580 ]
581 );
582
583 if (isset($filter['NAME_SEARCH']) || isset($filter['FIND']))
584 {
585 $nameSearch = isset($filter['NAME_SEARCH'])? $filter['NAME_SEARCH']: $filter['FIND'];
586 unset($filter['NAME_SEARCH']);
587 unset($filter['FIND']);
588
589 $filter = array_merge($filter, \Bitrix\Main\UserUtils::getUserSearchFilter(Array(
590 'FIND' => $nameSearch
591 )));
592 }
593 else if ($server->getMethod() == "user.search")
594 {
595 $previousFilter = $filter;
596 unset($filter['NAME']);
597 unset($filter['LAST_NAME']);
598 unset($filter['SECOND_NAME']);
599 unset($filter['WORK_POSITION']);
600 unset($filter['UF_DEPARTMENT_NAME']);
601
602 $filter = array_merge($filter, \Bitrix\Main\UserUtils::getUserSearchFilter(Array(
603 'NAME' => $previousFilter['NAME'],
604 'LAST_NAME' => $previousFilter['LAST_NAME'],
605 'SECOND_NAME' => $previousFilter['SECOND_NAME'],
606 'WORK_POSITION' => $previousFilter['WORK_POSITION'],
607 'UF_DEPARTMENT_NAME' => $previousFilter['UF_DEPARTMENT_NAME'],
608 )));
609 }
610
611 if (
612 !$adminMode
613 && Loader::includeModule("extranet")
614 )
615 {
616 $filteredUserIDs = \CExtranet::getMyGroupsUsersSimple(\CExtranet::getExtranetSiteID());
617 $filteredUserIDs[] = $USER->getID();
618
619 if (\CExtranet::isIntranetUser())
620 {
621 if (
622 !isset($filter["ID"])
623 || !Loader::includeModule('socialnetwork')
624 || !\CSocNetUser::IsCurrentUserModuleAdmin(\CSite::getDefSite(), false)
625 )
626 {
627 $filter[] = array(
628 'LOGIC' => 'OR',
629 '!UF_DEPARTMENT' => false,
630 'ID' => $filteredUserIDs
631 );
632 }
633 }
634 else
635 {
636 $filter["ID"] = (isset($filter["ID"]) ? array_intersect((is_array($filter["ID"]) ? $filter["ID"] : array($filter["ID"])), $filteredUserIDs) : $filteredUserIDs);
637 }
638 }
639
640 if (array_key_exists('HAS_DEPARTAMENT', $filter))
641 {
642 if ($filter['HAS_DEPARTAMENT'] === 'Y')
643 {
644 $filter[] = [
645 'LOGIC' => 'AND',
646 '!UF_DEPARTMENT' => false,
647 ];
648 }
649
650 unset($filter['HAS_DEPARTAMENT']);
651 }
652
653 $filter['=IS_REAL_USER'] = 'Y';
654
655 $getListClassName = '\Bitrix\Main\UserTable';
656 if (Loader::includeModule('intranet'))
657 {
658 $getListClassName = '\Bitrix\Intranet\UserTable';
659 }
660 $getListMethodName = 'getList';
661
662 $navParams = self::getNavData($nav, true);
663
664 $querySort = [];
665 if ($sort && $order)
666 {
667 $querySort[$sort] = $order;
668 }
669 $allowedFields = static::getAllowedUserFields($server->getAuthScope());
670
671 $dbRes = $getListClassName::$getListMethodName(
672 [
673 'order' => $querySort,
674 'filter' => $filter,
675 'select' => $allowedFields,
676 'limit' => $navParams['limit'],
677 'offset' => $navParams['offset'],
678 'data_doubling' => false,
679 'count_total' => $nav !== -1,
680 ]
681 );
682
683 $result = [];
684 $files = [];
685
686 while ($userInfo = $dbRes->fetch())
687 {
688 $result[] = self::getUserData($userInfo, $allowedFields);
689
690 if ($userInfo['PERSONAL_PHOTO'] > 0)
691 {
692 $files[] = $userInfo['PERSONAL_PHOTO'];
693 }
694 }
695
696 if (count($files) > 0)
697 {
698 $files = \CRestUtil::getFile($files, $resize);
699
700 foreach ($result as $key => $userInfo)
701 {
702 if ($userInfo['PERSONAL_PHOTO'] > 0)
703 {
704 $result[$key]['PERSONAL_PHOTO'] = $files[$userInfo['PERSONAL_PHOTO']];
705 }
706 }
707 }
708
709 if ($result)
710 {
711 $count = 0;
712 if ($nav !== -1)
713 {
714 try
715 {
716 $count = $dbRes->getCount();
717 }
718 catch (ObjectPropertyException $exception)
719 {
720 }
721 }
722
723 return self::setNavData(
724 $result,
725 [
726 'count' => $count,
727 'offset' => $navParams['offset']
728 ]
729 );
730 }
731
732 return $result;
733 }
734
735 public static function userOnline()
736 {
737 $dbRes = UserTable::getList(array(
738 'filter' => array(
739 'IS_ONLINE' => 'Y',
740 ),
741 'select' => array('ID')
742 ));
743
744 $onlineUsers = array();
745 while($userData = $dbRes->fetch())
746 {
747 $onlineUsers[] = $userData['ID'];
748 }
749
750 return $onlineUsers;
751 }
752
753 public static function userCounters($arParams)
754 {
755 $arParams = array_change_key_case($arParams, CASE_UPPER);
756
757 global $USER;
758
759 $counters = \CUserCounter::GetAllValues($USER->getID());
760
761 if (!isset($arParams['SKIP_LIVEFEED_GROUP']) || $arParams['SKIP_LIVEFEED_GROUP'] != 'Y')
762 {
763 $counters = \CUserCounter::getGroupedCounters($counters);
764 }
765
766 return $counters;
767 }
768
769 public static function userAdd($userFields, $nav = 0, \CRestServer $server = null)
770 {
771 if (!is_null($server) && !static::isMainScope($server))
772 {
773 return static::getErrorScope();
774 }
775
776 global $APPLICATION, $USER;
777
778 static::checkAllowedFields();
779
780 $bB24 = ModuleManager::isModuleInstalled('bitrix24');
781 $res = false;
782
783 if(
784 (
785 $bB24 && $USER->canDoOperation('bitrix24_invite')
786 || $USER->canDoOperation('edit_all_users')
787 )
788 && Loader::includeModule('intranet'))
789 {
790 $userFields = array_change_key_case($userFields, CASE_UPPER);
791
792 $bExtranet = false;
793
794 if (
795 isset($userFields["EXTRANET"])
796 && $userFields["EXTRANET"] == "Y"
797 )
798 {
799 if (IsModuleInstalled('extranet'))
800 {
801 $bExtranet = true;
802 $userFields["UF_DEPARTMENT"] = array();
803
804 if (!empty($userFields["SONET_GROUP_ID"]))
805 {
806 $sonetGroupId = $userFields["SONET_GROUP_ID"];
807 if (!is_array($sonetGroupId))
808 {
809 $sonetGroupId = array($sonetGroupId);
810 }
811
812 unset($userFields["SONET_GROUP_ID"]);
813 }
814 else
815 {
816 throw new \Exception('no_sonet_group_for_extranet');
817 }
818 }
819
820 unset($userFields["EXTRANET"]);
821 }
822
823 $inviteFields = self::prepareSaveData($userFields);
824
825 $userFields["EMAIL"] = trim($userFields["EMAIL"]);
826 if(check_email($userFields["EMAIL"]))
827 {
828 $siteId = self::getDefaultSite();
829
830 if(\CIntranetInviteDialog::checkUsersCount(1))
831 {
832 if (
833 IsModuleInstalled('extranet')
834 && empty($inviteFields["UF_DEPARTMENT"])
835 && !$bExtranet
836 )
837 {
838 throw new \Exception('no_extranet_field');
839 }
840
841 $inviteFields['EMAIL'] = $userFields["EMAIL"];
842 $inviteFields['ACTIVE'] = (isset($inviteFields['ACTIVE'])? $inviteFields['ACTIVE'] : 'Y');
843 $inviteFields['GROUP_ID'] = \CIntranetInviteDialog::getUserGroups($siteId, $bExtranet);
844 $inviteFields["CONFIRM_CODE"] = randString(8);
845
846 $ID = \CIntranetInviteDialog::RegisterUser($inviteFields);
847 if(is_array($ID))
848 {
849 throw new \Exception(implode("\n", $ID));
850 }
851 elseif($ID > 0)
852 {
853 $obUser = new \CUser;
854 if(!$obUser->update($ID, $inviteFields))
855 {
856 throw new \Exception($obUser->LAST_ERROR);
857 }
858
859 $inviteFields['ID'] = $ID;
860
861 Invitation::add([
862 'USER_ID' => $ID,
863 'TYPE' => Invitation::TYPE_EMAIL
864 ]);
865
866 \CIntranetInviteDialog::InviteUser(
867 $inviteFields,
868 (isset($userFields["MESSAGE_TEXT"])) ? htmlspecialcharsbx($userFields["MESSAGE_TEXT"]) : GetMessage("BX24_INVITE_DIALOG_INVITE_MESSAGE_TEXT_1")
869 );
870
871 if (
872 isset($sonetGroupId)
873 && is_array($sonetGroupId)
874 && \CModule::IncludeModule('socialnetwork')
875 )
876 {
877 foreach($sonetGroupId as $groupId)
878 {
879 if (!\CSocNetUserToGroup::SendRequestToJoinGroup($USER->GetID(), $ID, $groupId, "", false))
880 {
881 if ($e = $APPLICATION->GetException())
882 {
883 throw new \Exception($e->GetString());
884 }
885 }
886 }
887 }
888
889 $res = $ID;
890 }
891 }
892 else
893 {
894 throw new \Exception('user_count_exceeded');
895 }
896 }
897 else
898 {
899 throw new \Exception('wrong_email');
900 }
901 }
902 else
903 {
904 throw new \Exception('access_denied');
905 }
906
907 return $res;
908 }
909
910 public static function userUpdate($userFields, $nav = 0, \CRestServer $server = null)
911 {
912 if (!is_null($server) && !static::isMainScope($server))
913 {
914 return static::getErrorScope();
915 }
916
917 global $USER;
918
919 static::checkAllowedFields();
920
921 $bB24 = ModuleManager::isModuleInstalled('bitrix24');
922
923 $bAdmin = ($bB24 && $USER->canDoOperation('bitrix24_invite'))
924 || $USER->canDoOperation('edit_all_users');
925
926 $userFields = array_change_key_case($userFields, CASE_UPPER);
927
928 if($userFields['ID'] > 0)
929 {
930 if($bAdmin || ($USER->getID() == $userFields['ID'] && $USER->CanDoOperation('edit_own_profile')))
931 {
932 $updateFields = self::prepareSaveData($userFields);
933
934 // security
935 if(!$bAdmin)
936 {
937 unset($updateFields['ACTIVE']);
938 unset($updateFields['UF_DEPARTMENT']);
939 }
940 // \security
941
942 $obUser = new \CUser;
943 if(!$obUser->update($userFields['ID'], $updateFields))
944 {
945 throw new NonLoggedExceptionDecorator(new \Exception($obUser->LAST_ERROR));
946 }
947 else
948 {
949 $res = true;
950 }
951 }
952 else
953 {
954 throw new NonLoggedExceptionDecorator(new \Exception('access_denied'));
955 }
956 }
957 else
958 {
959 throw new NonLoggedExceptionDecorator(new \Exception('access_denied'));
960 }
961
962 return $res;
963 }
964
965 private static function prepareUserField($params, $data)
966 {
967 $result = $data;
968 switch ($params['USER_TYPE_ID'])
969 {
970 case 'datetime':
971 $result = \CRestUtil::unConvertDateTime($data);
972 break;
973 case 'date':
974 $result = \CRestUtil::unConvertDate($data);
975 break;
976 case 'file':
977 if (is_array($data))
978 {
979 if ($params['MULTIPLE'] === 'N')
980 {
981 if (!empty($data['fileData']))
982 {
983 $result = \CRestUtil::saveFile($data['fileData']);
984 $result['old_id'] = $params['VALUE'];
985 }
986 $id = isset($data['id']) ? (int)$data['id'] : 0;
987 $remove = isset($data['remove']) && is_string($data['remove']) && mb_strtoupper($data['remove']) === 'Y';
988 if ($remove && $id > 0)
989 {
990 $result = [
991 'old_id' => $id,
992 'del' => 'Y'
993 ];
994 }
995 }
996 else
997 {
998 if ($params['VALUE'])
999 {
1000 $result = array_merge($result, $params['VALUE']);
1001 }
1002
1003 foreach ($result as $key => $value)
1004 {
1005 if ($value['fileData'])
1006 {
1007 $result[$key] = \CRestUtil::saveFile($value['fileData']);
1008 }
1009 else
1010 {
1011 $id = isset($value['id']) ? (int)$value['id'] : 0;
1012 $remove = isset($value['remove']) && is_string($value['remove']) && mb_strtoupper($value['remove']) === 'Y';
1013 if ($remove && $id > 0)
1014 {
1015 $result[$key] = [
1016 'old_id' => $id,
1017 'del' => 'Y'
1018 ];
1019 }
1020 elseif ($value > 0)
1021 {
1022 $result[$key] = [
1023 'old_id' => $value,
1024 'error' => 'Y'
1025 ];
1026 }
1027 }
1028 }
1029 }
1030 }
1031 break;
1032 }
1033 return $result;
1034 }
1035
1042 protected static function prepareUserData($userData, $allowedUserFields = null)
1043 {
1044 $user = array();
1045
1046 if (!$allowedUserFields)
1047 {
1048 $allowedUserFields = static::getDefaultAllowedUserFields();
1049 }
1050 foreach($userData as $key => $value)
1051 {
1052 if(in_array($key, $allowedUserFields, true))
1053 {
1054 $user[$key] = static::prepareUserValue($key, $value);
1055 }
1056 }
1057
1058 return $user;
1059 }
1060
1061 private static function prepareUserValue($code, $value)
1062 {
1063 switch ($code):
1064 case 'ID':
1065 if (is_array($value) && !empty($value))
1066 {
1067 $value = array_map('intval', $value);
1068 }
1069 else
1070 {
1071 $value = (int)($value);
1072 }
1073 break;
1074 case 'ACTIVE':
1075 case 'IS_ONLINE':
1076 $value = ($value && $value !== 'N')? 'Y' : 'N';
1077 break;
1078 case 'AUTO_TIME_ZONE':
1079 $value = $value === 'Y'? 'Y' : 'N';
1080 break;
1081 case 'PERSONAL_BIRTHDAY':
1082 $value = \CRestUtil::unConvertDate($value);
1083 break;
1084 case 'PERSONAL_PHOTO':
1085
1086 $value = \CRestUtil::saveFile($value);
1087
1088 if(!$value)
1089 {
1090 $value = [
1091 'del' => 'Y',
1092 ];
1093 }
1094 break;
1095 case 'UF_DEPARTMENT':
1096 if(!is_array($value) && !empty($value))
1097 {
1098 $value = [
1099 $value
1100 ];
1101 }
1102 break;
1103 case 'CONFIRM_CODE':
1104 if($value === '0')
1105 {
1106 $value = false;
1107 }
1108 break;
1109 endswitch;
1110
1111 return $value;
1112 }
1113
1114 private static function prepareUserFilter($query, $allowedUserFields = null, $clearFilterType = []): array
1115 {
1116 $filter = [];
1117
1118 if (!$allowedUserFields)
1119 {
1120 $allowedUserFields = static::getDefaultAllowedUserFields();
1121 }
1122
1123 foreach ($query as $code => $value)
1124 {
1125 $filterType = '';
1126 $matches = [];
1127 if (preg_match('/^([\W]{1,2})(.+)/', $code, $matches) && $matches[2])
1128 {
1129 $filterType = $matches[1];
1130 $code = $matches[2];
1131 }
1132
1133 if (in_array($code, $allowedUserFields, true))
1134 {
1135 if ($filterType !== '' && in_array($code, $clearFilterType, true))
1136 {
1137 $filterType = '';
1138 }
1139 elseif ($filterType === '' && in_array($code, ['USER_TYPE', 'ACTIVE'], true))
1140 {
1141 $filterType = '=';
1142 }
1143
1144 $filter[$filterType . $code] = static::prepareUserValue($code, $value);
1145 }
1146 }
1147
1148 return $filter;
1149 }
1150
1151 protected static function prepareSaveData($userData, $allowedUserFields = null)
1152 {
1153 global $USER_FIELD_MANAGER;
1154 $user = array();
1155
1156 if (!$allowedUserFields)
1157 {
1158 $allowedUserFields = static::getDefaultAllowedUserFields();
1159 }
1160
1161 $userId = (int) $userData['ID'];
1162
1163 $fieldsList = $USER_FIELD_MANAGER->getUserFields('USER', $userId, LANGUAGE_ID);
1164
1165 foreach ($userData as $key => $value)
1166 {
1167 if (in_array($key, $allowedUserFields, true))
1168 {
1169 if (mb_strpos($key, static::$nameFieldFullPrefix) === 0)
1170 {
1171 $user[$key] = static::prepareUserField($fieldsList[$key], $value);
1172 }
1173 else
1174 {
1175 $user[$key] = $value;
1176 }
1177 }
1178 }
1179
1180
1181 if (isset($user['ACTIVE']))
1182 $user['ACTIVE'] = ($user['ACTIVE'] && $user['ACTIVE'] != 'N') ? 'Y' : 'N';
1183
1184 if (isset($user['PERSONAL_BIRTHDAY']))
1185 $user['PERSONAL_BIRTHDAY'] = \CRestUtil::unConvertDate($user['PERSONAL_BIRTHDAY']);
1186
1187 if (isset($user['UF_DEPARTMENT']) && !is_array($user['UF_DEPARTMENT']) && !empty($user['UF_DEPARTMENT']))
1188 $user['UF_DEPARTMENT'] = array($user['UF_DEPARTMENT']);
1189
1190 if (isset($user['PERSONAL_PHOTO']))
1191 {
1192 $user['PERSONAL_PHOTO'] = \CRestUtil::saveFile($user['PERSONAL_PHOTO']);
1193
1194 if (!$user['PERSONAL_PHOTO'])
1195 {
1196 $user['PERSONAL_PHOTO'] = array('del' => 'Y');
1197 }
1198 }
1199
1200 $user = array_diff_key($user, array_fill_keys(static::$holdEditFields, 'Y'));
1201
1202 return $user;
1203 }
1204
1205 protected static function getUserData($userFields, $allowedFields = null)
1206 {
1207 static $extranetModuleInstalled = null;
1208 if ($extranetModuleInstalled === null)
1209 {
1210 $extranetModuleInstalled = ModuleManager::isModuleInstalled('extranet');
1211 }
1212 global $USER_FIELD_MANAGER;
1213 $fieldsList = $USER_FIELD_MANAGER->getUserFields(static::$entityUser, 0, LANGUAGE_ID);
1214
1215 $urlManager = \Bitrix\Main\Engine\UrlManager::getInstance();
1216
1217 $res = array();
1218 if (is_null($allowedFields))
1219 {
1220 $allowedFields = static::getDefaultAllowedUserFields();
1221 }
1222 foreach ($allowedFields as $key)
1223 {
1224 switch ($key)
1225 {
1226 case 'ACTIVE':
1227 $res[$key] = $userFields[$key] == 'Y';
1228 break;
1229 case 'PERSONAL_BIRTHDAY':
1230 case 'DATE_REGISTER':
1231 $res[$key] = \CRestUtil::convertDate($userFields[$key]);
1232 break;
1233 case 'LAST_LOGIN':
1234 $res[$key] = \CRestUtil::convertDateTime($userFields[$key]);
1235 break;
1236 case 'EXTERNAL_AUTH_ID':
1237 $res['IS_NETWORK'] = $userFields[$key] == 'replica';
1238 $res['IS_EMAIL'] = $userFields[$key] == 'email';
1239 unset($userFields[$key]);
1240 break;
1241 default:
1242 if (!empty($fieldsList[$key]))
1243 {
1244 if ($fieldsList[$key]['USER_TYPE_ID'] === 'date')
1245 {
1246 if ($fieldsList[$key]['MULTIPLE'] === 'Y' && is_array($userFields[$key]))
1247 {
1248 foreach ($userFields[$key] as $k => $value)
1249 {
1250 $res[$key][$k] = \CRestUtil::convertDate($userFields[$key][$k]);
1251 }
1252 }
1253 else
1254 {
1255 $res[$key] = \CRestUtil::convertDate($userFields[$key]);
1256 }
1257 }
1258 elseif ($fieldsList[$key]['USER_TYPE_ID'] === 'datetime')
1259 {
1260 if ($fieldsList[$key]['MULTIPLE'] === 'Y' && is_array($userFields[$key]))
1261 {
1262 foreach ($userFields[$key] as $k => $value)
1263 {
1264 $res[$key][$k] = \CRestUtil::convertDateTime($userFields[$key][$k]);
1265 }
1266 }
1267 else
1268 {
1269 $res[$key] = \CRestUtil::convertDateTime($userFields[$key]);
1270 }
1271 }
1272 elseif ($fieldsList[$key]['USER_TYPE_ID'] === 'file')
1273 {
1274 if ($fieldsList[$key]['MULTIPLE'] === 'Y' && is_array($userFields[$key]))
1275 {
1276 foreach ($userFields[$key] as $k => $value)
1277 {
1278 $res[$key][$k] = [
1279 'id' => $userFields[$key][$k],
1280 'showUrl' => $urlManager->create(
1281 'rest.file.get',
1282 [
1283 'entity' => static::$entityUser,
1284 'id' => $userFields['ID'],
1285 'field' => $key,
1286 'value' => $userFields[$key]
1287 ]
1288 ),
1289 'downloadData' => [
1290 'id' => $userFields['ID'],
1291 'field' => $key,
1292 'value' => $userFields[$key][$k],
1293 ],
1294 ];
1295 }
1296 }
1297 else
1298 {
1299 $res[$key] = [
1300 'id' => $userFields[$key],
1301 'showUrl' => $urlManager->create(
1302 'rest.file.get',
1303 [
1304 'entity' => static::$entityUser,
1305 'id' => $userFields['ID'],
1306 'field' => $key,
1307 'value' => $userFields[$key]
1308 ]
1309 ),
1310 'downloadData' => [
1311 'id' => $userFields['ID'],
1312 'field' => $key,
1313 'value' => $userFields[$key]
1314 ]
1315 ];
1316 }
1317 }
1318 }
1319
1320 if (!isset($res[$key]) && isset($userFields[$key]))
1321 {
1322 $res[$key] = $userFields[$key];
1323 }
1324 break;
1325 }
1326 }
1327
1328 return $res;
1329 }
1330
1331 public static function getFile($query, $n, \CRestServer $server)
1332 {
1333 $file = new File();
1334 return $file->getAction(static::$entityUser, $query['id'], $query['field'], $query['value'], $server);
1335 }
1336
1337 protected static function getDefaultSite()
1338 {
1339 return \CSite::getDefSite();
1340 }
1341}
static isModuleInstalled($moduleName)
static getUserSearchFilter(array $fields)
Definition userutils.php:18
static userOnline()
Definition user.php:735
static onRestServiceBuildDescription()
Definition user.php:271
static getUserData($userFields, $allowedFields=null)
Definition user.php:1205
const SCOPE_USER_BASIC
Definition user.php:17
static $allowedUserFields
Definition user.php:126
static userCurrent($query, $n, \CRestServer $server)
Definition user.php:488
static checkAllowedFields()
Definition user.php:351
static userCounters($arParams)
Definition user.php:753
static prepareSaveData($userData, $allowedUserFields=null)
Definition user.php:1151
static userGet($query, $nav=0, \CRestServer $server)
Definition user.php:513
static getDefaultSite()
Definition user.php:1337
static setDefaultAllowedUserField($field)
Definition user.php:266
static getDefaultAllowedUserFields()
Definition user.php:204
static $holdEditFields
Definition user.php:197
static userAdd($userFields, $nav=0, \CRestServer $server=null)
Definition user.php:769
static unsetDefaultAllowedUserField($key)
Definition user.php:261
static isAdmin()
Definition user.php:406
static hasAccess($params)
Definition user.php:411
static getFields($query=[], $nav=0, \CRestServer $server=null)
Definition user.php:447
static userUpdate($userFields, $nav=0, \CRestServer $server=null)
Definition user.php:910
static getFile($query, $n, \CRestServer $server)
Definition user.php:1331
const SCOPE_USER_BRIEF
Definition user.php:18
static onUserInitialize($arParams, $arHandler)
Definition user.php:374
static prepareUserData($userData, $allowedUserFields=null)
Definition user.php:1042
static getAccess($params)
Definition user.php:425
static getByClientId($clientId)
Definition app.php:929