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