Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
PushService.php
1<?php
2
4
15use Bitrix\Im\V2\Common\ContextCustomer;
16
18{
19 use ContextCustomer;
20
21 private SendingConfig $sendingConfig;
22
26 public function __construct(?SendingConfig $sendingConfig = null)
27 {
28 if ($sendingConfig === null)
29 {
30 $sendingConfig = new SendingConfig();
31 }
32 $this->sendingConfig = $sendingConfig;
33 }
34
35 public function isPullEnable(): bool
36 {
37 static $enable;
38 if ($enable === null)
39 {
40 $enable = \Bitrix\Main\Loader::includeModule('pull');
41 }
42 return $enable;
43 }
44
45
46 //region Push Private chat
47
54 public function sendPushPrivateChat(PrivateChat $chat, Message $message, array $counters = []): void
55 {
56 if (!$this->isPullEnable())
57 {
58 return;
59 }
60
61 $fromUserId = $message->getAuthorId();
62 $toUserId = $chat->getCompanion()->getId();
63
64 $pullMessage = [
65 'module_id' => 'im',
66 'command' => 'message',
67 'params' => (new PushFormat())->formatPrivateMessage($message, $chat),
68 'extra' => \Bitrix\Im\Common::getPullExtra(),
69 ];
70
71 $pullMessageTo = $pullMessage;
72 $pullMessageTo['params']['dialogId'] = $fromUserId;
73
74 $pullMessageFrom = $pullMessage;
75 $pullMessageFrom['params']['dialogId'] = $toUserId;
76
77 $pullMessageFrom['params']['counter'] = $counters[$fromUserId] ?? 0;
78 \Bitrix\Pull\Event::add($fromUserId, $pullMessageFrom);
79
80 if ($fromUserId != $toUserId)
81 {
82 $pullMessageTo['params']['counter'] = $counters[$toUserId] ?? 0;
83 \Bitrix\Pull\Event::add($toUserId, $pullMessageTo);
84
85 $pullMessageTo = $this->preparePushForPrivate($pullMessageTo);
86 $pullMessageFrom = $this->preparePushForPrivate($pullMessageFrom);
87
88 if ($this->sendingConfig->sendPush())
89 {
90 if ($message->getPushMessage())
91 {
92 $pullMessageTo['push']['message'] = $message->getPushMessage();
93 $pullMessageTo['push']['advanced_params']['senderMessage'] = $message->getPushMessage();
94 $pullMessageFrom['push']['message'] = $message->getPushMessage();
95 $pullMessageFrom['push']['advanced_params']['senderMessage'] = $message->getPushMessage();
96 }
97
98 $pullMessageTo['push']['advanced_params']['counter'] = $counters[$toUserId] ?? 0;
99 \Bitrix\Pull\Push::add($toUserId, $pullMessageTo);
100
101 $pullMessageFrom['push']['advanced_params']['counter'] = $counters[$fromUserId] ?? 0;
102 \Bitrix\Pull\Push::add($fromUserId, array_merge_recursive($pullMessageFrom, ['push' => [
103 'skip_users' => [$fromUserId],
104 'advanced_params' => [
105 "notificationsToCancel" => ['IM_MESS'],
106 ],
107 'send_immediately' => 'Y', // $this->sendingConfig->sendPushImmediately()
108 ]]));
109 }
110 }
111 }
112
117 private function preparePushForPrivate(array $params): array
118 {
119 $pushText = $this->prepareMessageForPush($params['params']);
120 unset($params['params']['message']['text_push']);
121
122 if (isset($params['params']['system']) && $params['params']['system'] == 'Y')
123 {
124 $userName = '';
125 $avatarUser = '';
126 }
127 else
128 {
129 $userName = User::getInstance($params['params']['message']['senderId'])->getFullName(false);
130 $avatarUser = User::getInstance($params['params']['message']['senderId'])->getAvatar();
131 if ($avatarUser && mb_strpos($avatarUser, 'http') !== 0)
132 {
133 $avatarUser = \Bitrix\Im\Common::getPublicDomain().$avatarUser;
134 }
135 }
136
137 if ($params['params']['users'][$params['params']['message']['senderId']])
138 {
139 $params['params']['users'] = [
140 $params['params']['message']['senderId'] => $params['params']['users'][$params['params']['message']['senderId']]
141 ];
142 }
143 else
144 {
145 $params['params']['users'] = [];
146 }
147
148 unset($params['extra']);
149
150 array_walk_recursive($params, function(&$item, $key)
151 {
152 if (is_null($item))
153 {
154 $item = false;
155 }
156 else if ($item instanceof DateTime)
157 {
158 $item = date('c', $item->getTimestamp());
159 }
160 });
161
162 $result = [];
163 $result['module_id'] = 'im';
164 $result['push'] = [];
165 $result['push']['type'] = 'message';
166 $result['push']['tag'] = 'IM_MESS_'.(int)$params['params']['message']['senderId'];
167 $result['push']['sub_tag'] = 'IM_MESS';
168 $result['push']['app_id'] = 'Bitrix24';
169 $result['push']['message'] = $pushText;
170 $result['push']['advanced_params'] = [
171 'group' => 'im_message',
172 'avatarUrl' => $avatarUser,
173 'senderName' => $userName,
174 'senderMessage' => $pushText,
175 'data' => $this->prepareEventForPush($params['command'], $params['params']),
176 ];
177 $result['push']['params'] = [
178 'TAG' => 'IM_MESS_'.$params['params']['message']['senderId'],
179 'CATEGORY' => 'ANSWER',
180 'URL' => SITE_DIR. 'mobile/ajax.php?mobile_action=im_answer',
181 'PARAMS' => [
182 'RECIPIENT_ID' => (int)$params['params']['message']['senderId'],
183 'MESSAGE_ID' => $params['params']['message']['id']
184 ],
185 ];
186
187 return $result;
188 }
189
190 //endregion
191
192
193 //region Push in Group Chat
194
201 public function sendPushGroupChat(GroupChat $chat, Message $message, array $counters = []): void
202 {
203 if (!$this->isPullEnable())
204 {
205 return;
206 }
207
208 $fromUserId = $message->getAuthorId();
209
210 $skippedRelations = [];
211 $pushUserSkip = [];
212 $pushUserSend = [];
213
214 foreach ($chat->getRelations() as $relation)
215 {
216 if ($this->sendingConfig->addRecent() !== true)
217 {
218 $skippedRelations[$relation->getId()] = true;
219 continue;
220 }
221 if ($relation->getUser()->getExternalAuthId() == \Bitrix\Im\Bot::EXTERNAL_AUTH_ID)
222 {
223 }
224 elseif ($relation->getUser()->isActive() !== true)
225 {
226 $skippedRelations[$relation->getId()] = true;
227 continue;
228 }
229
230 if ($chat->getEntityType() == Chat::ENTITY_TYPE_LINE)
231 {
232 if ($relation->getUser()->getExternalAuthId() == 'imconnector')
233 {
234 $skippedRelations[$relation->getId()] = true;
235 continue;
236 }
237 }
238
239 if ($relation->getUserId() == $fromUserId)
240 {
241 \CPushManager::DeleteFromQueueBySubTag($fromUserId, 'IM_MESS');
242 }
243 elseif ($relation->getNotifyBlock() && !$this->sendingConfig->sendPushImmediately())
244 {
245 $pushUserSkip[] = $relation->getChatId();
246 $pushUserSend[] = $relation->getChatId();
247 }
248 elseif (!$this->sendingConfig->sendPush())
249 {
250 }
251 else
252 {
253 $pushUserSend[] = $relation['USER_ID'];
254 }
255 }
256
257 $pullMessage = [
258 'module_id' => 'im',
259 'command' => 'messageChat',
260 'params' => $this->getFormatGroupChatMessage($message, $chat),
261 'extra' => \Bitrix\Im\Common::getPullExtra()
262 ];
263 $events = [];
264 foreach ($chat->getRelations() as $relation)
265 {
266 if (isset($skippedRelations[$relation->getId()]))
267 {
268 continue;
269 }
270 $events[$relation->getUserId()] = $pullMessage;
271 $events[$relation->getUserId()]['params']['counter'] = $counters[$relation->getUserId()] ?? 0;
272 $events[$relation->getUserId()]['groupId'] =
273 'im_chat_'
274 . $chat->getChatId()
275 . '_'. $message->getMessageId()
276 . '_'. $events[$relation['USER_ID']]['params']['counter']
277 ;
278 }
279
280 if ($chat->getType() == Chat::IM_TYPE_OPEN || $chat->getType() == Chat::IM_TYPE_OPEN_LINE)
281 {
282 $watchPullMessage = $pullMessage;
283 $watchPullMessage['params']['message']['params']['NOTIFY'] = 'N';
284 \CPullWatch::AddToStack('IM_PUBLIC_'. $chat->getChatId(), $watchPullMessage);
285 }
286
287 $groups = $this->getEventByCounterGroup($events);
288 foreach ($groups as $group)
289 {
290 \Bitrix\Pull\Event::add($group['users'], $group['event']);
291
292 $userList = array_intersect($pushUserSend, $group['users']);
293 if (!empty($userList))
294 {
295 $pushParams = $group['event'];
296
297 $pushParams = $this->preparePushForChat($pushParams);
298
299 if ($this->sendingConfig->sendPushImmediately())
300 {
301 $pushParams['push']['important'] = 'Y';
302 }
303
304 $pushParams['skip_users'] = $pushUserSkip;
305
306 if ($message->getPushMessage())
307 {
308 $pushParams['push']['message'] = $message->getPushMessage();
309 $pushParams['push']['advanced_params']['senderMessage'] = $message->getPushMessage();
310 }
311 $pushParams['push']['advanced_params']['counter'] = $group['event']['params']['counter'];
312
313 \Bitrix\Pull\Push::add($userList, $pushParams);
314 }
315 }
316 }
317
323 private function getFormatGroupChatMessage(Message $message, GroupChat $chat): array
324 {
325 $fromUserId = $message->getAuthorId();
326
327 $arUsers = \CIMContactList::GetUserData(Array(
328 'ID' => $fromUserId,
329 'PHONES' => 'Y',
330 ));
331
332 $arChat = \CIMChat::GetChatData([
333 'ID' => $chat->getChatId(),
334 'USE_CACHE' => 'N',
335 ]);
336
337 // todo: Replace it with Chat methods
338 $pushParams = $message->getPushParams();
339 $extraParamContext = $pushParams['CONTEXT'] ?? null;
340 if (
341 !empty($arUsers['users'])
342 && $extraParamContext == Chat::ENTITY_TYPE_LIVECHAT
343 && \Bitrix\Main\Loader::includeModule('imopenlines')
344 )
345 {
346 [$lineId, $userId] = explode('|', $arChat['chat'][$chat->getChatId()]['entity_id']);
347 $userCode = 'livechat|' . $lineId . '|' . $chat->getChatId() . '|' . $userId;
348 unset($lineId, $userId);
349
350 foreach ($arUsers['users'] as $userId => $userData)
351 {
352 $arUsers['users'][$userId] = \Bitrix\ImOpenLines\Connector::getOperatorInfo($pushParams['LINE_ID'], $userId, $userCode);
353 }
354 }
355
356 return [
357 'chatId' => $chat->getChatId(),
358 'dialogId' => $chat->getDialogId(),
359 'chat' => $arChat['chat'] ?? [],
360 'lines' => $arChat['lines'][$chat->getChatId()] ?? null,
361 'userInChat' => $arChat['userInChat'] ?? [],
362 'userBlockChat' => $arChat['userChatBlockStatus'] ?? [],
363 'users' => (is_array($arUsers) && is_array($arUsers['users'])) ? $arUsers['users'] : null,
364 'message' => [
365 'id' => $message->getMessageId(),
366 'templateId' => $message->getUuid(),
367 'templateFileId' => $message->getFileIds(),
368 'prevId' => $chat->getPrevMessageId(),
369 'chatId' => $chat->getChatId(),
370 'senderId' => $fromUserId,
371 'recipientId' => $chat->getDialogId(),
372 'system' => ($message->isSystem() ? 'Y': 'N'),
373 'date' => DateTime::createFromTimestamp(time()), // DATE_CREATE
374 'text' => Text::parse($message->getMessage()),
375 'textLegacy' => Text::parseLegacyFormat($message->getMessage()),
376 'params' => $message->getParams()->toPullFormat(),
377 'counter' => 0,
378 'isImportant' => $message->isImportant(),
379 'importantFor' => $message->getImportantFor(),
380 ],
381 'files' => $message->getFilesDiskData(),
382 'notify' => 'Y',
383 ];
384 }
385
391 public function getEventByCounterGroup(array $events, int $maxUserInGroup = 100): array
392 {
393 $groups = [];
394 foreach ($events as $userId => $event)
395 {
396 $eventCode = $event['groupId'];
397 if (!isset($groups[$eventCode]))
398 {
399 $groups[$eventCode]['event'] = $event;
400 }
401 $groups[$eventCode]['users'][] = $userId;
402 $groups[$eventCode]['count'] = count($groups[$eventCode]['users']);
403 }
404
405 \Bitrix\Main\Type\Collection::sortByColumn($groups, ['count' => \SORT_DESC]);
406
407 $count = 0;
408 $finalGroup = [];
409 foreach ($groups as $eventCode => $event)
410 {
411 if ($count >= $maxUserInGroup)
412 {
413 if (isset($finalGroup['other']))
414 {
415 $finalGroup['other']['users'] = array_unique(array_merge($finalGroup['other']['users'], $event['users']));
416 }
417 else
418 {
419 $finalGroup['other'] = $event;
420 $finalGroup['other']['event']['params']['counter'] = 100;
421 }
422 }
423 else
424 {
425 $finalGroup[$eventCode] = $event;
426 }
427 $count++;
428 }
429
430 \Bitrix\Main\Type\Collection::sortByColumn($finalGroup, ['count' => \SORT_ASC]);
431
432 return $finalGroup;
433 }
434
439 private function preparePushForChat(array $params): array
440 {
441 $pushText = $this->prepareMessageForPush($params['params']);
442 unset($params['params']['message']['text_push']);
443
444 $chatTitle = mb_substr(htmlspecialcharsback($params['params']['chat'][$params['params']['chatId']]['name']), 0, 32);
445 $chatType = $params['params']['chat'][$params['params']['chatId']]['type'];
446 $chatAvatar = $params['params']['chat'][$params['params']['chatId']]['avatar'];
447 $chatTypeLetter = $params['params']['chat'][$params['params']['chatId']]['message_type'];
448
449
450 if (($params['params']['system'] ?? null) === 'Y' || $params['params']['message']['senderId'] <= 0)
451 {
452 $avatarUser = '';
453 $userName = '';
454 }
455 else
456 {
457 $userName = User::getInstance($params['params']['message']['senderId'])->getFullName(false);
458 $avatarUser = User::getInstance($params['params']['message']['senderId'])->getAvatar();
459 if ($avatarUser && mb_strpos($avatarUser, 'http') !== 0)
460 {
461 $avatarUser = \Bitrix\Im\Common::getPublicDomain().$avatarUser;
462 }
463 }
464
465 if (
466 isset(
467 $params['params']['message']['senderId'],
468 $params['params']['users'][$params['params']['message']['senderId']]
469 )
470 && $params['params']['users'][$params['params']['message']['senderId']]
471 )
472 {
473 $params['params']['users'] = [
474 $params['params']['message']['senderId'] => $params['params']['users'][$params['params']['message']['senderId']]
475 ];
476 }
477 else
478 {
479 $params['params']['users'] = [];
480 }
481
482 if ($chatAvatar == '/bitrix/js/im/images/blank.gif')
483 {
484 $chatAvatar = '';
485 }
486 else if ($chatAvatar && mb_strpos($chatAvatar, 'http') !== 0)
487 {
488 $chatAvatar = \Bitrix\Im\Common::getPublicDomain().$chatAvatar;
489 }
490
491 unset($params['extra']);
492
493 array_walk_recursive($params, function(&$item, $key)
494 {
495 if (is_null($item))
496 {
497 $item = false;
498 }
499 else if ($item instanceof DateTime)
500 {
501 $item = date('c', $item->getTimestamp());
502 }
503 });
504
505 $result = [];
506 $result['module_id'] = 'im';
507 $result['push']['type'] = ($chatType === 'open'? 'openChat': $chatType);
508 $result['push']['tag'] = 'IM_CHAT_'.intval($params['params']['chatId']);
509 $result['push']['sub_tag'] = 'IM_MESS';
510 $result['push']['app_id'] = 'Bitrix24';
511 $result['push']['message'] = ($userName? $userName.': ': '').$pushText;
512 $result['push']['advanced_params'] = [
513 'group' => $chatType == 'lines'? 'im_lines_message': 'im_message',
514 'avatarUrl' => $chatAvatar? $chatAvatar: $avatarUser,
515 'senderName' => $chatTitle,
516 'senderMessage' => ($userName? $userName.': ': '').$pushText,
517 'senderCut' => mb_strlen($userName? $userName.': ' : ''),
518 'data' => $this->prepareEventForPush($params['command'], $params['params'])
519 ];
520 $result['push']['params'] = [
521 'TAG' => 'IM_CHAT_'.$params['params']['chatId'],
522 'CHAT_TYPE' => $chatTypeLetter? $chatTypeLetter: 'C',
523 'CATEGORY' => 'ANSWER',
524 'URL' => SITE_DIR.'mobile/ajax.php?mobile_action=im_answer',
525 'PARAMS' => [
526 'RECIPIENT_ID' => 'chat'.$params['params']['chatId'],
527 'MESSAGE_ID' => $params['params']['message']['id']
528 ],
529 ];
530
531 return $result;
532 }
533
534
535 //endregion
536
537
538 //region Notification Push
539
540 public function sendPushNotification(NotifyChat $chat, Message $message, int $counter = 0, bool $sendNotifyFlash = true): void
541 {
542 if (!$this->isPullEnable())
543 {
544 return;
545 }
546
547 $toUserId = $chat->getAuthorId();
548
549 $pullNotificationParams = $this->getFormatNotify($message, $counter);
550
551 // We shouldn't send push, if it is disabled in notification settings.
552 $needPush = \CIMSettings::GetNotifyAccess(
553 $toUserId,
554 $message->getNotifyModule(),
555 $message->getNotifyEvent(),
556 \CIMSettings::CLIENT_PUSH
557 );
558
559 if ($needPush)
560 {
561 // we prepare push params ONLY if there are no ADVANCED_PARAMS from outside.
562 // If ADVANCED_PARAMS exists we must not change them.
563 $pushParams = $message->getPushParams();
564 if (isset($pushParams['ADVANCED_PARAMS']))
565 {
566 $advancedParams = $pushParams['ADVANCED_PARAMS'];
567 unset($pushParams['ADVANCED_PARAMS']);
568 }
569 else
570 {
571 $advancedParams = $this->prepareAdvancedParamsForNotificationPush(
572 $pullNotificationParams,
573 $message->getPushMessage()
574 );
575 }
576
577 \Bitrix\Pull\Push::add(
578 $toUserId,
579 [
580 'module_id' => $message->getNotifyModule(),
581 'push' => [
582 'type' => $message->getNotifyEvent(),
583 'message' => $message->getPushMessage(),
584 'params' => $message->getPushParams() ?? ['TAG' => 'IM_NOTIFY'],
585 'advanced_params' => $advancedParams,
586 'important' => ($this->sendingConfig->sendPushImmediately() ? 'Y': 'N'),
587 'tag' => $message->getNotifyTag(),
588 'sub_tag' => $message->getNotifySubTag(),
589 'app_id' => $message->getPushAppId() ?? '',
590 ]
591 ]
592 );
593 }
594
595 //($message->isNotifyFlash() ?? false),
596 if ($sendNotifyFlash)
597 {
598 \Bitrix\Pull\Event::add(
599 $toUserId,
600 [
601 'module_id' => 'im',
602 'command' => 'notifyAdd',
603 'params' => $pullNotificationParams,
604 'extra' => \Bitrix\Im\Common::getPullExtra()
605 ]
606 );
607 }
608 }
609
610 public function sendPushNotificationFlash(NotifyChat $chat, Message $message, int $counter = 0): void
611 {
612 if (!$this->isPullEnable())
613 {
614 return;
615 }
616
617 $toUserId = $chat->getAuthorId();
618
619 $pullNotificationParams = $this->getFormatNotify($message, $counter);
620
621 \Bitrix\Pull\Event::add(
622 $toUserId,
623 [
624 'module_id' => 'im',
625 'command' => 'notifyAdd',
626 'params' => $pullNotificationParams,
627 'extra' => \Bitrix\Im\Common::getPullExtra()
628 ]
629 );
630 }
631
637 private function getFormatNotify(Message $message, int $counter = 0): array
638 {
639 $messageText = Text::parse(
641 [
642 'LINK' => 'Y', // (isset($arFields['HIDE_LINK']) && $arFields['HIDE_LINK'] === 'Y') ? 'N' : 'Y',
643 'LINK_TARGET_SELF' => 'Y',
644 'SAFE' => 'N',
645 'FONT' => 'Y',
646 'SMILES' => 'N',
647 ]
648 );
649
650 $notify = [
651 'id' => $message->getMessageId(),
652 'type' => $message->getNotifyType(),
653 'date' => DateTime::createFromTimestamp(time()), // DATE_CREATE
654 'silent' => 'N', //($arFields['NOTIFY_SILENT'] ?? null) ? 'Y' : 'N',
655 'onlyFlash' => ($message->isNotifyFlash() ?? false),
656 'link' => ($message->getNotifyLink() ?? ''),
657 'text' => $messageText,
658 'tag' => ($message->getNotifyTag() ? md5($message->getNotifyTag()) : ''),
659 'originalTag' => $message->getNotifyTag(),
660 'original_tag' => $message->getNotifyTag(),
661 'read' => $message->isNotifyRead() !== null ? ($message->isNotifyRead() ? 'Y' : 'N') : null,
662 'settingName' => $message->getNotifyModule(). '|'. $message->getNotifyEvent(),
663 'params' => $message->getParams()->toPullFormat(),
664 'counter' => $counter,
665 'users' => [],
666 'userId' => null,
667 'userName' => null,
668 'userColor' => null,
669 'userAvatar' => null,
670 'userLink' => null,
671 ];
672 if ($message->getAuthorId())
673 {
674 $notify['users'][] = $message->getAuthor()->getArray([
675 'JSON' => 'Y',
676 'SKIP_ONLINE' => 'Y'
677 ]);
678
679 $notify['userId'] = $message->getAuthorId();
680 $notify['userName'] = $message->getAuthor()->getName();
681 $notify['userColor'] = $message->getAuthor()->getColor();
682 $notify['userAvatar'] = $message->getAuthor()->getAvatar();
683 $notify['userLink'] = $message->getAuthor()->getProfile();
684 }
685
686
687 if ($message->getNotifyType() == \IM_NOTIFY_CONFIRM)
688 {
689 $notify['buttons'] = $message->getNotifyButtons();
690 }
691 else
692 {
693 $notify['title'] = htmlspecialcharsbx($message->getNotifyTitle());
694 }
695
696 return $notify;
697 }
698
704 private function prepareAdvancedParamsForNotificationPush(array $params, ?string $pushMessage = null): array
705 {
706 if ($params['date'] instanceof DateTime)
707 {
708 $params['date'] = date('c', $params['date']->getTimestamp());
709 }
710
711 $params['text'] = $this->prepareMessageForPush(['message' => ['text' => $params['text']]]);
712
713 $advancedParams = [
714 'id' => 'im_notify',
715 'group' => 'im_notify',
716 'data' => $this->prepareNotificationEventForPush($params, $pushMessage)
717 ];
718
719 if (isset($params['userName']))
720 {
721 $advancedParams['senderName'] = $params['userName'];
722 if (isset($params['userAvatar']))
723 {
724 $advancedParams['avatarUrl'] = $params['userAvatar'];
725 }
726 $advancedParams['senderMessage'] = $pushMessage ?: $params['text'];
727 }
728
729 return $advancedParams;
730 }
731
741 private function prepareNotificationEventForPush(array $event, ?string $pushMessage = null): array
742 {
743 $result = [
744 'cmd' => 'notifyAdd',
745 'id' => (int)$event['id'],
746 'type' => (int)$event['type'],
747 'date' => (string)$event['date'],
748 'tag' => (string)$event['tag'],
749 'onlyFlash' => $event['onlyFlash'],
750 'originalTag' => (string)$event['originalTag'],
751 'settingName' => (string)$event['settingName'],
752 'counter' => (int)$event['counter'],
753 'userId' => (int)$event['userId'],
754 'userName' => (string)$event['userName'],
755 'userColor' => (string)$event['userColor'],
756 'userAvatar' => (string)$event['userAvatar'],
757 'userLink' => (string)$event['userLink'],
758 'params' => $event['params'],
759 ];
760 if (isset($event['buttons']))
761 {
762 $result['buttons'] = $event['buttons'];
763 }
764
765 // We need to save original text ("long") in result only if we have push text ("short").
766 // "Long" text will be used to render push in notifications list.
767 if (isset($pushMessage))
768 {
769 $result['text'] = $event['text'];
770 }
771
772 $fieldToIndex = [
773 'id' => 1,
774 'type' => 2,
775 'date' => 3,
776 'text' => 4,
777 'tag' => 6,
778 'onlyFlash' => 7,
779 'originalTag' => 8,
780 'settingName' => 9,
781 'counter' => 10,
782 'userId' => 11,
783 'userName' => 12,
784 'userColor' => 13,
785 'userAvatar' => 14,
786 'userLink' => 15,
787 'params' => 16,
788 'buttons' => 17,
789 ];
790
791 return $this->changeKeysPushEvent($result, $fieldToIndex);
792 }
793
794
795 //endregion
796
797
798 //region Common
799
804 private function prepareMessageForPush(array $message): string
805 {
807
808 $messageText = $message['message']['text'];
809 if (isset($message['message']['text_push']) && $message['message']['text_push'])
810 {
811 $messageText = $message['message']['text_push'];
812 }
813 else
814 {
815 if (isset($message['message']['params']['ATTACH']) && count($message['message']['params']['ATTACH']) > 0)
816 {
817 $attachText = $message['message']['params']['ATTACH'][0]['DESCRIPTION'];
818 if (!$attachText)
819 {
820 $attachText = Text::getEmoji('attach').' '.Loc::getMessage('IM_MESSAGE_ATTACH');
821 }
822
823 $messageText .=
824 (empty($messageText)? '': ' ')
825 . $attachText
826 ;
827 }
828
829 if (isset($message['files']) && count($message['files']) > 0)
830 {
831 $file = array_values($message['files'])[0];
832
833 if ($file['type'] === 'image')
834 {
835 $fileName = Text::getEmoji($file['type']).' '.Loc::getMessage('IM_MESSAGE_IMAGE');
836 }
837 else if ($file['type'] === 'audio')
838 {
839 $fileName = Text::getEmoji($file['type']).' '.Loc::getMessage('IM_MESSAGE_AUDIO');
840 }
841 else if ($file['type'] === 'video')
842 {
843 $fileName = Text::getEmoji($file['type']).' '.Loc::getMessage('IM_MESSAGE_VIDEO');
844 }
845 else
846 {
847 $fileName = Text::getEmoji('file', Loc::getMessage('IM_MESSAGE_FILE').':').' '.$file['name'];
848 }
849
850 $messageText .= trim($fileName);
851 }
852 }
853
854 $codeIcon = Text::getEmoji('code', '['.Loc::getMessage('IM_MESSAGE_CODE').']');
855 $quoteIcon = Text::getEmoji('quote', '['.Loc::getMessage('IM_MESSAGE_QUOTE').']');
856
857 $messageText = str_replace("\n", ' ', $messageText);
858 $messageText = preg_replace("/\[CODE\](.*?)\[\/CODE\]/si", ' '.$codeIcon.' ', $messageText);
859 $messageText = preg_replace("/\[s\].*?\[\/s\]/i", '-', $messageText);
860 $messageText = preg_replace("/\[[bui]\](.*?)\[\/[bui]\]/i", "$1", $messageText);
861 $messageText = preg_replace("/\\[url\\](.*?)\\[\\/url\\]/i".\BX_UTF_PCRE_MODIFIER, "$1", $messageText);
862 $messageText = preg_replace("/\\[url\\s*=\\s*((?:[^\\[\\]]++|\\[ (?: (?>[^\\[\\]]+) | (?:\\1) )* \\])+)\\s*\\](.*?)\\[\\/url\\]/ixs".\BX_UTF_PCRE_MODIFIER, "$2", $messageText);
863 $messageText = preg_replace_callback("/\[USER=([0-9]{1,})\]\[\/USER\]/i", ['\Bitrix\Im\Text', 'modifyShortUserTag'], $messageText);
864 $messageText = preg_replace("/\[USER=([0-9]+)( REPLACE)?](.+?)\[\/USER]/i", "$3", $messageText);
865 $messageText = preg_replace("/\[CHAT=([0-9]{1,})\](.*?)\[\/CHAT\]/i", "$2", $messageText);
866 $messageText = preg_replace_callback("/\[SEND(?:=(?:.+?))?\](?:.+?)?\[\/SEND]/i", ['\Bitrix\Im\Text', "modifySendPut"], $messageText);
867 $messageText = preg_replace_callback("/\[PUT(?:=(?:.+?))?\](?:.+?)?\[\/PUT]/i", ['\Bitrix\Im\Text', "modifySendPut"], $messageText);
868 $messageText = preg_replace("/\[CALL(?:=(.+?))?\](.+?)?\[\/CALL\]/i", "$2", $messageText);
869 $messageText = preg_replace("/\[PCH=([0-9]{1,})\](.*?)\[\/PCH\]/i", "$2", $messageText);
870 $messageText = preg_replace_callback("/\[ICON\=([^\]]*)\]/i", ['\Bitrix\Im\Text', 'modifyIcon'], $messageText);
871 $messageText = preg_replace('#\-{54}.+?\-{54}#s', ' '.$quoteIcon.' ', str_replace('#BR#', ' ', $messageText));
872 $messageText = preg_replace('/^(>>(.*)(\n)?)/mi', ' '.$quoteIcon.' ', str_replace('#BR#', ' ', $messageText));
873 $messageText = preg_replace("/\\[color\\s*=\\s*([^\\]]+)\\](.*?)\\[\\/color\\]/is".\BX_UTF_PCRE_MODIFIER, "$2", $messageText);
874 $messageText = preg_replace("/\\[size\\s*=\\s*([^\\]]+)\\](.*?)\\[\\/size\\]/is".\BX_UTF_PCRE_MODIFIER, "$2", $messageText);
875
876 return trim($messageText);
877 }
878
879 private function prepareEventForPush(string $command, array $event): array
880 {
881 $result = [
882 'cmd' => $command,
883 'chatId' => (int)$event['chatId'],
884 'dialogId' => (string)$event['dialogId'],
885 'counter' => (int)$event['counter'],
886 ];
887
888 if ($event['notify'] !== true)
889 {
890 $result['notify'] = $event['notify'];
891 }
892
893 if (!empty($event['chat'][$event['chatId']]))
894 {
895 $eventChat = $event['chat'][$event['chatId']];
896
897 $chat = [
898 'id' => (int)$eventChat['id'],
899 'name' => (string)$eventChat['name'],
900 'owner' => (int)$eventChat['owner'],
901 'color' => (string)$eventChat['color'],
902 'type' => (string)$eventChat['type'],
903 'date_create' => (string)$eventChat['date_create'],
904 ];
905
906 if (
907 !empty($eventChat['avatar'])
908 && $eventChat['avatar'] !== '/bitrix/js/im/images/blank.gif'
909 )
910 {
911 $chat['avatar'] = $eventChat['avatar'];
912 }
913 if ($eventChat['call'])
914 {
915 $chat['call'] = (string)$eventChat['call'];
916 }
917 if ($eventChat['call_number'])
918 {
919 $chat['call_number'] = (string)$eventChat['call_number'];
920 }
921 if ($eventChat['entity_data_1'])
922 {
923 $chat['entity_data_1'] = (string)$eventChat['entity_data_1'];
924 }
925 if ($eventChat['entity_data_2'])
926 {
927 $chat['entity_data_2'] = (string)$eventChat['entity_data_2'];
928 }
929 if ($eventChat['entity_data_3'])
930 {
931 $chat['entity_data_3'] = (string)$eventChat['entity_data_3'];
932 }
933 if ($eventChat['entity_id'])
934 {
935 $chat['entity_id'] = (string)$eventChat['entity_id'];
936 }
937 if ($eventChat['entity_type'])
938 {
939 $chat['entity_type'] = (string)$eventChat['entity_type'];
940 }
941 if ($eventChat['extranet'])
942 {
943 $chat['extranet'] = true;
944 }
945
946 $result['chat'] = $chat;
947 }
948
949 if (!empty($event['lines']))
950 {
951 $result['lines'] = $event['lines'];
952 }
953
954 if (!empty($event['users'][$event['message']['senderId']]))
955 {
956 $eventUser = $event['users'][$event['message']['senderId']];
957
958 $user = [
959 'id' => (int)$eventUser['id'],
960 'name' => (string)$eventUser['name'],
961 'first_name' => (string)$eventUser['first_name'],
962 'last_name' => (string)$eventUser['last_name'],
963 'color' => (string)$eventUser['color'],
964 ];
965
966 if (
967 !empty($eventUser['avatar'])
968 && $eventUser['avatar'] !== '/bitrix/js/im/images/blank.gif'
969 )
970 {
971 $user['avatar'] = (string)$eventUser['avatar'];
972 }
973
974 if ($eventUser['absent'])
975 {
976 $user['absent'] = true;
977 }
978 if (!$eventUser['active'])
979 {
980 $user['active'] = $eventUser['active'];
981 }
982 if ($eventUser['bot'])
983 {
984 $user['bot'] = true;
985 }
986 if ($eventUser['extranet'])
987 {
988 $user['extranet'] = true;
989 }
990 if ($eventUser['network'])
991 {
992 $user['network'] = true;
993 }
994 if ($eventUser['birthday'])
995 {
996 $user['birthday'] = $eventUser['birthday'];
997 }
998 if ($eventUser['connector'])
999 {
1000 $user['connector'] = true;
1001 }
1002 if ($eventUser['external_auth_id'] !== 'default')
1003 {
1004 $user['external_auth_id'] = $eventUser['external_auth_id'];
1005 }
1006 if ($eventUser['gender'] === 'F')
1007 {
1008 $user['gender'] = 'F';
1009 }
1010 if ($eventUser['work_position'])
1011 {
1012 $user['work_position'] = (string)$eventUser['work_position'];
1013 }
1014
1015 $result['users'] = $user;
1016 }
1017
1018 if (!empty($event['files']))
1019 {
1020 foreach ($event['files'] as $key => $value)
1021 {
1022 $file = [
1023 'id' => (int)$value['id'],
1024 'extension' => (string)$value['extension'],
1025 'name' => (string)$value['name'],
1026 'size' => (int)$value['size'],
1027 'type' => (string)$value['type'],
1028 'image' => $value['image'],
1029 'urlDownload' => '',
1030 'urlPreview' => (new \Bitrix\Main\Web\Uri($value['urlPreview']))->deleteParams(['fileName'])->getUri(),
1031 'urlShow' => '',
1032 ];
1033 if ($value['image'])
1034 {
1035 $file['image'] = $value['image'];
1036 }
1037 if ($value['progress'] !== 100)
1038 {
1039 $file['progress'] = (int)$value['progress'];
1040 }
1041 if ($value['status'] !== 'done')
1042 {
1043 $file['status'] = $value['status'];
1044 }
1045
1046 $result['files'][$key] = $file;
1047 }
1048 }
1049
1050 if (!empty($event['message']))
1051 {
1052 $eventMessage = $event['message'];
1053
1054 $message = [
1055 'id' => (int)$eventMessage['id'],
1056 'date' => (string)$eventMessage['date'],
1057 'params' => $eventMessage['params'],
1058 'prevId' => (int)$eventMessage['prevId'],
1059 'senderId' => (int)$eventMessage['senderId'],
1060 ];
1061
1062 if (isset($message['params']['ATTACH']))
1063 {
1064 unset($message['params']['ATTACH']);
1065 }
1066
1067 if ($eventMessage['system'] === 'Y')
1068 {
1069 $message['system'] = 'Y';
1070 }
1071
1072 $result['message'] = $message;
1073 }
1074
1075 $indexToNameMap = [
1076 'chat' => 1,
1077 'chatId' => 2,
1078 'counter' => 3,
1079 'dialogId' => 4,
1080 'files' => 5,
1081 'message' => 6,
1082 'users' => 8,
1083 'name' => 9,
1084 'avatar' => 10,
1085 'color' => 11,
1086 'notify' => 12,
1087 'type' => 13,
1088 'extranet' => 14,
1089
1090 'date_create' => 20,
1091 'owner' => 21,
1092 'entity_id' => 23,
1093 'entity_type' => 24,
1094 'entity_data_1' => 203,
1095 'entity_data_2' => 204,
1096 'entity_data_3' => 205,
1097 'call' => 201,
1098 'call_number' => 202,
1099 'manager_list' => 209,
1100 'mute_list' => 210,
1101
1102 'first_name' => 40,
1103 'last_name' => 41,
1104 'gender' => 42,
1105 'work_position' => 43,
1106 'active' => 400,
1107 'birthday' => 401,
1108 'bot' => 402,
1109 'connector' => 403,
1110 'external_auth_id' => 404,
1111 'network' => 406,
1112
1113
1114 'textLegacy' => 65,
1115 'date' => 61,
1116 'prevId' => 62,
1117 'params' => 63,
1118 'senderId' => 64,
1119 'system' => 601,
1120
1121 'extension' => 80,
1122 'image' => 81,
1123 'progress' => 82,
1124 'size' => 83,
1125 'status' => 84,
1126 'urlDownload' => 85,
1127 'urlPreview' => 86,
1128 'urlShow' => 87,
1129 'width' => 88,
1130 'height' => 89,
1131 ];
1132
1133 return $this->changeKeysPushEvent($result, $indexToNameMap);
1134 }
1135
1136 private function changeKeysPushEvent(array $object, array $map): array
1137 {
1138 $result = [];
1139
1140 foreach($object as $key => $value)
1141 {
1142 $index = isset($map[$key]) ? $map[$key] : $key;
1143 if (is_null($value))
1144 {
1145 $value = "";
1146 }
1147 if (is_array($value))
1148 {
1149 $result[$index] = $this->changeKeysPushEvent($value, $map);
1150 }
1151 else
1152 {
1153 $result[$index] = $value;
1154 }
1155 }
1156
1157 return $result;
1158 }
1159
1160 //endregion
1161}
static getType($chatData)
Definition chat.php:41
static getPullExtra()
Definition common.php:128
static parse($text, $params=Array())
Definition text.php:24
static convertHtmlToBbCode($html)
Definition text.php:389
static getEmoji($code, $fallbackText='')
Definition text.php:364
static getInstance($userId=null)
Definition user.php:44
getCompanion(?int $userId=null)
const ENTITY_TYPE_LIVECHAT
Definition Chat.php:98
const IM_TYPE_OPEN_LINE
Definition Chat.php:58
const IM_TYPE_OPEN
Definition Chat.php:61
const ENTITY_TYPE_LINE
Definition Chat.php:97
sendPushPrivateChat(PrivateChat $chat, Message $message, array $counters=[])
sendPushGroupChat(GroupChat $chat, Message $message, array $counters=[])
getEventByCounterGroup(array $events, int $maxUserInGroup=100)
sendPushNotificationFlash(NotifyChat $chat, Message $message, int $counter=0)
__construct(?SendingConfig $sendingConfig=null)
sendPushNotification(NotifyChat $chat, Message $message, int $counter=0, bool $sendNotifyFlash=true)
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
static createFromTimestamp($timestamp)
Definition datetime.php:246