Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
user.php
1<?php
3
5use Bitrix\Main\Entity\ExpressionField;
9
10class User
11{
12 static $isEmployee = [];
13
15
16 public static function canInvite(): bool
17 {
18 if (!\Bitrix\Main\ModuleManager::isModuleInstalled('intranet'))
19 {
20 return false;
21 }
22
23 return \Bitrix\Intranet\Invitation::canListDelete();
24 }
25 public static function onInviteLinkCopied(\Bitrix\Main\Event $event): bool
26 {
27 if (!\Bitrix\Main\ModuleManager::isModuleInstalled('intranet'))
28 {
29 return false;
30 }
31
32 $userId = (int)$event->getParameter('userId');
33
34 return self::sendMessageToGeneralChat($userId, [
35 'MESSAGE' => Loc::getMessage('IM_INT_USR_LINK_COPIED', [
36 '#USER_NAME#' => self::getUserBlock($userId)
37 ]),
38 'SYSTEM' => 'Y'
39 ]);
40 }
41
42 public static function onUserInvited(\Bitrix\Main\Event $event): bool
43 {
44 if (!\Bitrix\Main\ModuleManager::isModuleInstalled('intranet'))
45 {
46 return false;
47 }
48
49 $originatorId = (int)$event->getParameter('originatorId');
50 $users = (array)$event->getParameter('userId');
51
52 if (!self::isEmployee($originatorId))
53 {
54 return false;
55 }
56
57 $userForSend = [];
58 $result = \Bitrix\Intranet\UserTable::getList([
59 'filter' => [
60 '=ID' => $users
61 ],
62 'select' => ['ID', 'USER_TYPE', 'EMAIL']
63
64 ]);
65 while ($row = $result->fetch())
66 {
67 if ($row['USER_TYPE'] === 'employee')
68 {
69 $userForSend[] = [
70 'ID' => $row['ID'],
71 'INVITED' => [
72 'originator_id' => $originatorId,
73 'can_resend' => !empty($row['EMAIL'])
74 ]
75 ];
76 }
77 }
78
79 if (empty($userForSend))
80 {
81 return false;
82 }
83
84 self::sendInviteEvent($userForSend);
85
86 $userForSend = array_map(function($user) {
87 return self::getUserBlock($user['ID']);
88 }, $userForSend);
89
90 return self::sendMessageToGeneralChat($originatorId, [
91 'MESSAGE' => Loc::getMessage('IM_INT_USR_INVITE_USERS', [
92 '#USER_NAME#' => self::getUserBlock($originatorId),
93 '#USERS#' => implode(', ', $userForSend)
94 ]),
95 'SYSTEM' => 'Y',
96 'PUSH' => 'N'
97 ]);
98 }
99
100 public static function onUserAdded(\Bitrix\Main\Event $event): bool
101 {
102 if (!\Bitrix\Main\ModuleManager::isModuleInstalled('intranet'))
103 {
104 return false;
105 }
106
107 $originatorId = (int)$event->getParameter('originatorId');
108 $users = (array)$event->getParameter('userId');
109
110 if (!self::isEmployee($originatorId))
111 {
112 return false;
113 }
114
115 $userForSend = [];
116 $result = \Bitrix\Intranet\UserTable::getList([
117 'filter' => [
118 '=ID' => $users
119 ],
120 'select' => ['ID', 'USER_TYPE', 'EMAIL']
121
122 ]);
123 while ($row = $result->fetch())
124 {
125 if ($row['USER_TYPE'] === 'employee')
126 {
127 $userForSend[] = [
128 'ID' => $row['ID'],
129 'INVITED' => [
130 'originator_id' => $originatorId,
131 'can_resend' => !empty($row['EMAIL'])
132 ]
133 ];
134 }
135 }
136
137 self::sendInviteEvent($userForSend);
138
139 $users = array_map(function($userId) {
140 return self::getUserBlock($userId);
141 }, $users);
142
143 return self::sendMessageToGeneralChat($originatorId, [
144 'MESSAGE' => Loc::getMessage('IM_INT_USR_REGISTER_USERS', [
145 '#USER_NAME#' => self::getUserBlock($originatorId),
146 '#USERS#' => implode(', ', $users)
147 ]),
148 'SYSTEM' => 'Y',
149 'PUSH' => 'N'
150 ]);
151 }
152
153 public static function onUserAdminRights(\Bitrix\Main\Event $event): bool
154 {
155 if (!\Bitrix\Main\ModuleManager::isModuleInstalled('intranet'))
156 {
157 return false;
158 }
159
160 if (!\COption::GetOptionString("im", "general_chat_message_admin_rights", true))
161 {
162 return false;
163 }
164
165 $originatorId = (int)$event->getParameter('originatorId');
166 $users = (array)$event->getParameter('userId');
167 $type = (string)$event->getParameter('type');
168
169 $users = array_map(function($userId) {
170 return self::getUserBlock($userId);
171 }, $users);
172
173 $originatorGender = 'M';
174 if ($originatorId > 0)
175 {
176 $dbUser = \CUser::GetList('', '', ['ID_EQUAL_EXACT' => $originatorId], array('FIELDS' => ['PERSONAL_GENDER']));
177 if ($user = $dbUser->Fetch())
178 {
179 $originatorGender = $user["PERSONAL_GENDER"] == 'F'? 'F': 'M';
180 }
181 }
182
183 $messId = (
184 $type === 'setAdminRigths'
185 ? 'IM_INT_USR_SET_ADMIN_RIGTHS_'.$originatorGender
186 : 'IM_INT_USR_REMOVE_ADMIN_RIGTHS_'.$originatorGender
187 );
188
189 return self::sendMessageToGeneralChat($originatorId, [
190 'MESSAGE' => Loc::getMessage($messId, [
191 '#USER_NAME#' => self::getUserBlock($originatorId),
192 '#USERS#' => implode(', ', $users)
193 ]),
194 'SYSTEM' => 'Y'
195 ]);
196
197 }
198
199 public static function onInviteSend(array $params): bool
200 {
201 if (!\Bitrix\Main\ModuleManager::isModuleInstalled('intranet'))
202 {
203 return false;
204 }
205
206 $userId = (int)$params['ID'];
207
208 if (!self::isEmployee($userId))
209 {
210 return false;
211 }
212
213 \CIMContactList::SetRecent(['ENTITY_ID' => $userId]);
214
215 return true;
216 }
217
218 public static function onInviteAccepted(array $params): bool
219 {
220 if (!\Bitrix\Main\ModuleManager::isModuleInstalled('intranet'))
221 {
222 return true;
223 }
224
225 $userData = $params['user_fields'];
226
227 if (in_array($userData['EXTERNAL_AUTH_ID'], \Bitrix\Main\UserTable::getExternalUserTypes()))
228 {
229 return true;
230 }
231
232 if ($userData['LAST_LOGIN'])
233 {
234 return true;
235 }
236
237 $userId = (int)$userData['ID'];
238 if ($userData['LAST_ACTIVITY_DATE'])
239 {
240 return true;
241 }
242
243 if (!self::isEmployee($userId))
244 {
245 return false;
246 }
247
248 \CUser::SetLastActivityDate($userId);
249
250 \CIMContactList::SetRecent(Array('ENTITY_ID' => $userId));
251
252 if (self::isCountOfUsersExceededForPersonalNotify())
253 {
254 if (!\CIMChat::GetGeneralChatAutoMessageStatus(\CIMChat::GENERAL_MESSAGE_TYPE_JOIN))
255 {
256 return false;
257 }
258
259 return self::sendMessageToGeneralChat($userId, [
260 "MESSAGE" => Loc::getMessage('IM_INT_USR_JOIN_GENERAL_2'),
261 "PARAMS" => [
262 "CODE" => 'USER_JOIN_GENERAL',
263 ]
264 ]);
265 }
266
267 self::sendInviteEvent([[
268 'ID' => $userId,
269 'INVITED' => false
270 ]]);
271
272 $orm = \Bitrix\Main\UserTable::getList([
273 'select' => ['ID'],
274 'filter' => [
275 '=ACTIVE' => 'Y',
276 '=IS_REAL_USER' => 'Y',
277 '!=UF_DEPARTMENT' => false
278 ]
279 ]);
280 while($row = $orm->fetch())
281 {
282 if ($row['ID'] == $userId)
283 {
284 continue;
285 }
286
287 $viewCommonUsers = (bool)\CIMSettings::GetSetting(\CIMSettings::SETTINGS, 'viewCommonUsers', $row['ID']);
288 if (!$viewCommonUsers)
289 {
290 continue;
291 }
292
293 \CIMMessage::Add([
294 "TO_USER_ID" => $row['ID'],
295 "FROM_USER_ID" => $userId,
296 "MESSAGE" => Loc::getMessage('IM_INT_USR_JOIN_2'),
297 "SYSTEM" => 'Y',
298 "RECENT_SKIP_AUTHOR" => 'Y',
299 "MESSAGE_OUT" => IM_MAIL_SKIP,
300 "PARAMS" => [
301 "CODE" => 'USER_JOIN',
302 ],
303 ]);
304 }
305
306 return true;
307 }
308
309 private static function sendInviteEvent(array $users): bool
310 {
311 if (!\Bitrix\Main\Loader::includeModule('pull'))
312 {
313 return false;
314 }
315
316 if (!\Bitrix\Main\ModuleManager::isModuleInstalled('intranet'))
317 {
318 return false;
319 }
320
321 $onlineUsers = \Bitrix\Im\Helper::getOnlineIntranetUsers();
322 foreach ($users as $user)
323 {
324 \Bitrix\Pull\Event::add($onlineUsers, [
325 'module_id' => 'im',
326 'command' => 'userInvite',
327 'expiry' => 3600,
328 'params' => [
329 'userId' => $user['ID'],
330 'invited' => $user['INVITED'],
331 'user' => \Bitrix\Im\User::getInstance($user['ID'])->getFields(),
332 'date' => new DateTime(),
333 ],
334 'extra' => \Bitrix\Im\Common::getPullExtra()
335 ]);
336 }
337
338 return true;
339 }
340
341 private static function sendMessageToGeneralChat(int $fromUserId, array $params): bool
342 {
343 $chatId = \CIMChat::GetGeneralChatId();
344 if (!$chatId)
345 return false;
346
347 $params = array_merge($params, [
348 "TO_CHAT_ID" => $chatId,
349 "FROM_USER_ID" => $fromUserId,
350 "MESSAGE_OUT" => IM_MAIL_SKIP,
351 "SKIP_USER_CHECK" => 'Y',
352 ]);
353
354 $result = \CIMChat::AddMessage($params);
355
356 return $result !== false;
357 }
358
359 private static function getUserBlock(int $userId): string
360 {
361 return '[USER='.$userId.'][/USER]';
362 }
363
364 private static function isEmployee(int $userId): bool
365 {
366 if (isset(self::$isEmployee[$userId]))
367 {
368 return self::$isEmployee[$userId];
369 }
370
371 if (!\Bitrix\Main\Loader::includeModule('intranet'))
372 {
373 return false;
374 }
375
376 $result = \Bitrix\Intranet\UserTable::getList([
377 'filter' => [
378 '=ID' => $userId
379 ],
380 'select' => ['ID', 'USER_TYPE']
381
382 ])->fetch();
383
384 self::$isEmployee[$userId] = $result['USER_TYPE'] === 'employee';
385
386 return self::$isEmployee[$userId];
387 }
388
389 public static function getBirthdayForToday()
390 {
391 if (!\Bitrix\Main\ModuleManager::isModuleInstalled('intranet'))
392 {
393 return [];
394 }
395
396 $option = Option::get('im', 'contact_list_birthday');
397 if ($option === 'none' || \Bitrix\Im\User::getInstance()->isExtranet())
398 {
399 return [];
400 }
401
402 global $USER;
403
404 $today = (new DateTime())->format('m-d');
405 if ($option === 'department')
406 {
407 $cacheId = 'birthday_'.$today.'_'.$USER->GetID();
408 }
409 else
410 {
411 $cacheId = 'birthday_'.$today;
412 }
413
414 $cache = \Bitrix\Main\Data\Cache::createInstance();
415 if($cache->initCache(86400, $cacheId, '/bx/im/birthday/'))
416 {
417 return $cache->getVars();
418 }
419
420 $user = \CUser::getById($USER->GetId())->Fetch();
421
422 $filter = [
423 '=ACTIVE' => 'Y',
424 '=BIRTHDAY_DATE' => $today,
425 '=IS_REAL_USER' => true,
426 ];
427 if ($option === 'department')
428 {
429 $filter['=UF_DEPARTMENT'] = $user['UF_DEPARTMENT'];
430 }
431 else
432 {
433 $filter['!=UF_DEPARTMENT'] = false;
434 }
435
436 $connection = \Bitrix\Main\Application::getConnection();
437 $helper = $connection->getSqlHelper();
438
439 $result = [];
440 $users = UserTable::getList([
441 'filter' => $filter,
442 'select' => ['ID'],
443 'runtime' => [
444 new ExpressionField('BIRTHDAY_DATE', str_replace('PERSONAL_BIRTHDAY', '%s', str_replace('%', '%%', $helper->formatDate('MM-DD', 'PERSONAL_BIRTHDAY'))), 'PERSONAL_BIRTHDAY')
445 ],
446 'limit' => 100,
447 ])->fetchAll();
448
449 foreach ($users as $user)
450 {
451 $result[] = \Bitrix\Im\User::getInstance($user['ID'])->getArray(['SKIP_ONLINE' => 'Y', 'JSON' => 'Y']);
452 }
453
454 $cache->forceRewriting(true);
455 $cache->startDataCache();
456 $cache->endDataCache($result);
457
458 return $result;
459 }
460
461 private static function isCountOfUsersExceededForPersonalNotify(): bool
462 {
463 $count = UserTable::query()
464 ->setSelect(['ID'])
465 ->where('ACTIVE', true)
466 ->where('IS_REAL_USER', true)
467 ->whereNotNull('LAST_LOGIN')
468 ->setLimit(self::INVITE_MAX_USER_NOTIFY + 1)
469 ->fetchCollection()
470 ->count()
471 ;
472
473 return $count > self::INVITE_MAX_USER_NOTIFY;
474 }
475
476 public static function registerEventHandler()
477 {
478 $eventManager = \Bitrix\Main\EventManager::getInstance();
479 $eventManager->registerEventHandlerCompatible('main', 'OnAfterUserAuthorize', 'im', self::class, 'onInviteAccepted');
480 $eventManager->registerEventHandlerCompatible('intranet', 'OnRegisterUser', 'im', self::class, 'onInviteSend');
481 $eventManager->registerEventHandler('intranet', 'OnCopyRegisterUrl', 'im', self::class, 'onInviteLinkCopied');
482 $eventManager->registerEventHandler('intranet', 'onUserInvited', 'im', self::class, 'onUserInvited');
483 $eventManager->registerEventHandler('intranet', 'onUserAdded', 'im', self::class, 'onUserAdded');
484 $eventManager->registerEventHandler('intranet', 'onUserAdminRights', 'im', self::class, 'onUserAdminRights');
485 }
486
487 public static function unRegisterEventHandler()
488 {
489 $eventManager = \Bitrix\Main\EventManager::getInstance();
490 $eventManager->unRegisterEventHandler('main', 'OnAfterUserAuthorize', 'im', self::class, 'onInviteAccepted');
491 $eventManager->unRegisterEventHandler('intranet', 'OnRegisterUser', 'im', self::class, 'onInviteSend');
492 $eventManager->unRegisterEventHandler('intranet', 'OnCopyRegisterUrl', 'im', self::class, 'onInviteLinkCopied');
493 $eventManager->unRegisterEventHandler('intranet', 'onUserInvited', 'im', self::class, 'onUserInvited');
494 $eventManager->unRegisterEventHandler('intranet', 'onUserAdded', 'im', self::class, 'onUserAdded');
495 $eventManager->unRegisterEventHandler('intranet', 'onUserAdminRights', 'im', self::class, 'onUserAdminRights');
496 }
497}
498
499
500
static getPullExtra()
Definition common.php:128
static onInviteSend(array $params)
Definition user.php:199
static onUserAdded(\Bitrix\Main\Event $event)
Definition user.php:100
static onInviteLinkCopied(\Bitrix\Main\Event $event)
Definition user.php:25
static onUserInvited(\Bitrix\Main\Event $event)
Definition user.php:42
static onInviteAccepted(array $params)
Definition user.php:218
static onUserAdminRights(\Bitrix\Main\Event $event)
Definition user.php:153
static getInstance($userId=null)
Definition user.php:44
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
static isModuleInstalled($moduleName)