1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
bot.php
См. документацию.
1<?php
2
3namespace Bitrix\Im;
4
5use Bitrix\Im\V2\Chat\Background\Background;
6use Bitrix\Im\V2\Chat\Background\BackgroundId;
7use Bitrix\Im\V2\Chat\PrivateChat;
8use Bitrix\Im\V2\Entity\User\Data\BotData;
9use Bitrix\Im\V2\Message;
10use Bitrix\Main;
11use Bitrix\Main\Localization\Loc;
12
13Loc::loadMessages(__FILE__);
14
15class Bot
16{
17 public const BACKGROUND_MARTA = 'martaAI';
18 public const BACKGROUND_COPILOT = 'copilot';
19 public const BACKGROUND_COLLAB = 'collab';
20 public const BACKGROUND_NONE = '';
21
22 const INSTALL_TYPE_SYSTEM = 'system';
23 const INSTALL_TYPE_USER = 'user';
24 const INSTALL_TYPE_SILENT = 'silent';
25
26 const LOGIN_START = 'bot_';
27 const EXTERNAL_AUTH_ID = 'bot';
28
29 const LIST_ALL = 'all';
30 const LIST_OPENLINE = 'openline';
31
32 const TYPE_HUMAN = 'H';
33 const TYPE_BOT = 'B';
34 const TYPE_SUPERVISOR = 'S';
35 const TYPE_NETWORK = 'N';
36 const TYPE_OPENLINE = 'O';
37
38 const CACHE_TTL = 31536000;
39 const CACHE_PATH = '/bx/im/bot/old_cache_v1/';
40
41 public const PLATFORM_CONTEXT_MOBILE = 'mobile';
42 public const PLATFORM_CONTEXT_WEB = 'web';
43
44 protected static ?string $platformContext = null;
45
50 public static function register(array $fields)
51 {
52 $code = isset($fields['CODE'])? $fields['CODE']: '';
53 $type = in_array($fields['TYPE'], [self::TYPE_BOT, self::TYPE_SUPERVISOR, self::TYPE_NETWORK, self::TYPE_OPENLINE])
54 ? $fields['TYPE']
55 : self::TYPE_BOT;
56 $moduleId = $fields['MODULE_ID'];
57 $installType = in_array($fields['INSTALL_TYPE'], [self::INSTALL_TYPE_SYSTEM, self::INSTALL_TYPE_USER, self::INSTALL_TYPE_SILENT])
58 ? $fields['INSTALL_TYPE']
59 : self::INSTALL_TYPE_SILENT;
60 $botFields = $fields['PROPERTIES'];
61 $language = isset($fields['LANG'])? $fields['LANG']: null;
62
63 /* vars for module install */
64 $class = isset($fields['CLASS'])? $fields['CLASS']: '';
65 $methodBotDelete = isset($fields['METHOD_BOT_DELETE'])? $fields['METHOD_BOT_DELETE']: '';
66 $methodMessageAdd = isset($fields['METHOD_MESSAGE_ADD'])? $fields['METHOD_MESSAGE_ADD']: '';
67 $methodMessageUpdate = isset($fields['METHOD_MESSAGE_UPDATE'])? $fields['METHOD_MESSAGE_UPDATE']: '';
68 $methodMessageDelete = isset($fields['METHOD_MESSAGE_DELETE'])? $fields['METHOD_MESSAGE_DELETE']: '';
69 $methodWelcomeMessage = isset($fields['METHOD_WELCOME_MESSAGE'])? $fields['METHOD_WELCOME_MESSAGE']: '';
70 $methodContextGet = isset($fields['METHOD_CONTEXT_GET']) ? $fields['METHOD_CONTEXT_GET'] : '';
71 $textPrivateWelcomeMessage = isset($fields['TEXT_PRIVATE_WELCOME_MESSAGE'])? $fields['TEXT_PRIVATE_WELCOME_MESSAGE']: '';
72 $textChatWelcomeMessage = isset($fields['TEXT_CHAT_WELCOME_MESSAGE'])? $fields['TEXT_CHAT_WELCOME_MESSAGE']: '';
73 $openline = isset($fields['OPENLINE']) && $fields['OPENLINE'] == 'Y'? 'Y': 'N';
74 $isHidden = isset($fields['HIDDEN']) && $fields['HIDDEN'] === 'Y' ? 'Y' : 'N';
75 $backgroundId = Background::validateBackgroundId($fields['BACKGROUND_ID'] ?? null);
76
77 /* rewrite vars for openline type */
78 if ($type == self::TYPE_OPENLINE)
79 {
80 $openline = 'Y';
81 $installType = self::INSTALL_TYPE_SILENT;
82 }
83
84 /* vars for rest install */
85 $appId = isset($fields['APP_ID'])? $fields['APP_ID']: '';
86 $verified = isset($fields['VERIFIED']) && $fields['VERIFIED'] == 'Y'? 'Y': 'N';
87
88 if ($moduleId == 'rest')
89 {
90 if (empty($appId))
91 {
92 return false;
93 }
94 }
95 else
96 {
97 if (empty($class) || empty($methodMessageAdd))
98 {
99 return false;
100 }
101 if (!(!empty($methodWelcomeMessage) || isset($fields['TEXT_PRIVATE_WELCOME_MESSAGE'])))
102 {
103 return false;
104 }
105 }
106
107 $bots = self::getListCache();
108 if ($moduleId && $code)
109 {
110 foreach ($bots as $bot)
111 {
112 if ($bot['MODULE_ID'] == $moduleId && $bot['CODE'] == $code)
113 {
114 return $bot['BOT_ID'];
115 }
116 }
117 }
118
119 $userCode = $code? $moduleId.'_'.$code: $moduleId;
120
121 $color = null;
122 if (isset($botFields['COLOR']))
123 {
124 $color = $botFields['COLOR'];
125 unset($botFields['COLOR']);
126 }
127
128 $userId = 0;
129 if ($installType == self::INSTALL_TYPE_USER)
130 {
131 if (isset($fields['USER_ID']) && intval($fields['USER_ID']) > 0)
132 {
133 $userId = intval($fields['USER_ID']);
134 }
135 else
136 {
137 global $USER;
138 if (is_object($USER))
139 {
140 $userId = $USER->GetID() > 0? $USER->GetID(): 0;
141 }
142 }
143 if ($userId <= 0)
144 {
145 $installType = self::INSTALL_TYPE_SYSTEM;
146 }
147 }
148
149 if ($moduleId == '')
150 {
151 return false;
152 }
153
154 if (!(isset($botFields['NAME']) || isset($botFields['LAST_NAME'])))
155 {
156 return false;
157 }
158
159 $botFields['LOGIN'] = mb_substr(self::LOGIN_START. mb_substr($userCode, 0, 40). '_'. randString(5), 0, 50);
160 $botFields['PASSWORD'] = md5($botFields['LOGIN'].'|'.rand(1000,9999).'|'.time());
161 $botFields['CONFIRM_PASSWORD'] = $botFields['PASSWORD'];
162 $botFields['EXTERNAL_AUTH_ID'] = self::EXTERNAL_AUTH_ID;
163
164 unset($botFields['GROUP_ID']);
165
166 $botFields['ACTIVE'] = 'Y';
167
168 unset($botFields['UF_DEPARTMENT']);
169
170 $botFields['WORK_POSITION'] = isset($botFields['WORK_POSITION'])? trim($botFields['WORK_POSITION']): '';
171 if (empty($botFields['WORK_POSITION']))
172 {
173 $botFields['WORK_POSITION'] = Loc::getMessage('BOT_DEFAULT_WORK_POSITION');
174 }
175
176 $user = new \CUser;
177 $botId = $user->Add($botFields);
178 if (!$botId)
179 {
180 return false;
181 }
182
183 $result = \Bitrix\Im\Model\BotTable::add(Array(
184 'BOT_ID' => $botId,
185 'CODE' => $code? $code: $botId,
186 'MODULE_ID' => $moduleId,
187 'CLASS' => $class,
188 'TYPE' => $type,
189 'LANG' => $language? $language: '',
190 'METHOD_BOT_DELETE' => $methodBotDelete,
191 'METHOD_MESSAGE_ADD' => $methodMessageAdd,
192 'METHOD_MESSAGE_UPDATE' => $methodMessageUpdate,
193 'METHOD_MESSAGE_DELETE' => $methodMessageDelete,
194 'METHOD_WELCOME_MESSAGE' => $methodWelcomeMessage,
195 'METHOD_CONTEXT_GET' => $methodContextGet,
196 'TEXT_PRIVATE_WELCOME_MESSAGE' => $textPrivateWelcomeMessage,
197 'TEXT_CHAT_WELCOME_MESSAGE' => $textChatWelcomeMessage,
198 'APP_ID' => $appId,
199 'VERIFIED' => $verified,
200 'OPENLINE' => $openline,
201 'HIDDEN' => $isHidden,
202 'BACKGROUND_ID' => $backgroundId,
203 ));
204
205 $cache = \Bitrix\Main\Data\Cache::createInstance();
206 $cache->cleanDir(self::CACHE_PATH);
207
208 if ($result->isSuccess())
209 {
210 if (\Bitrix\Main\Loader::includeModule('pull'))
211 {
212 if ($color)
213 {
214 \CIMStatus::SetColor($botId, $color);
215 }
216
217 self::sendPullNotify($botId, 'botAdd');
218
219 if ($installType != self::INSTALL_TYPE_SILENT)
220 {
221 $message = '';
222 if ($installType == self::INSTALL_TYPE_USER && \Bitrix\Im\User::getInstance($userId)->isExists())
223 {
224 $userName = '[USER='.$userId.'][/USER]';
225 $userGender = \Bitrix\Im\User::getInstance($userId)->getGender();
226 $message = Loc::getMessage('BOT_MESSAGE_INSTALL_USER'.($userGender == 'F'? '_F':''), Array('#USER_NAME#' => $userName));
227 }
228 if (empty($message))
229 {
230 $message = Loc::getMessage('BOT_MESSAGE_INSTALL_SYSTEM');
231 }
232
233 $attach = new \CIMMessageParamAttach(null, $color);
234 $attach->AddBot(Array(
235 "NAME" => \Bitrix\Im\User::getInstance($botId)->getFullName(),
236 "AVATAR" => \Bitrix\Im\User::getInstance($botId)->getAvatar(),
237 "BOT_ID" => $botId,
238 ));
239 $attach->addMessage(\Bitrix\Im\User::getInstance($botId)->getWorkPosition());
240
241 \CIMChat::AddGeneralMessage(Array(
242 'MESSAGE' => $message,
243 'ATTACH' => $attach,
244 'SKIP_USER_CHECK' => 'Y',
245 ));
246 }
247 }
248
249 \Bitrix\Main\Application::getInstance()->getTaggedCache()->clearByTag("IM_CONTACT_LIST");
250 }
251 else
252 {
253 $user->Delete($botId);
254 $botId = 0;
255 }
256
257 return $botId;
258 }
259
264 public static function unRegister(array $bot)
265 {
266 $botId = intval($bot['BOT_ID']);
267 $moduleId = isset($bot['MODULE_ID'])? $bot['MODULE_ID']: '';
268 $appId = isset($bot['APP_ID'])? $bot['APP_ID']: '';
269
270 if (intval($botId) <= 0)
271 {
272 return false;
273 }
274
275 $bots = self::getListCache();
276 if (!isset($bots[$botId]))
277 {
278 return false;
279 }
280
281 if ($moduleId <> '' && $bots[$botId]['MODULE_ID'] != $moduleId)
282 {
283 return false;
284 }
285
286 if ($appId <> '' && $bots[$botId]['APP_ID'] != $appId)
287 {
288 return false;
289 }
290
291 \Bitrix\Im\Model\BotTable::delete($botId);
292
293 $cache = \Bitrix\Main\Data\Cache::createInstance();
294 $cache->cleanDir(self::CACHE_PATH);
295
296 $user = new \CUser;
297 $user->Delete($botId);
298
299 if (\Bitrix\Main\Loader::includeModule($bots[$botId]['MODULE_ID']) && $bots[$botId]["METHOD_BOT_DELETE"] && class_exists($bots[$botId]["CLASS"]) && method_exists($bots[$botId]["CLASS"], $bots[$botId]["METHOD_BOT_DELETE"]))
300 {
301 call_user_func_array(array($bots[$botId]["CLASS"], $bots[$botId]["METHOD_BOT_DELETE"]), Array($botId));
302 }
303
304 foreach(\Bitrix\Main\EventManager::getInstance()->findEventHandlers("im", "onImBotDelete") as $event)
305 {
306 \ExecuteModuleEventEx($event, Array($bots[$botId], $botId));
307 }
308
309 $orm = \Bitrix\Im\Model\CommandTable::getList(Array(
310 'filter' => Array('=BOT_ID' => $botId)
311 ));
312 while ($row = $orm->fetch())
313 {
314 \Bitrix\Im\Command::unRegister(Array('COMMAND_ID' => $row['ID'], 'FORCE' => 'Y'));
315 }
316
317 $orm = \Bitrix\Im\Model\AppTable::getList(Array(
318 'filter' => Array('=BOT_ID' => $botId)
319 ));
320 while ($row = $orm->fetch())
321 {
322 \Bitrix\Im\App::unRegister(Array('ID' => $row['ID'], 'FORCE' => 'Y'));
323 }
324
325 self::sendPullNotify($botId, 'botDelete');
326
327 \Bitrix\Main\Application::getInstance()->getTaggedCache()->clearByTag("IM_CONTACT_LIST");
328
329 return true;
330 }
331
337 public static function update(array $bot, array $updateFields)
338 {
339 $botId = intval($bot['BOT_ID']);
340 $moduleId = isset($bot['MODULE_ID'])? $bot['MODULE_ID']: '';
341 $appId = isset($bot['APP_ID'])? $bot['APP_ID']: '';
342
343 if ($botId <= 0)
344 {
345 return false;
346 }
347
348 if (!\Bitrix\Im\User::getInstance($botId)->isExists() || !\Bitrix\Im\User::getInstance($botId)->isBot())
349 {
350 return false;
351 }
352
353 $bots = self::getListCache();
354 if (!isset($bots[$botId]))
355 {
356 return false;
357 }
358
359 if ($moduleId <> '' && $bots[$botId]['MODULE_ID'] != $moduleId)
360 {
361 return false;
362 }
363
364 if ($appId <> '' && $bots[$botId]['APP_ID'] != $appId)
365 {
366 return false;
367 }
368
369 if (isset($updateFields['PROPERTIES']))
370 {
371 $update = $updateFields['PROPERTIES'];
372
373 $update['EXTERNAL_AUTH_ID'] = self::EXTERNAL_AUTH_ID;
374
375 if (isset($update['NAME']) && trim($update['NAME']) == '')
376 {
377 unset($update['NAME']);
378 }
379 if (isset($update['WORK_POSITION']) && trim($update['WORK_POSITION']) == '')
380 {
381 $update['WORK_POSITION'] = Loc::getMessage('BOT_DEFAULT_WORK_POSITION');
382 }
383
384 $botAvatar = false;
385 $delBotAvatar = false;
386 $previousBotAvatar = false;
387 if (
388 !empty($update['PERSONAL_PHOTO'])
389 && is_numeric($update['PERSONAL_PHOTO'])
390 && (int)$update['PERSONAL_PHOTO'] > 0
391 )
392 {
393 $previousBotAvatar = (int)\Bitrix\Im\User::getInstance($botId)->getAvatarId();
394 $botAvatar = (int)$update['PERSONAL_PHOTO'];
395 }
396 elseif (
397 !empty($update['DELETE_PERSONAL_PHOTO'])
398 && $update['DELETE_PERSONAL_PHOTO'] == 'Y'
399 )
400 {
401 $previousBotAvatar = (int)\Bitrix\Im\User::getInstance($botId)->getAvatarId();
402 $delBotAvatar = true;
403 }
404
405 // update user properties
406 unset(
407 $update['ACTIVE'],
408 $update['LOGIN'],
409 $update['PASSWORD'],
410 $update['CONFIRM_PASSWORD'],
411 $update['GROUP_ID'],
412 $update['UF_DEPARTMENT'],
413 $update['PERSONAL_PHOTO'],
414 $update['DELETE_PERSONAL_PHOTO']
415 );
416
417 $user = new \CUser;
418 $user->Update($botId, $update);
419
420 if ($botAvatar > 0 && $botAvatar !== $previousBotAvatar)
421 {
423 $connection->query("UPDATE b_user SET PERSONAL_PHOTO = ".(int)$botAvatar." WHERE ID = ".(int)$botId);
424 }
425 elseif ($delBotAvatar)
426 {
428 $connection->query("UPDATE b_user SET PERSONAL_PHOTO = null WHERE ID = ".(int)$botId);
429 }
430
431 if ($previousBotAvatar > 0)
432 {
433 \CFile::Delete($previousBotAvatar);
434 }
435 }
436
437 $update = Array();
438 if (isset($updateFields['CLASS']) && !empty($updateFields['CLASS']))
439 {
440 $update['CLASS'] = $updateFields['CLASS'];
441 }
442 if (isset($updateFields['TYPE']) && !empty($updateFields['TYPE']))
443 {
444 $update['TYPE'] = $updateFields['TYPE'];
445 }
446 if (isset($updateFields['CODE']) && !empty($updateFields['CODE']))
447 {
448 $update['CODE'] = $updateFields['CODE'];
449 }
450 if (isset($updateFields['APP_ID']) && !empty($updateFields['APP_ID']))
451 {
452 $update['APP_ID'] = $updateFields['APP_ID'];
453 }
454 if (isset($updateFields['LANG']))
455 {
456 $update['LANG'] = $updateFields['LANG']? $updateFields['LANG']: '';
457 }
458 if (isset($updateFields['METHOD_BOT_DELETE']))
459 {
460 $update['METHOD_BOT_DELETE'] = $updateFields['METHOD_BOT_DELETE'];
461 }
462 if (isset($updateFields['METHOD_MESSAGE_ADD']))
463 {
464 $update['METHOD_MESSAGE_ADD'] = $updateFields['METHOD_MESSAGE_ADD'];
465 }
466 if (isset($updateFields['METHOD_MESSAGE_UPDATE']))
467 {
468 $update['METHOD_MESSAGE_UPDATE'] = $updateFields['METHOD_MESSAGE_UPDATE'];
469 }
470 if (isset($updateFields['METHOD_MESSAGE_DELETE']))
471 {
472 $update['METHOD_MESSAGE_DELETE'] = $updateFields['METHOD_MESSAGE_DELETE'];
473 }
474 if (isset($updateFields['METHOD_WELCOME_MESSAGE']))
475 {
476 $update['METHOD_WELCOME_MESSAGE'] = $updateFields['METHOD_WELCOME_MESSAGE'];
477 }
478 if (isset($updateFields['METHOD_CONTEXT_GET']))
479 {
480 $update['METHOD_CONTEXT_GET'] = $updateFields['METHOD_CONTEXT_GET'];
481 }
482 if (isset($updateFields['TEXT_PRIVATE_WELCOME_MESSAGE']))
483 {
484 $update['TEXT_PRIVATE_WELCOME_MESSAGE'] = $updateFields['TEXT_PRIVATE_WELCOME_MESSAGE'];
485 }
486 if (isset($updateFields['TEXT_CHAT_WELCOME_MESSAGE']))
487 {
488 $update['TEXT_CHAT_WELCOME_MESSAGE'] = $updateFields['TEXT_CHAT_WELCOME_MESSAGE'];
489 }
490 if (isset($updateFields['VERIFIED']))
491 {
492 $update['VERIFIED'] = $updateFields['VERIFIED'] == 'Y'? 'Y': 'N';
493 }
494 if (isset($updateFields['HIDDEN']))
495 {
496 $update['HIDDEN'] = $updateFields['HIDDEN'] === 'Y' ? 'Y' : 'N';
497 }
498 if (isset($updateFields['BACKGROUND_ID']))
499 {
500 $update['BACKGROUND_ID'] = Background::validateBackgroundId($updateFields['BACKGROUND_ID']);
501 }
502 if (!empty($update))
503 {
504 \Bitrix\Im\Model\BotTable::update($botId, $update);
505
506 $cache = \Bitrix\Main\Data\Cache::createInstance();
507 $cache->cleanDir(self::CACHE_PATH);
508 }
509
510 self::sendPullNotify($botId, 'botUpdate');
511
512 \Bitrix\Main\Application::getInstance()->getTaggedCache()->clearByTag("IM_CONTACT_LIST");
513
514 return true;
515 }
516
523 public static function sendPullNotify($botId, $messageType): bool
524 {
525 if (!\Bitrix\Main\Loader::includeModule('pull'))
526 {
527 return false;
528 }
529
530 $botForJs = self::getListForJs();
531 if (!isset($botForJs[$botId]))
532 {
533 return false;
534 }
535
536 if ($messageType === 'botAdd' || $messageType === 'botUpdate')
537 {
538
539 $userData = \CIMContactList::GetUserData([
540 'ID' => $botId,
541 'DEPARTMENT' => 'Y',
542 'USE_CACHE' => 'N',
543 'SHOW_ONLINE' => 'N',
544 'PHONES' => 'N'
545 ]);
546
547 return \CPullStack::AddShared([
548 'module_id' => 'im',
549 'command' => $messageType,
550 'params' => [
551 'bot' => $botForJs[$botId],
552 'user' => $userData['users'][$botId],
553 'userInGroup' => $userData['userInGroup'],
554 ],
555 'extra' => \Bitrix\Im\Common::getPullExtra()
556 ]);
557 }
558 elseif ($messageType === 'botDelete')
559 {
560 return \CPullStack::AddShared([
561 'module_id' => 'im',
562 'command' => $messageType,
563 'params' => [
564 'botId' => $botId
565 ],
566 'extra' => \Bitrix\Im\Common::getPullExtra()
567 ]);
568 }
569
570 return false;
571 }
572
579 public static function sendPullOpenDialog(int $botId, int $userId = null): bool
580 {
581 if (!\Bitrix\Main\Loader::includeModule('pull'))
582 {
583 return false;
584 }
585
587 if (!$userId)
588 {
589 return false;
590 }
591
592 $botForJs = self::getListForJs();
593 if (!isset($botForJs[$botId]))
594 {
595 return false;
596 }
597
598 return \Bitrix\Pull\Event::add($userId, [
599 'module_id' => 'im',
600 'expiry' => 5,
601 'command' => 'applicationOpenChat',
602 'params' => [
603 'dialogId' => $botId
604 ],
605 'extra' => \Bitrix\Im\Common::getPullExtra()
606 ]);
607 }
608
609 public static function onMessageAdd($messageId, $messageFields)
610 {
611 $botExecModule = self::getBotsForMessage($messageFields);
612 if (!$botExecModule)
613 {
614 return true;
615 }
616
617 $messageFields = self::addAdditionalParams($messageFields);
618
619 if ($messageFields['MESSAGE_TYPE'] != IM_MESSAGE_PRIVATE)
620 {
621 $messageFields['MESSAGE_ORIGINAL'] = $messageFields['MESSAGE'];
622 if (preg_match("/\[USER=([0-9]+)( REPLACE)?](.*?)\[\/USER]/i", $messageFields['MESSAGE'], $matches))
623 {
624 $messageFields['TO_USER_ID'] = $matches[1];
625 }
626 else
627 {
628 $messageFields['TO_USER_ID'] = 0;
629 }
630 $messageFields['MESSAGE'] = trim(preg_replace('#\[(?P<tag>USER)=\d+\].+?\[/(?P=tag)\],?#', '', $messageFields['MESSAGE']));
631 }
632
633 $messageFields['DIALOG_ID'] = self::getDialogId($messageFields);
634 $messageFields = self::removeFieldsToEvent($messageFields);
635 $messageFieldsForEvents = $messageFields;
636
637 foreach ($botExecModule as $params)
638 {
639 if (!$params['MODULE_ID'] || !\Bitrix\Main\Loader::includeModule($params['MODULE_ID']))
640 {
641 continue;
642 }
643
644 $messageFields['BOT_ID'] = $params['BOT_ID'];
645
646 if ($params["METHOD_MESSAGE_ADD"] && class_exists($params["CLASS"]) && method_exists($params["CLASS"], $params["METHOD_MESSAGE_ADD"]))
647 {
648 \Bitrix\Im\Model\BotTable::update($params['BOT_ID'], array(
649 "COUNT_MESSAGE" => new \Bitrix\Main\DB\SqlExpression("?# + 1", "COUNT_MESSAGE")
650 ));
651
652 call_user_func_array(array($params["CLASS"], $params["METHOD_MESSAGE_ADD"]), Array($messageId, $messageFields));
653 }
654 else if (class_exists($params["CLASS"]) && method_exists($params["CLASS"], "onMessageAdd"))
655 {
656 call_user_func_array(array($params["CLASS"], "onMessageAdd"), Array($messageId, $messageFields));
657 }
658 }
659
660 foreach(\Bitrix\Main\EventManager::getInstance()->findEventHandlers("im", "onImBotMessageAdd") as $event)
661 {
662 $eventParams = [$botExecModule, $messageId, $messageFieldsForEvents];
663 \ExecuteModuleEventEx($event, $eventParams);
664 }
665
666 if (
667 $messageFields['CHAT_ENTITY_TYPE'] == 'LINES'
668 && trim($messageFields['MESSAGE']) === '0'
669 && \Bitrix\Main\Loader::includeModule('imopenlines')
670 )
671 {
672 $chat = new \Bitrix\Imopenlines\Chat($messageFields['TO_CHAT_ID']);
673 $chat->endBotSession();
674 }
675
676 return true;
677 }
678
680 {
681 $botExecModule = self::getBotsForMessage($messageFields);
682 if (!$botExecModule)
683 {
684 return true;
685 }
686
687 $messageFields = self::addAdditionalParams($messageFields);
688
689 if ($messageFields['MESSAGE_TYPE'] != IM_MESSAGE_PRIVATE)
690 {
691 $messageFields['MESSAGE_ORIGINAL'] = $messageFields['MESSAGE'];
692 if (preg_match("/\[USER=([0-9]+)( REPLACE)?](.*?)\[\/USER]/i", $messageFields['MESSAGE'], $matches))
693 {
694 $messageFields['TO_USER_ID'] = $matches[1];
695 }
696 else
697 {
698 $messageFields['TO_USER_ID'] = 0;
699 }
700 $messageFields['MESSAGE'] = trim(preg_replace('#\[(?P<tag>USER)=\d+\].+?\[/(?P=tag)\],?#', '', $messageFields['MESSAGE']));
701 }
702
703 $messageFields['DIALOG_ID'] = self::getDialogId($messageFields);
704 $messageFields = self::removeFieldsToEvent($messageFields);
705 $messageFieldsForEvents = $messageFields;
706
707 foreach ($botExecModule as $params)
708 {
709 if (!$params['MODULE_ID'] || !\Bitrix\Main\Loader::includeModule($params['MODULE_ID']))
710 {
711 continue;
712 }
713
714 $messageFields['BOT_ID'] = $params['BOT_ID'];
715
716 if ($params["METHOD_MESSAGE_UPDATE"] && class_exists($params["CLASS"]) && method_exists($params["CLASS"], $params["METHOD_MESSAGE_UPDATE"]))
717 {
718 call_user_func_array(array($params["CLASS"], $params["METHOD_MESSAGE_UPDATE"]), Array($messageId, $messageFields));
719 }
720 else if (class_exists($params["CLASS"]) && method_exists($params["CLASS"], "onMessageUpdate"))
721 {
722 call_user_func_array(array($params["CLASS"], "onMessageUpdate"), Array($messageId, $messageFields));
723 }
724 }
725 unset($messageFields['BOT_ID']);
726
727 foreach(\Bitrix\Main\EventManager::getInstance()->findEventHandlers("im", "onImBotMessageUpdate") as $event)
728 {
729 $eventParams = [$botExecModule, $messageId, $messageFieldsForEvents];
730
731 \ExecuteModuleEventEx($event, $eventParams);
732 }
733
734 return true;
735 }
736
738 {
739 $botExecModule = self::getBotsForMessage($messageFields);
740 if (!$botExecModule)
741 {
742 return true;
743 }
744
745 $messageFields['DIALOG_ID'] = self::getDialogId($messageFields);
746 $messageFields = self::removeFieldsToEvent($messageFields);
747
748 foreach ($botExecModule as $params)
749 {
750 if (!$params['MODULE_ID'] || !\Bitrix\Main\Loader::includeModule($params['MODULE_ID']))
751 {
752 continue;
753 }
754
755 $messageFields['BOT_ID'] = $params['BOT_ID'];
756
757 if ($params["METHOD_MESSAGE_DELETE"] && class_exists($params["CLASS"]) && method_exists($params["CLASS"], $params["METHOD_MESSAGE_DELETE"]))
758 {
759 call_user_func_array(array($params["CLASS"], $params["METHOD_MESSAGE_DELETE"]), Array($messageId, $messageFields));
760 }
761 else if (class_exists($params["CLASS"]) && method_exists($params["CLASS"], "onMessageDelete"))
762 {
763 call_user_func_array(array($params["CLASS"], "onMessageDelete"), Array($messageId, $messageFields));
764 }
765 }
766 unset($messageFields['BOT_ID']);
767
768 foreach(\Bitrix\Main\EventManager::getInstance()->findEventHandlers("im", "onImBotMessageDelete") as $event)
769 {
770 \ExecuteModuleEventEx($event, Array($botExecModule, $messageId, $messageFields));
771 }
772
773 return true;
774 }
775
776 public static function onJoinChat($dialogId, $joinFields)
777 {
778 $bots = self::getListCache();
779 if (empty($bots))
780 {
781 return true;
782 }
783
784 if (!isset($joinFields['BOT_ID']) || !$bots[$joinFields['BOT_ID']])
785 {
786 return false;
787 }
788
789 $bot = $bots[$joinFields['BOT_ID']];
790
791 if (!\Bitrix\Main\Loader::includeModule($bot['MODULE_ID']))
792 {
793 return false;
794 }
795
796 if ($joinFields['CHAT_TYPE'] == IM_MESSAGE_PRIVATE)
797 {
798 $updateCounter = array("COUNT_USER" => new \Bitrix\Main\DB\SqlExpression("?# + 1", "COUNT_USER"));
799 }
800 else
801 {
802 $updateCounter = array("COUNT_CHAT" => new \Bitrix\Main\DB\SqlExpression("?# + 1", "COUNT_CHAT"));
803 }
804 \Bitrix\Im\Model\BotTable::update($joinFields['BOT_ID'], $updateCounter);
805
806 if ($bot["METHOD_WELCOME_MESSAGE"] && class_exists($bot["CLASS"]) && method_exists($bot["CLASS"], $bot["METHOD_WELCOME_MESSAGE"]))
807 {
808 call_user_func_array(array($bot["CLASS"], $bot["METHOD_WELCOME_MESSAGE"]), Array($dialogId, $joinFields));
809 }
810 else if (
811 $bot["TEXT_PRIVATE_WELCOME_MESSAGE"] <> ''
812 && $joinFields['CHAT_TYPE'] == IM_MESSAGE_PRIVATE
813 && $joinFields['FROM_USER_ID'] != $joinFields['BOT_ID']
814 )
815 {
816 if ($bot['TYPE'] == self::TYPE_HUMAN)
817 {
818 self::startWriting(Array('BOT_ID' => $joinFields['BOT_ID']), $dialogId);
819 }
820
821 $userName = \Bitrix\Im\User::getInstance($joinFields['USER_ID'])->getName();
822 self::addMessage(Array('BOT_ID' => $joinFields['BOT_ID']), Array(
823 'DIALOG_ID' => $dialogId,
824 'MESSAGE' => str_replace(Array('#USER_NAME#'), Array($userName), $bot["TEXT_PRIVATE_WELCOME_MESSAGE"]),
825 ));
826 }
827 else if (
828 $bot["TEXT_CHAT_WELCOME_MESSAGE"] <> ''
829 && in_array($joinFields['CHAT_TYPE'], \CIMChat::getGroupTypesExtra())
830 && $joinFields['FROM_USER_ID'] != $joinFields['BOT_ID']
831 )
832 {
833 if ($bot['TYPE'] == self::TYPE_HUMAN)
834 {
835 self::startWriting(Array('BOT_ID' => $joinFields['BOT_ID']), $dialogId);
836 }
837 $userName = \Bitrix\Im\User::getInstance($joinFields['USER_ID'])->getName();
838 self::addMessage(Array('BOT_ID' => $joinFields['BOT_ID']), Array(
839 'DIALOG_ID' => $dialogId,
840 'MESSAGE' => str_replace(Array('#USER_NAME#'), Array($userName), $bot["TEXT_CHAT_WELCOME_MESSAGE"]),
841 ));
842 }
843
844 foreach(\Bitrix\Main\EventManager::getInstance()->findEventHandlers("im", "onImBotJoinChat") as $event)
845 {
846 \ExecuteModuleEventEx($event, Array($bot, $dialogId, $joinFields));
847 }
848
849 return true;
850 }
851
852 public static function onLeaveChat($dialogId, $leaveFields)
853 {
854 $bots = self::getListCache();
855 if (empty($bots))
856 {
857 return true;
858 }
859
860 if (!isset($leaveFields['BOT_ID']) || !$bots[$leaveFields['BOT_ID']])
861 {
862 return false;
863 }
864
865 $bot = $bots[$leaveFields['BOT_ID']];
866
867 if (!\Bitrix\Main\Loader::includeModule($bot['MODULE_ID']))
868 {
869 return false;
870 }
871
872 if ($leaveFields['CHAT_TYPE'] == IM_MESSAGE_PRIVATE)
873 {
874 $updateCounter = array("COUNT_USER" => new \Bitrix\Main\DB\SqlExpression("?# - 1", "COUNT_USER"));
875 }
876 else
877 {
878 $updateCounter = array("COUNT_CHAT" => new \Bitrix\Main\DB\SqlExpression("?# - 1", "COUNT_CHAT"));
879 }
880 \Bitrix\Im\Model\BotTable::update($leaveFields['BOT_ID'], $updateCounter);
881
882 foreach(\Bitrix\Main\EventManager::getInstance()->findEventHandlers("im", "onImBotLeaveChat") as $event)
883 {
884 \ExecuteModuleEventEx($event, Array($bot, $dialogId, $leaveFields));
885 }
886
887 return true;
888 }
889
890 public static function onContextGet(\Bitrix\Im\V2\Chat $chat, array $params): bool
891 {
892 $botsForEvent = [];
893 $botList = $chat->getBotInChat();
894
895 $dialogId = self::getDialogIdByChat($chat);
896 if ($dialogId === null)
897 {
898 return false;
899 }
900
901 foreach ($botList as $botId)
902 {
903 $botData = BotData::getInstance($botId)?->getBotData();
904 if (
905 empty($botData)
906 || !\Bitrix\Main\Loader::includeModule($botData['MODULE_ID'])
907 )
908 {
909 continue;
910 }
911
912 $botsForEvent[$botId] = $botData;
913
914 if ($botData["METHOD_CONTEXT_GET"] && class_exists($botData["CLASS"]) && method_exists($botData["CLASS"], $botData["METHOD_CONTEXT_GET"]))
915 {
916 call_user_func([$botData["CLASS"], $botData["METHOD_CONTEXT_GET"]], $dialogId, $params);
917 }
918 else if (class_exists($botData["CLASS"]) && method_exists($botData["CLASS"], "onContextGet"))
919 {
920 call_user_func([$botData["CLASS"], "onContextGet"], $dialogId, $params);
921 }
922 }
923
924 if (empty($botsForEvent))
925 {
926 return false;
927 }
928
929 foreach(\Bitrix\Main\EventManager::getInstance()->findEventHandlers("im", "onImBotContextGet") as $event)
930 {
931 \ExecuteModuleEventEx($event, [$botsForEvent, $dialogId, $params]);
932 }
933
934 return true;
935 }
936
937 protected static function addAdditionalParams(array $params): array
938 {
939 $chatId = $params['TO_CHAT_ID'] ?? $params['CHAT_ID'] ?? null;
940 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
941
942 if ($chat instanceof PrivateChat)
943 {
944 $params['CHAT_USER_COUNT'] = 2;
945 }
946 else
947 {
948 $params['CHAT_USER_COUNT'] = $chat->getUserCount();
949 }
950
951 $params['MENTIONED_LIST'] = (new Message())
952 ->setMessage($params['MESSAGE'] ?? '')
953 ->getUserIdsFromMention()
954 ;
955
956 $params['PLATFORM_CONTEXT'] = self::getPlatformContext();
957
958 return $params;
959 }
960
961 public static function startWriting(array $bot, $dialogId, $userName = '')
962 {
963 $botId = $bot['BOT_ID'];
964 $moduleId = isset($bot['MODULE_ID'])? $bot['MODULE_ID']: '';
965 $appId = isset($bot['APP_ID'])? $bot['APP_ID']: '';
966
967 if (intval($botId) <= 0)
968 {
969 return false;
970 }
971
972 if (!\Bitrix\Im\User::getInstance($botId)->isExists() || !\Bitrix\Im\User::getInstance($botId)->isBot())
973 {
974 return false;
975 }
976
977 $bots = self::getListCache();
978 if (!isset($bots[$botId]))
979 {
980 return false;
981 }
982
983 if ($moduleId <> '' && $bots[$botId]['MODULE_ID'] != $moduleId)
984 {
985 return false;
986 }
987
988 if ($appId <> '' && $bots[$botId]['APP_ID'] != $appId)
989 {
990 return false;
991 }
992
993 \CIMMessenger::StartWriting($dialogId, $botId, $userName);
994
995 return true;
996 }
997
998 public static function setChatBackgroundId(array $bot, $dialogId, string $backgroundId): bool
999 {
1000 $botId = (int)$bot['BOT_ID'];
1001
1002 if (!self::checkBotValid($botId))
1003 {
1004 return false;
1005 }
1006
1007 $chatId = Dialog::getChatId($dialogId, $botId);
1008 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
1009 if ($chat->getRelationByUserId($botId) === null)
1010 {
1011 return false;
1012 }
1013
1014 $chat->getBackground()->set($backgroundId);
1015
1016 return true;
1017 }
1018
1019 public static function enableChatTextField(array $bot, $dialogId): bool
1020 {
1021 return self::changeChatTextFieldInternal($bot, $dialogId, true);
1022 }
1023
1024 public static function disableChatTextField(array $bot, $dialogId): bool
1025 {
1026 return self::changeChatTextFieldInternal($bot, $dialogId, false);
1027 }
1028
1029 private static function changeChatTextFieldInternal(array $bot, $dialogId, bool $textFieldEnabled): bool
1030 {
1031 $botId = (int)$bot['BOT_ID'];
1032
1033 if (!self::checkBotValid($botId))
1034 {
1035 return false;
1036 }
1037
1038 $chatId = Dialog::getChatId($dialogId, $botId);
1039 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
1040 if ($chat->getRelationByUserId($botId) === null)
1041 {
1042 return false;
1043 }
1044
1045 $chat->getTextFieldEnabled()->set($textFieldEnabled);
1046
1047 return true;
1048 }
1049
1050 private static function checkBotValid(int $botId): bool
1051 {
1052 if ($botId <= 0)
1053 {
1054 return false;
1055 }
1056
1057 if (!\Bitrix\Im\User::getInstance($botId)->isExists() || !\Bitrix\Im\User::getInstance($botId)->isBot())
1058 {
1059 return false;
1060 }
1061
1062 $botData = BotData::getInstance($botId)?->getBotData();
1063 if (!isset($botData))
1064 {
1065 return false;
1066 }
1067
1068 return true;
1069 }
1070
1101 public static function addMessage(array $bot, array $messageFields)
1102 {
1103 $botId = $bot['BOT_ID'];
1104 $moduleId = isset($bot['MODULE_ID'])? $bot['MODULE_ID']: '';
1105 $appId = isset($bot['APP_ID'])? $bot['APP_ID']: '';
1106
1107 if (intval($botId) <= 0)
1108 {
1109 return false;
1110 }
1111
1112 if (!\Bitrix\Im\User::getInstance($botId)->isExists() || !\Bitrix\Im\User::getInstance($botId)->isBot())
1113 {
1114 return false;
1115 }
1116
1117 $bots = self::getListCache();
1118 if (!isset($bots[$botId]))
1119 {
1120 return false;
1121 }
1122
1123 if ($moduleId <> '' && $bots[$botId]['MODULE_ID'] != $moduleId)
1124 {
1125 return false;
1126 }
1127
1128 if ($appId <> '' && $bots[$botId]['APP_ID'] != $appId)
1129 {
1130 return false;
1131 }
1132
1133 $isPrivateSystem = false;
1134 if (($messageFields['FROM_USER_ID'] ?? null) && ($messageFields['TO_USER_ID'] ?? null))
1135 {
1136 $messageFields['SYSTEM'] = 'Y';
1137 $messageFields['DIALOG_ID'] = $messageFields['TO_USER_ID'];
1138 $isPrivateSystem = true;
1139 }
1140 else if (empty($messageFields['DIALOG_ID']))
1141 {
1142 return false;
1143 }
1144
1145 $messageFields['MENU'] ??= null;
1146 $messageFields['ATTACH'] ??= null;
1147 $messageFields['KEYBOARD'] ??= null;
1148 $messageFields['PARAMS'] ??= [];
1149
1150 if (Common::isChatId($messageFields['DIALOG_ID']))
1151 {
1152 $chatId = \Bitrix\Im\Dialog::getChatId($messageFields['DIALOG_ID']);
1153 if ($chatId <= 0)
1154 {
1155 return false;
1156 }
1157
1158 if (\CIMChat::GetGeneralChatId() == $chatId && !\CIMChat::CanSendMessageToGeneralChat($botId))
1159 {
1160 return false;
1161 }
1162 else
1163 {
1164 $ar = Array(
1165 "FROM_USER_ID" => $botId,
1166 "TO_CHAT_ID" => $chatId,
1167 "ATTACH" => $messageFields['ATTACH'],
1168 "KEYBOARD" => $messageFields['KEYBOARD'],
1169 "MENU" => $messageFields['MENU'],
1170 "PARAMS" => $messageFields['PARAMS'],
1171 );
1172 if (isset($messageFields['MESSAGE']) && (!empty($messageFields['MESSAGE']) || $messageFields['MESSAGE'] === "0"))
1173 {
1174 $ar['MESSAGE'] = $messageFields['MESSAGE'];
1175 }
1176 if (isset($messageFields['SYSTEM']) && $messageFields['SYSTEM'] == 'Y')
1177 {
1178 $ar['SYSTEM'] = 'Y';
1179 $ar['MESSAGE'] = \Bitrix\Im\User::getInstance($botId)->getFullName().":[br]".$ar['MESSAGE'];
1180 }
1181 if (isset($messageFields['URL_PREVIEW']) && $messageFields['URL_PREVIEW'] == 'N')
1182 {
1183 $ar['URL_PREVIEW'] = 'N';
1184 }
1185 if (isset($messageFields['SKIP_CONNECTOR']) && $messageFields['SKIP_CONNECTOR'] == 'Y')
1186 {
1187 $ar['SKIP_CONNECTOR'] = 'Y';
1188 $ar['SILENT_CONNECTOR'] = 'Y';
1189 }
1190 $ar['SKIP_COMMAND'] = 'Y';
1191 $id = \CIMChat::AddMessage($ar);
1192 }
1193 }
1194 else
1195 {
1196 if ($isPrivateSystem)
1197 {
1198 $fromUserId = intval($messageFields['FROM_USER_ID']);
1199 if ($botId > 0)
1200 {
1201 $messageFields['MESSAGE'] = Loc::getMessage("BOT_MESSAGE_FROM", Array("#BOT_NAME#" => "[USER=".$botId."][/USER][BR]")).$messageFields['MESSAGE'];
1202 }
1203 }
1204 else
1205 {
1206 $fromUserId = $botId;
1207 }
1208
1209 $userId = intval($messageFields['DIALOG_ID']);
1210 $ar = Array(
1211 "FROM_USER_ID" => $fromUserId,
1212 "TO_USER_ID" => $userId,
1213 "ATTACH" => $messageFields['ATTACH'],
1214 "KEYBOARD" => $messageFields['KEYBOARD'],
1215 "MENU" => $messageFields['MENU'],
1216 "PARAMS" => $messageFields['PARAMS'],
1217 );
1218 if (isset($messageFields['MESSAGE']) && (!empty($messageFields['MESSAGE']) || $messageFields['MESSAGE'] === "0"))
1219 {
1220 $ar['MESSAGE'] = $messageFields['MESSAGE'];
1221 }
1222 if (isset($messageFields['SYSTEM']) && $messageFields['SYSTEM'] == 'Y')
1223 {
1224 $ar['SYSTEM'] = 'Y';
1225 }
1226 if (isset($messageFields['URL_PREVIEW']) && $messageFields['URL_PREVIEW'] == 'N')
1227 {
1228 $ar['URL_PREVIEW'] = 'N';
1229 }
1230 if (isset($messageFields['SKIP_CONNECTOR']) && $messageFields['SKIP_CONNECTOR'] == 'Y')
1231 {
1232 $ar['SKIP_CONNECTOR'] = 'Y';
1233 $ar['SILENT_CONNECTOR'] = 'Y';
1234 }
1235 $ar['SKIP_COMMAND'] = 'Y';
1236 $id = \CIMMessage::Add($ar);
1237 }
1238
1239 return $id;
1240 }
1241
1267 public static function updateMessage(array $bot, array $messageFields)
1268 {
1269 $botId = $bot['BOT_ID'];
1270 $moduleId = isset($bot['MODULE_ID'])? $bot['MODULE_ID']: '';
1271 $appId = isset($bot['APP_ID'])? $bot['APP_ID']: '';
1272
1273 if (intval($botId) <= 0)
1274 return false;
1275
1276 if (!\Bitrix\Im\User::getInstance($botId)->isExists() || !\Bitrix\Im\User::getInstance($botId)->isBot())
1277 return false;
1278
1279 $bots = self::getListCache();
1280 if (!isset($bots[$botId]))
1281 return false;
1282
1283 if ($moduleId <> '' && $bots[$botId]['MODULE_ID'] != $moduleId)
1284 return false;
1285
1286 if ($appId <> '' && $bots[$botId]['APP_ID'] != $appId)
1287 return false;
1288
1289 $messageId = intval($messageFields['MESSAGE_ID']);
1290 if ($messageId <= 0)
1291 return false;
1292
1293 $message = \CIMMessenger::CheckPossibilityUpdateMessage(IM_CHECK_UPDATE, $messageId, $botId);
1294 if (!$message)
1295 return false;
1296
1297 if (isset($messageFields['ATTACH']))
1298 {
1299 if (empty($messageFields['ATTACH']) || $messageFields['ATTACH'] == 'N')
1300 {
1301 \CIMMessageParam::Set($messageId, Array('ATTACH' => Array()));
1302 }
1303 else if ($messageFields['ATTACH'] instanceof \CIMMessageParamAttach)
1304 {
1305 if ($messageFields['ATTACH']->IsAllowSize())
1306 {
1307 \CIMMessageParam::Set($messageId, Array('ATTACH' => $messageFields['ATTACH']));
1308 }
1309 }
1310 }
1311
1312 if (isset($messageFields['KEYBOARD']))
1313 {
1314 if (empty($messageFields['KEYBOARD']) || $messageFields['KEYBOARD'] == 'N')
1315 {
1316 \CIMMessageParam::Set($messageId, Array('KEYBOARD' => 'N'));
1317 }
1318 else if ($messageFields['KEYBOARD'] instanceof \Bitrix\Im\Bot\Keyboard)
1319 {
1320 if ($messageFields['KEYBOARD']->isAllowSize())
1321 {
1322 \CIMMessageParam::Set($messageId, Array('KEYBOARD' => $messageFields['KEYBOARD']));
1323 }
1324 }
1325 }
1326
1327 if (isset($messageFields['MENU']))
1328 {
1329 if (empty($messageFields['MENU']) || $messageFields['MENU'] == 'N')
1330 {
1331 \CIMMessageParam::Set($messageId, Array('MENU' => 'N'));
1332 }
1333 else if ($messageFields['MENU'] instanceof \Bitrix\Im\Bot\ContextMenu)
1334 {
1335 if ($messageFields['MENU']->isAllowSize())
1336 {
1337 \CIMMessageParam::Set($messageId, Array('MENU' => $messageFields['MENU']));
1338 }
1339 }
1340 }
1341
1342 if (isset($messageFields['MESSAGE']))
1343 {
1344 $urlPreview = isset($messageFields['URL_PREVIEW']) && $messageFields['URL_PREVIEW'] == "N"? false: true;
1345 $skipConnector = isset($messageFields['SKIP_CONNECTOR']) && $messageFields['SKIP_CONNECTOR'] == "Y"? true: false;
1346 $editFlag = isset($messageFields['EDIT_FLAG']) && $messageFields['EDIT_FLAG'] == "Y"? true: false;
1347
1348 $res = \CIMMessenger::Update($messageId, $messageFields['MESSAGE'], $urlPreview, $editFlag, $botId, $skipConnector);
1349 if (!$res)
1350 {
1351 return false;
1352 }
1353 }
1354 \CIMMessageParam::SendPull($messageId, Array('KEYBOARD', 'ATTACH', 'MENU'));
1355
1356 return true;
1357 }
1358
1359 public static function deleteMessage(array $bot, $messageId)
1360 {
1361 $botId = $bot['BOT_ID'];
1362 $moduleId = isset($bot['MODULE_ID'])? $bot['MODULE_ID']: '';
1363 $appId = isset($bot['APP_ID'])? $bot['APP_ID']: '';
1364
1365 $messageId = intval($messageId);
1366 if ($messageId <= 0)
1367 return false;
1368
1369 if (intval($botId) <= 0)
1370 return false;
1371
1372 if (!\Bitrix\Im\User::getInstance($botId)->isExists() || !\Bitrix\Im\User::getInstance($botId)->isBot())
1373 return false;
1374
1375 $bots = self::getListCache();
1376 if (!isset($bots[$botId]))
1377 return false;
1378
1379 if ($moduleId <> '' && $bots[$botId]['MODULE_ID'] != $moduleId)
1380 return false;
1381
1382 if ($appId <> '' && $bots[$botId]['APP_ID'] != $appId)
1383 return false;
1384
1385 return \CIMMessenger::Delete($messageId, $botId);
1386 }
1387
1388 public static function likeMessage(array $bot, $messageId, $action = 'AUTO')
1389 {
1390 $botId = $bot['BOT_ID'];
1391 $moduleId = isset($bot['MODULE_ID'])? $bot['MODULE_ID']: '';
1392 $appId = isset($bot['APP_ID'])? $bot['APP_ID']: '';
1393
1394 $messageId = intval($messageId);
1395 if ($messageId <= 0)
1396 return false;
1397
1398 if (intval($botId) <= 0)
1399 return false;
1400
1401 if (!\Bitrix\Im\User::getInstance($botId)->isExists() || !\Bitrix\Im\User::getInstance($botId)->isBot())
1402 return false;
1403
1404 $bots = self::getListCache();
1405 if (!isset($bots[$botId]))
1406 return false;
1407
1408 if ($moduleId <> '' && $bots[$botId]['MODULE_ID'] != $moduleId)
1409 return false;
1410
1411 if ($appId <> '' && $bots[$botId]['APP_ID'] != $appId)
1412 return false;
1413
1414 return \CIMMessenger::Like($messageId, $action, $botId);
1415 }
1416
1417 public static function getDialogId($messageFields)
1418 {
1419 if ($messageFields['MESSAGE_TYPE'] == IM_MESSAGE_PRIVATE)
1420 {
1421 $dialogId = $messageFields['FROM_USER_ID'];
1422 }
1423 else
1424 {
1425 $dialogId = 'chat'.($messageFields['TO_CHAT_ID'] ?? $messageFields['CHAT_ID']);
1426 }
1427
1428 return $dialogId;
1429 }
1430
1431 public static function getDialogIdByChat(\Bitrix\Im\V2\Chat $chat): ?string
1432 {
1433 if ($chat instanceof PrivateChat)
1434 {
1435 return (string)$chat->getContext()->getUserId();
1436 }
1437
1438 return $chat->getDialogId();
1439 }
1440
1441 public static function getCache($botId)
1442 {
1443 $botList = self::getListCache();
1444 return isset($botList[$botId])? $botList[$botId]: false;
1445 }
1446
1447 public static function clearCache()
1448 {
1449 $cache = \Bitrix\Main\Data\Cache::createInstance();
1450 $cache->cleanDir(self::CACHE_PATH);
1451
1452 return true;
1453 }
1454
1455 public static function getListCache($type = self::LIST_ALL)
1456 {
1457 $cache = \Bitrix\Main\Data\Cache::createInstance();
1458 if($cache->initCache(self::CACHE_TTL, 'list_r5', self::CACHE_PATH))
1459 {
1460 $result = $cache->getVars();
1461 }
1462 else
1463 {
1464 $result = Array();
1465 $orm = \Bitrix\Im\Model\BotTable::getList();
1466 while ($row = $orm->fetch())
1467 {
1468 $row['LANG'] = $row['LANG']? $row['LANG']: null;
1469 $result[$row['BOT_ID']] = $row;
1470 }
1471
1472 $cache->startDataCache();
1473 $cache->endDataCache($result);
1474 }
1475
1476 if ($type == self::LIST_OPENLINE)
1477 {
1478 foreach ($result as $botId => $botData)
1479 {
1480 if ($botData['OPENLINE'] != 'Y' || $botData['CODE'] == 'marta')
1481 {
1482 unset($result[$botId]);
1483 }
1484 }
1485 }
1486
1487 return $result;
1488 }
1489
1490 public static function getListForJs()
1491 {
1492 $result = Array();
1493 $bots = self::getListCache();
1494 foreach ($bots as $bot)
1495 {
1496 $type = 'bot';
1497 $code = $bot['CODE'];
1498
1499 if ($bot['TYPE'] == self::TYPE_NETWORK)
1500 {
1501 $type = 'network';
1502
1503 if (
1504 $bot['CLASS'] == \Bitrix\ImBot\Bot\Support24::class
1505 || $bot['CLASS'] == \Bitrix\ImBot\Bot\SaleSupport24::class
1506 )
1507 {
1508 $type = 'support24';
1509 $code = 'network_cloud';
1510 }
1511 else if ($bot['CLASS'] == \Bitrix\ImBot\Bot\Partner24::class)
1512 {
1513 $type = 'support24';
1514 $code = 'network_partner';
1515 }
1516 else if ($bot['CLASS'] == \Bitrix\ImBot\Bot\SupportBox::class)
1517 {
1518 $type = 'support24';
1519 $code = 'network_box';
1520 }
1521 }
1522 else if ($bot['TYPE'] == self::TYPE_OPENLINE)
1523 {
1524 $type = 'openline';
1525 }
1526 else if ($bot['TYPE'] == self::TYPE_SUPERVISOR)
1527 {
1528 $type = 'supervisor';
1529 }
1530
1531 $result[$bot['BOT_ID']] = Array(
1532 'id' => $bot['BOT_ID'],
1533 'code' => $code,
1534 'type' => $type,
1535 'openline' => $bot['OPENLINE'] == 'Y',
1536 'backgroundId' => $bot['BACKGROUND_ID'] ?? null,
1537 );
1538 }
1539
1540 return $result;
1541 }
1542
1543 private static function removeFieldsToEvent($messageFields)
1544 {
1545 unset(
1546 $messageFields['BOT_IN_CHAT'],
1547 $messageFields['MESSAGE_OUT'],
1548 $messageFields['NOTIFY_EVENT'],
1549 $messageFields['NOTIFY_MODULE'],
1550 $messageFields['URL_PREVIEW'],
1551 $messageFields['DATE_CREATE'],
1552 $messageFields['EMAIL_TEMPLATE'],
1553 $messageFields['RECENT_ADD'],
1554 $messageFields['SKIP_USER_CHECK'],
1555 $messageFields['DATE_CREATE'],
1556 $messageFields['EMAIL_TEMPLATE'],
1557 $messageFields['NOTIFY_TYPE'],
1558 $messageFields['NOTIFY_TAG'],
1559 $messageFields['NOTIFY_TITLE'],
1560 $messageFields['NOTIFY_BUTTONS'],
1561 $messageFields['NOTIFY_READ'],
1562 $messageFields['NOTIFY_READ'],
1563 $messageFields['IMPORT_ID'],
1564 $messageFields['NOTIFY_SUB_TAG'],
1565 $messageFields['CHAT_PARENT_ID'],
1566 $messageFields['CHAT_PARENT_MID'],
1567 $messageFields['DATE_MODIFY']
1568 );
1569
1570 return $messageFields;
1571 }
1572
1573 public static function getDefaultLanguage()
1574 {
1575 $cache = \Bitrix\Main\Data\Cache::createInstance();
1576 if($cache->initCache(self::CACHE_TTL, 'language_v2', '/bx/im/'))
1577 {
1578 $languageId = $cache->getVars();
1579 }
1580 else
1581 {
1583 $languageId = '';
1585 'select' => array('LID', 'LANGUAGE_ID'),
1586 'filter' => array('=DEF' => 'Y', '=ACTIVE' => 'Y'),
1587 'cache' => ['ttl' => 86400],
1588 ));
1589 if ($site = $siteIterator->fetch())
1590 $languageId = (string)$site['LANGUAGE_ID'];
1591
1592 if ($languageId == '')
1593 {
1594 if (\Bitrix\Main\Loader::includeModule('bitrix24'))
1595 {
1596 $languageId = \CBitrix24::getLicensePrefix();
1597 }
1598 else
1599 {
1600 $languageId = LANGUAGE_ID;
1601 }
1602 }
1603 if ($languageId == '')
1604 {
1605 $languageId = 'en';
1606 }
1607
1608 $languageId = mb_strtolower($languageId);
1609
1610 $cache->startDataCache();
1611 $cache->endDataCache($languageId);
1612 }
1613
1614 return $languageId;
1615 }
1616
1617 public static function deleteExpiredTokenAgent(): string
1618 {
1619 $orm = \Bitrix\Im\Model\BotTokenTable::getList(Array(
1620 'filter' => array(
1621 '<DATE_EXPIRE' => new \Bitrix\Main\Type\DateTime(),
1622 ),
1623 'select' => array('ID'),
1624 'limit' => 1
1625 ));
1626 if ($token = $orm->fetch())
1627 {
1629 $connection = $application->getConnection();
1630 $sqlHelper = $connection->getSqlHelper();
1631 $connection->query("
1632 DELETE FROM b_im_bot_token
1633 WHERE DATE_EXPIRE < ".$sqlHelper->getCurrentDateTimeFunction()."
1634 ");
1635 }
1636
1637 return __METHOD__. '();';
1638 }
1639
1644 private static function getBotsForMessage($messageFields): array
1645 {
1646 $bots = self::getListCache();
1647 if (empty($bots))
1648 {
1649 return [];
1650 }
1651
1652 if (isset($messageFields['FROM_USER_ID'], $bots[$messageFields['FROM_USER_ID']]))
1653 {
1654 return [];
1655 }
1656 if (
1657 $messageFields['MESSAGE_TYPE'] === \IM_MESSAGE_CHAT
1658 && $messageFields['CHAT_ENTITY_TYPE'] === 'SUPPORT24_QUESTION'
1659 && isset($bots[$messageFields['AUTHOR_ID']])
1660 )
1661 {
1662 return [];
1663 }
1664
1665 $botExecModule = [];
1666 if ($messageFields['MESSAGE_TYPE'] === \IM_MESSAGE_PRIVATE)
1667 {
1668 if (isset($bots[$messageFields['TO_USER_ID']]))
1669 {
1670 $botExecModule[$messageFields['TO_USER_ID']] = $bots[$messageFields['TO_USER_ID']];
1671 }
1672 }
1673 else
1674 {
1675 $botFound = [];
1676 $message = $messageFields['MESSAGE'] ?? null;
1677 if (
1678 $messageFields['CHAT_ENTITY_TYPE'] === 'LINES'
1679 || $messageFields['CHAT_ENTITY_TYPE'] === 'SUPPORT24_QUESTION'
1680 || $messageFields['CHAT_ENTITY_TYPE'] === 'NETWORK_DIALOG'
1681 )
1682 {
1683 $botFound = $messageFields['BOT_IN_CHAT'];
1684 }
1685 else if (preg_match_all("/\[USER=([0-9]+)( REPLACE)?](.*?)\[\/USER]/i", $message, $matches))
1686 {
1687 foreach ($matches[1] as $userId)
1688 {
1689 if (isset($bots[$userId]) && isset($messageFields['BOT_IN_CHAT'][$userId]))
1690 {
1691 $botFound[$userId] = $userId;
1692 }
1693 }
1694 }
1695
1696 foreach ($messageFields['BOT_IN_CHAT'] as $botId)
1697 {
1698 if (isset($bots[$botId]) && $bots[$botId]['TYPE'] == self::TYPE_SUPERVISOR)
1699 {
1700 $botFound[$botId] = $botId;
1701 }
1702 }
1703
1704 if (!empty($botFound))
1705 {
1706 foreach ($botFound as $botId)
1707 {
1708 if (!isset($bots[$botId]))
1709 {
1710 continue;
1711 }
1712 if ($messageFields['CHAT_ENTITY_TYPE'] == 'LINES' && $bots[$botId]['OPENLINE'] == 'N')
1713 {
1714 continue;
1715 }
1716 $botExecModule[$botId] = $bots[$botId];
1717 }
1718 }
1719 }
1720
1721 return $botExecModule;
1722 }
1723
1724 public static function setPlatformContext(string $context): void
1725 {
1726 self::$platformContext = self::resolvePlatformContext($context);
1727 }
1728
1729 protected static function resolvePlatformContext(string $context): string
1730 {
1731 return match ($context)
1732 {
1733 'Bitrix24.Mobile', self::PLATFORM_CONTEXT_MOBILE => self::PLATFORM_CONTEXT_MOBILE,
1734 default => self::PLATFORM_CONTEXT_WEB,
1735 };
1736 }
1737
1738 protected static function getPlatformContext(): string
1739 {
1740 if (self::$platformContext !== null)
1741 {
1742 return self::$platformContext;
1743 }
1744
1745 $context = Main\Web\UserAgent\Browser::detect()->getName() ?? '';
1746 self::$platformContext = self::resolvePlatformContext($context);
1747
1748 return self::$platformContext;
1749 }
1750}
$connection
Определения actionsdefinitions.php:38
$type
Определения options.php:106
$messageFields
Определения callback_ednaru.php:22
if(! $messageFields||!isset($messageFields['message_id'])||!isset($messageFields['status'])||!CModule::IncludeModule("messageservice")) $messageId
Определения callback_ismscenter.php:26
if(!is_object($USER)||! $USER->IsAuthorized()) $userId
Определения check_mail.php:18
static unRegister(array $app)
Определения app.php:191
static setPlatformContext(string $context)
Определения bot.php:1724
static string $platformContext
Определения bot.php:44
const TYPE_OPENLINE
Определения bot.php:36
const INSTALL_TYPE_SILENT
Определения bot.php:24
static onContextGet(\Bitrix\Im\V2\Chat $chat, array $params)
Определения bot.php:890
const LIST_ALL
Определения bot.php:29
static unRegister(array $bot)
Определения bot.php:264
static addMessage(array $bot, array $messageFields)
Определения bot.php:1101
static sendPullOpenDialog(int $botId, int $userId=null)
Определения bot.php:579
const CACHE_PATH
Определения bot.php:39
static getListForJs()
Определения bot.php:1490
static onLeaveChat($dialogId, $leaveFields)
Определения bot.php:852
static onMessageAdd($messageId, $messageFields)
Определения bot.php:609
static setChatBackgroundId(array $bot, $dialogId, string $backgroundId)
Определения bot.php:998
const TYPE_BOT
Определения bot.php:33
const TYPE_NETWORK
Определения bot.php:35
const INSTALL_TYPE_SYSTEM
Определения bot.php:22
static update(array $bot, array $updateFields)
Определения bot.php:337
static getCache($botId)
Определения bot.php:1441
static getDefaultLanguage()
Определения bot.php:1573
const PLATFORM_CONTEXT_MOBILE
Определения bot.php:41
const BACKGROUND_COLLAB
Определения bot.php:19
const INSTALL_TYPE_USER
Определения bot.php:23
static onMessageUpdate($messageId, $messageFields)
Определения bot.php:679
const EXTERNAL_AUTH_ID
Определения bot.php:27
const BACKGROUND_MARTA
Определения bot.php:17
static addAdditionalParams(array $params)
Определения bot.php:937
static onMessageDelete($messageId, $messageFields)
Определения bot.php:737
static deleteMessage(array $bot, $messageId)
Определения bot.php:1359
static deleteExpiredTokenAgent()
Определения bot.php:1617
static enableChatTextField(array $bot, $dialogId)
Определения bot.php:1019
const BACKGROUND_COPILOT
Определения bot.php:18
static disableChatTextField(array $bot, $dialogId)
Определения bot.php:1024
const CACHE_TTL
Определения bot.php:38
static sendPullNotify($botId, $messageType)
Определения bot.php:523
static getDialogId($messageFields)
Определения bot.php:1417
static likeMessage(array $bot, $messageId, $action='AUTO')
Определения bot.php:1388
const LIST_OPENLINE
Определения bot.php:30
const PLATFORM_CONTEXT_WEB
Определения bot.php:42
const TYPE_SUPERVISOR
Определения bot.php:34
static getListCache($type=self::LIST_ALL)
Определения bot.php:1455
static startWriting(array $bot, $dialogId, $userName='')
Определения bot.php:961
static resolvePlatformContext(string $context)
Определения bot.php:1729
const BACKGROUND_NONE
Определения bot.php:20
static onJoinChat($dialogId, $joinFields)
Определения bot.php:776
const TYPE_HUMAN
Определения bot.php:32
static getPlatformContext()
Определения bot.php:1738
static getDialogIdByChat(\Bitrix\Im\V2\Chat $chat)
Определения bot.php:1431
static updateMessage(array $bot, array $messageFields)
Определения bot.php:1267
static clearCache()
Определения bot.php:1447
const LOGIN_START
Определения bot.php:26
static unRegister(array $command)
Определения command.php:147
static isChatId($id)
Определения common.php:58
static getPullExtra()
Определения common.php:127
static getUserId($userId=null)
Определения common.php:73
static getChatId($dialogId, $userId=null)
Определения dialog.php:93
static getInstance($userId=null)
Определения user.php:45
static getInstance(?int $id)
Определения BotData.php:34
static getInstance()
Определения application.php:98
static getConnection($name="")
Определения application.php:638
static getInstance()
Определения eventmanager.php:31
static getList(array $parameters=array())
Определения datamanager.php:431
static detect(?string $userAgent=null)
Определения browser.php:113
static Add($arFields)
Определения im_message.php:28
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
$res
Определения filter_act.php:7
$result
Определения get_property_values.php:14
$moduleId
const IM_CHECK_UPDATE
Определения include.php:69
const IM_MESSAGE_CHAT
Определения include.php:23
const IM_MESSAGE_PRIVATE
Определения include.php:22
global $USER
Определения csv_new_run.php:40
$context
Определения csv_new_setup.php:223
if(!is_null($config))($config as $configItem)(! $configItem->isVisible()) $code
Определения options.php:195
$application
Определения bitrix.php:23
ExecuteModuleEventEx($arEvent, $arParams=[])
Определения tools.php:5214
randString($pass_len=10, $pass_chars=false)
Определения tools.php:2154
Определения contextmenu.php:9
Определения Uuid.php:3
Определения ActionUuid.php:3
Определения arrayresult.php:2
Определения collection.php:2
$user
Определения mysql_to_pgsql.php:33
$message
Определения payment.php:8
$event
Определения prolog_after.php:141
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
$ar
Определения options.php:199
else $userName
Определения order_form.php:75
if($inWords) echo htmlspecialcharsbx(Number2Word_Rus(roundEx($totalVatSum $params['CURRENCY']
Определения template.php:799
$siteIterator
Определения options.php:48
$matches
Определения index.php:22
$action
Определения file_dialog.php:21
$site
Определения yandex_run.php:614
$fields
Определения yandex_run.php:501