1
0

BxDolAiQuery.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaCore UNA Core
  7. * @{
  8. */
  9. class BxDolAiQuery extends BxDolDb
  10. {
  11. public function __construct()
  12. {
  13. parent::__construct();
  14. }
  15. static protected function _getObject(int $iId, string $sTable): array|bool
  16. {
  17. $oDb = BxDolDb::getInstance();
  18. $a = $oDb->getRow("SELECT * FROM `$sTable` WHERE `id` = :id", ['id' => $iId]);
  19. if(!$a || !is_array($a))
  20. return false;
  21. return $a;
  22. }
  23. static public function getModelObject(int $iId): array|bool
  24. {
  25. return self::_getObject($iId, 'sys_agents_models');
  26. }
  27. static public function getVectorStoreObject(int $iId): array|bool
  28. {
  29. return self::_getObject($iId, 'sys_agents_vector_store');
  30. }
  31. static public function getAgentObject(int $iId): array|bool
  32. {
  33. return self::_getObject($iId, 'sys_agents_agents');
  34. }
  35. static public function getToolObject(int $iId): array|bool
  36. {
  37. return self::_getObject($iId, 'sys_agents_tools');
  38. }
  39. public function insertModel($aModel)
  40. {
  41. if(empty($aModel))
  42. return false;
  43. return (int)$this->query("INSERT INTO `sys_agents_models` SET " . $this->arrayToSQL($aModel));
  44. }
  45. public function getModelsBy($aParams = [])
  46. {
  47. $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
  48. $sWhereClause = "";
  49. switch($aParams['sample']) {
  50. case 'id':
  51. $aMethod['name'] = 'getRow';
  52. $aMethod['params'][1] = [
  53. 'id' => $aParams['id']
  54. ];
  55. $sWhereClause .= " AND `id`=:id";
  56. break;
  57. case 'all_pairs':
  58. $aMethod['name'] = 'getPairs';
  59. $aMethod['params'][1] = 'id';
  60. $aMethod['params'][2] = 'title';
  61. $aMethod['params'][3] = [];
  62. if(isset($aParams['active'])) {
  63. $aMethod['params'][3]['active'] = $aParams['active'];
  64. $sWhereClause .= " AND `active`=:active";
  65. }
  66. if(isset($aParams['capabilities'])) {
  67. if (is_array($aParams['capabilities']))
  68. {
  69. $sWhereClause .= " AND `capabilities` IN (" . $this->implode_escape($aParams['capabilities']) . ")";
  70. }
  71. else {
  72. $aMethod['params'][3]['capabilities'] = $aParams['capabilities'];
  73. $sWhereClause .= " AND `capabilities` = :capabilities";
  74. }
  75. }
  76. if (!empty($aParams['type_not'])) {
  77. $aMethod['params'][3]['type_not'] = $aParams['type_not'];
  78. $sWhereClause .= " AND `type` <> :type_not";
  79. }
  80. break;
  81. }
  82. $aMethod['params'][0] = "SELECT *
  83. FROM `sys_agents_models`
  84. WHERE 1" . $sWhereClause;
  85. return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
  86. }
  87. public function getVectorStores (): mixed
  88. {
  89. $sQuery = "SELECT `id`, `title` FROM `sys_agents_vector_store` WHERE `active` = 1 ORDER BY `title` ASC";
  90. return $this->getPairs($sQuery, 'id', 'title');
  91. }
  92. public function getVectorStoreById (int $iId): mixed
  93. {
  94. $sQuery = "SELECT * FROM `sys_agents_vector_store` WHERE `id` = :id";
  95. return $this->getRow($sQuery, ['id' => $iId]);
  96. }
  97. public function insertVectorStore($aVectorStore)
  98. {
  99. if(empty($aVectorStore) || !is_array($aVectorStore))
  100. return false;
  101. return (int)$this->query("INSERT INTO `sys_agents_vector_store` SET " . $this->arrayToSQL($aVectorStore));
  102. }
  103. public function getVectorStoreDataNum (int $iVectorStoreId): int
  104. {
  105. $sQuery = "SELECT COUNT(*) FROM `sys_agents_vector_store_data` WHERE `vector_store_id` = :vector_store_id";
  106. return (int)$this->getOne($sQuery, ['vector_store_id' => $iVectorStoreId]);
  107. }
  108. public function addVectorStoreData (int $iVectorStoreId, string $sType, string $sName, int $iFileSize, string $sMetadata, string $sSettings, string $sContent): bool
  109. {
  110. $sQuery = "INSERT INTO `sys_agents_vector_store_data` SET
  111. `vector_store_id` = :vector_store_id,
  112. `type` = :type,
  113. `name` = :name,
  114. `size` = :size,
  115. `metadata` = :metadata,
  116. `settings` = :settings,
  117. `content` = :content,
  118. `added` = :ts
  119. ";
  120. return $this->query($sQuery, [
  121. 'vector_store_id' => $iVectorStoreId,
  122. 'type' => $sType,
  123. 'name' => $sName,
  124. 'size' => $iFileSize,
  125. 'metadata' => $sMetadata,
  126. 'settings' => $sSettings,
  127. 'content' => $sContent,
  128. 'ts' => time()]) > 0;
  129. }
  130. public function getVectorStoreDataById (int $iId): mixed
  131. {
  132. $sQuery = "SELECT * FROM `sys_agents_vector_store_data` WHERE `id` = :id";
  133. return $this->getRow($sQuery, ['id' => $iId]);
  134. }
  135. static public function getVectorStorePendingData (int $iLimit = 1): mixed
  136. {
  137. $oDb = BxDolDb::getInstance();
  138. $sQuery = "SELECT * FROM `sys_agents_vector_store_data` WHERE `status` = 'pending' ORDER BY `added` ASC LIMIT :limit";
  139. return $oDb->getAll($sQuery, ['limit' => $iLimit]);
  140. }
  141. static public function updateVectorStoreDataStatus (int $iId, string $sStatus): mixed
  142. {
  143. $oDb = BxDolDb::getInstance();
  144. $sQuery = "UPDATE `sys_agents_vector_store_data` SET `status` = :status WHERE `id` = :id";
  145. return $oDb->query($sQuery, ['status' => $sStatus, 'id' => $iId]);
  146. }
  147. public function getAgentsWithAlert($bActiveOnly = true)
  148. {
  149. return $this->fromCache('sys_agents_with_alert', 'getAll', "SELECT * FROM `sys_agents_agents` WHERE `trigger` = 'alert' AND `active` = :active", ['active' => $bActiveOnly ? 1 : 0]);
  150. }
  151. public function getAgentsByProfileId($iProfileId, $bActiveOnly = true)
  152. {
  153. return $this->getAll("SELECT * FROM `sys_agents_agents` WHERE `trigger` = 'message' AND `profile_id` = :profile AND `active` = :active", ['profile' => $iProfileId, 'active' => $bActiveOnly ? 1 : 0]);
  154. }
  155. public function getAgentsByFormObject($sFormObject, $bActiveOnly = true)
  156. {
  157. return $this->fromMemory('sys_agents_with_form_' . $sFormObject, 'getAll', "SELECT * FROM `sys_agents_agents` WHERE `trigger` = 'form-input' AND `form_object` = :form_object AND `active` = :active", ['form_object' => $sFormObject, 'active' => $bActiveOnly ? 1 : 0]);
  158. }
  159. public function getAgentsBy($aParams = [])
  160. {
  161. $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
  162. $sWhereClause = "";
  163. switch($aParams['sample']) {
  164. case 'id':
  165. $aMethod['name'] = 'getRow';
  166. $aMethod['params'][1] = [
  167. 'id' => $aParams['id']
  168. ];
  169. $sWhereClause .= " AND `id`=:id";
  170. break;
  171. case 'all':
  172. if(isset($aParams['active'])) {
  173. $aMethod['params'][3]['active'] = $aParams['active'];
  174. $sWhereClause .= " AND `active`=:active";
  175. }
  176. break;
  177. }
  178. $aMethod['params'][0] = "SELECT *
  179. FROM `sys_agents_agents`
  180. WHERE 1" . $sWhereClause;
  181. return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
  182. }
  183. public function getAgentById(int $iId): mixed
  184. {
  185. return $this->getAgentsBy(['sample' => 'id', 'id' => $iId]);
  186. }
  187. public function getAgentByTriggerWebhookKey($sKey, $bActiveOnly = true)
  188. {
  189. return $this->getRow("SELECT * FROM `sys_agents_agents` WHERE `trigger` = 'webhook' AND `webhook_key` = :key AND `active` = :active", ['key' => $sKey, 'active' => $bActiveOnly ? 1 : 0]);
  190. }
  191. public function getAgentsByTriggerType($sTrigger, $bActiveOnly = true)
  192. {
  193. return $this->getAll("SELECT * FROM `sys_agents_agents` WHERE `trigger` = :trigger AND `active` = :active", ['trigger' => $sTrigger, 'active' => $bActiveOnly ? 1 : 0]);
  194. }
  195. public function isAgentProfile($iProfileId)
  196. {
  197. return (int)$this->getOne("SELECT `id` FROM `sys_agents_agents` WHERE `profile_id` = :profile_id AND `active` = 1 LIMIT 1", ['profile_id' => (int)$iProfileId]) > 0;
  198. }
  199. public function updateAgentField($iId, $sField, $sValue)
  200. {
  201. return $this->query("UPDATE `sys_agents_agents` SET `$sField` = :value WHERE `id` = :id", ['value' => $sValue, 'id' => $iId]);
  202. }
  203. public function getToolById (int $iId): mixed
  204. {
  205. $sQuery = "SELECT * FROM `sys_agents_tools` WHERE `id` = :id";
  206. return $this->getRow($sQuery, ['id' => $iId]);
  207. }
  208. public function insertTool(array $aFields): int
  209. {
  210. if(empty($aFields) || !is_array($aFields))
  211. return false;
  212. return (int)$this->query("INSERT INTO `sys_agents_tools` SET " . $this->arrayToSQL($aFields));
  213. }
  214. public function getTools()
  215. {
  216. $sQuery = "SELECT `id`, `title` FROM `sys_agents_tools` WHERE `active` = 1 ORDER BY `title` ASC";
  217. return $this->getPairs($sQuery, 'id', 'title');
  218. }
  219. public function wipeAgentChatHistory($aAgent)
  220. {
  221. $sQuery = "DELETE FROM `sys_agents_chat_history` WHERE `thread_id` LIKE :val";
  222. $iAffected = 0;
  223. $iAffected += $this->query($sQuery, ['val' => $aAgent['trigger'] . ':' . $aAgent['id'] . ':%']);
  224. $iAffected += $this->query($sQuery, ['val' => $aAgent['trigger'] . ':' . $aAgent['id']]);
  225. return $iAffected;
  226. }
  227. public function getAgentChatHistoryRows($aAgent)
  228. {
  229. $sExact = ($aAgent['trigger'] ?? '') . ':' . ($aAgent['id'] ?? '');
  230. return $this->getAll("
  231. SELECT " . $this->getChatHistoryRowFields() . "
  232. FROM `sys_agents_chat_history`
  233. WHERE `thread_id` = :exact OR `thread_id` LIKE :prefix
  234. ORDER BY `updated_at` DESC
  235. LIMIT 200
  236. ", [
  237. 'exact' => $sExact,
  238. 'prefix' => $sExact . ':%',
  239. ]);
  240. }
  241. /**
  242. * Every thread one owner (profile id, or guest session id) has with this agent:
  243. * site-wide and in any context, base and `?chat=` partitions. Newest first.
  244. * Owner is matched by LIKE on the thread id, so callers still re-check it via
  245. * BxDolAiChat::parseThreadId.
  246. */
  247. public function getOwnerAgentChatHistoryRows($aAgent, $sOwner, $iLimit = 100)
  248. {
  249. $sPrefix = ($aAgent['trigger'] ?? '') . ':' . ($aAgent['id'] ?? '');
  250. $sOwner = (string)$sOwner;
  251. if ($sPrefix === ':' || $sOwner === '')
  252. return [];
  253. $sOwnerLike = str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $sOwner);
  254. return $this->getAll("
  255. SELECT " . $this->getChatHistoryRowFields() . "
  256. FROM `sys_agents_chat_history`
  257. WHERE `thread_id` = :site
  258. OR `thread_id` LIKE :site_chat
  259. OR `thread_id` LIKE :ctx
  260. OR `thread_id` LIKE :ctx_chat
  261. ORDER BY `updated_at` DESC, `id` DESC
  262. LIMIT " . (int)$iLimit, [
  263. 'site' => $sPrefix . ':' . $sOwner,
  264. 'site_chat' => $sPrefix . ':' . $sOwnerLike . '#%',
  265. 'ctx' => $sPrefix . ':%:' . $sOwnerLike,
  266. 'ctx_chat' => $sPrefix . ':%:' . $sOwnerLike . '#%',
  267. ]);
  268. }
  269. /**
  270. * The owner's current thread for this agent+context: the newest one that is not
  271. * closed — a `?chat=` partition or the base thread. '' when there is none.
  272. */
  273. public function getCurrentOpenChatThreadId($aAgent, $sOwner, $iContext)
  274. {
  275. if (!$this->isFieldExists('sys_agents_chat_history', 'closed_reason'))
  276. return '';
  277. $sPrefix = ($aAgent['trigger'] ?? '') . ':' . ($aAgent['id'] ?? '');
  278. $sOwner = (string)$sOwner;
  279. if ($sPrefix === ':' || $sOwner === '')
  280. return '';
  281. $sBase = ((int)$iContext > 0)
  282. ? ($sPrefix . ':' . (int)$iContext . ':' . $sOwner)
  283. : ($sPrefix . ':' . $sOwner);
  284. return (string)$this->getOne("
  285. SELECT `thread_id`
  286. FROM `sys_agents_chat_history`
  287. WHERE (`thread_id` = :exact OR `thread_id` LIKE :hash)
  288. AND (`closed_reason` = '' OR `closed_reason` IS NULL)
  289. ORDER BY `updated_at` DESC, `id` DESC
  290. LIMIT 1
  291. ", [
  292. 'exact' => $sBase,
  293. 'hash' => $sBase . '#%',
  294. ]);
  295. }
  296. /**
  297. * Stored thread title; '' when unset, or when the column is not there yet —
  298. * callers fall back to deriving one from the messages.
  299. */
  300. public function getChatHistoryTitle($sThreadId)
  301. {
  302. if (!$this->isFieldExists('sys_agents_chat_history', 'title'))
  303. return '';
  304. return (string)$this->getOne("SELECT `title` FROM `sys_agents_chat_history` WHERE `thread_id` = :t", [
  305. 't' => (string)$sThreadId,
  306. ]);
  307. }
  308. public function setChatHistoryTitle($sThreadId, $sTitle)
  309. {
  310. if (!$this->isFieldExists('sys_agents_chat_history', 'title'))
  311. return false;
  312. return (bool)$this->query("UPDATE `sys_agents_chat_history` SET `title` = :s WHERE `thread_id` = :t", [
  313. 's' => get_mb_substr((string)$sTitle, 0, 255),
  314. 't' => (string)$sThreadId,
  315. ]);
  316. }
  317. /**
  318. * History row for a thread, created empty when missing.
  319. *
  320. * @return int row id, 0 for an invalid thread id
  321. */
  322. public function ensureChatHistoryRow($sThreadId)
  323. {
  324. $sThreadId = (string)$sThreadId;
  325. if ($sThreadId === '' || $sThreadId === ':')
  326. return 0;
  327. $iId = $this->getChatHistoryIdByThreadId($sThreadId);
  328. if ($iId)
  329. return $iId;
  330. $this->query("INSERT IGNORE INTO `sys_agents_chat_history` (`thread_id`, `messages`) VALUES (:t, :m)", [
  331. 't' => $sThreadId,
  332. 'm' => '[]',
  333. ]);
  334. return $this->getChatHistoryIdByThreadId($sThreadId);
  335. }
  336. protected function getChatHistoryRowFields()
  337. {
  338. $sFields = "`id`, `thread_id`, `messages`, `created_at`, `updated_at`";
  339. if ($this->isFieldExists('sys_agents_chat_history', 'closed_reason'))
  340. $sFields .= ", `closed_reason`";
  341. if ($this->isFieldExists('sys_agents_chat_history', 'title'))
  342. $sFields .= ", `title`";
  343. return $sFields;
  344. }
  345. public function getChatHistoryIdByThreadId($sThreadId)
  346. {
  347. $sThreadId = (string)$sThreadId;
  348. if ($sThreadId === '' || $sThreadId === ':')
  349. return 0;
  350. return (int)$this->getOne("SELECT `id` FROM `sys_agents_chat_history` WHERE `thread_id` = :t", [
  351. 't' => $sThreadId,
  352. ]);
  353. }
  354. public function getChatHistoryMessagesByThreadId($sThreadId)
  355. {
  356. $sThreadId = (string)$sThreadId;
  357. if ($sThreadId === '')
  358. return '';
  359. return $this->getOne("SELECT `messages` FROM `sys_agents_chat_history` WHERE `thread_id` = :t", [
  360. 't' => $sThreadId,
  361. ]);
  362. }
  363. public function getChatHistoryClosedReasonById($iHistoryId)
  364. {
  365. $iHistoryId = (int)$iHistoryId;
  366. if ($iHistoryId <= 0 || !$this->isFieldExists('sys_agents_chat_history', 'closed_reason'))
  367. return '';
  368. return (string)$this->getOne(
  369. "SELECT `closed_reason` FROM `sys_agents_chat_history` WHERE `id` = :id",
  370. ['id' => $iHistoryId]
  371. );
  372. }
  373. public function isNewChatSession($sThreadId)
  374. {
  375. $sThreadId = (string)$sThreadId;
  376. if ($sThreadId === '')
  377. return true;
  378. $aRow = $this->getRow("SELECT `ip`, `messages` FROM `sys_agents_chat_history` WHERE `thread_id` = :t", [
  379. 't' => $sThreadId,
  380. ]);
  381. if (!$aRow)
  382. return true;
  383. $iIp = (int)($aRow['ip'] ?? 0);
  384. $sMessages = trim((string)($aRow['messages'] ?? ''));
  385. return $iIp <= 0 || $sMessages === '' || $sMessages === '[]';
  386. }
  387. public function countChatSessionsByIp($sIp, $sPrefix, $iWindowSec)
  388. {
  389. $sSince = date('Y-m-d H:i:s', time() - (int)$iWindowSec);
  390. return (int)$this->getOne("
  391. SELECT COUNT(*) FROM `sys_agents_chat_history`
  392. WHERE `ip` = :ip
  393. AND (`thread_id` = :prefix OR `thread_id` LIKE :prefix_like)
  394. AND `created_at` >= :since
  395. ", [
  396. 'ip' => $sIp,
  397. 'prefix' => $sPrefix,
  398. 'prefix_like' => $sPrefix . ':%',
  399. 'since' => $sSince,
  400. ]);
  401. }
  402. public function getChatArtifactsByHistoryIds($aIds)
  403. {
  404. $aIds = array_values(array_unique(array_filter(array_map('intval', (array)$aIds))));
  405. if (!$aIds)
  406. return [];
  407. $sIn = implode(',', $aIds);
  408. $aRows = $this->getAll("
  409. SELECT `history_id`, `field_name`, `field_value`
  410. FROM `sys_agents_chat_artifacts`
  411. WHERE `history_id` IN ($sIn)
  412. ORDER BY `id` ASC
  413. ");
  414. return $this->mapChatArtifactRows($aRows);
  415. }
  416. public function getChatArtifactsByThreadId($sThreadId)
  417. {
  418. $sThreadId = (string)$sThreadId;
  419. if ($sThreadId === '')
  420. return [];
  421. $aRows = $this->getAll("
  422. SELECT `a`.`history_id`, `a`.`field_name`, `a`.`field_value`
  423. FROM `sys_agents_chat_artifacts` AS `a`
  424. INNER JOIN `sys_agents_chat_history` AS `h` ON `h`.`id` = `a`.`history_id`
  425. WHERE `h`.`thread_id` = :t
  426. ORDER BY `a`.`id` ASC
  427. ", [
  428. 't' => $sThreadId,
  429. ]);
  430. $aMap = $this->mapChatArtifactRows($aRows);
  431. if (!$aMap)
  432. return [];
  433. return (array)reset($aMap);
  434. }
  435. public function getChatArtifactsForAgent($aAgent)
  436. {
  437. $sExact = ($aAgent['trigger'] ?? '') . ':' . ($aAgent['id'] ?? '');
  438. if ($sExact === ':')
  439. return [];
  440. $aRows = $this->getAll("
  441. SELECT `a`.`history_id`, `a`.`field_name`, `a`.`field_value`
  442. FROM `sys_agents_chat_artifacts` AS `a`
  443. INNER JOIN `sys_agents_chat_history` AS `h` ON `h`.`id` = `a`.`history_id`
  444. WHERE `h`.`thread_id` = :exact OR `h`.`thread_id` LIKE :prefix
  445. ORDER BY `a`.`id` ASC
  446. ", [
  447. 'exact' => $sExact,
  448. 'prefix' => $sExact . ':%',
  449. ]);
  450. return $this->mapChatArtifactRows($aRows);
  451. }
  452. protected function mapChatArtifactRows($aRows)
  453. {
  454. if (!is_array($aRows) || !$aRows)
  455. return [];
  456. $aOut = [];
  457. foreach ($aRows as $aRow) {
  458. if (!is_array($aRow))
  459. continue;
  460. $iHistoryId = (int)($aRow['history_id'] ?? 0);
  461. $sName = trim((string)($aRow['field_name'] ?? ''));
  462. if ($iHistoryId <= 0 || $sName === '')
  463. continue;
  464. $aOut[$iHistoryId][] = [
  465. 'field_name' => $sName,
  466. 'field_value' => (string)($aRow['field_value'] ?? ''),
  467. ];
  468. }
  469. return $aOut;
  470. }
  471. public function getExpiredAgentChatHistoryIds($aAgent, $iTtlMin)
  472. {
  473. if (!$this->isFieldExists('sys_agents_chat_history', 'closed_reason'))
  474. return [];
  475. $sExact = ($aAgent['trigger'] ?? '') . ':' . ($aAgent['id'] ?? '');
  476. $iTtlMin = (int)$iTtlMin;
  477. if ($sExact === ':' || $iTtlMin <= 0)
  478. return [];
  479. return $this->getColumn("
  480. SELECT `id` FROM `sys_agents_chat_history`
  481. WHERE (`thread_id` = :exact OR `thread_id` LIKE :prefix)
  482. AND `messages` IS NOT NULL AND `messages` != '' AND `messages` != '[]'
  483. AND (`closed_reason` = '' OR `closed_reason` IS NULL)
  484. AND `updated_at` <= DATE_SUB(NOW(), INTERVAL :ttl MINUTE)
  485. ", [
  486. 'exact' => $sExact,
  487. 'prefix' => $sExact . ':%',
  488. 'ttl' => $iTtlMin,
  489. ]);
  490. }
  491. /**
  492. * Rename this agent's guest threads (`…:{sessionId}` or `…:{sessionId}#{chat}`) onto a profile id.
  493. * If the member thread already has messages, drop the guest copy.
  494. */
  495. public function adoptGuestChatHistory($aAgent, $sSessionId, $iProfileId)
  496. {
  497. $sSessionId = (string)$sSessionId;
  498. $iProfileId = (int)$iProfileId;
  499. if ($sSessionId === '' || !$iProfileId || empty($aAgent['id']))
  500. return 0;
  501. $sPrefix = $aAgent['trigger'] . ':' . $aAgent['id'] . ':';
  502. $aRows = $this->getAll("SELECT `id`, `thread_id`, `messages` FROM `sys_agents_chat_history` WHERE `thread_id` LIKE :p", [
  503. 'p' => $sPrefix . '%',
  504. ]);
  505. if (!is_array($aRows) || !$aRows)
  506. return 0;
  507. $iAffected = 0;
  508. foreach ($aRows as $aRow) {
  509. $sThreadId = (string)($aRow['thread_id'] ?? '');
  510. $aParsed = BxDolAiChat::parseThreadId($aAgent, $sThreadId);
  511. if (!$aParsed)
  512. continue;
  513. $sSub = (string)$aParsed['chat_history_subindex'];
  514. $sOwner = BxDolAiChat::chatHistoryOwnerFromSubindex($sSub);
  515. if ($sOwner !== $sSessionId)
  516. continue;
  517. $sConv = strlen($sSub) > strlen($sOwner) ? substr($sSub, strlen($sOwner)) : '';
  518. $sNewThread = BxDolAiChat::threadId($aAgent, [
  519. 'chat_history_context_pid' => (int)$aParsed['chat_history_context_pid'],
  520. 'chat_history_subindex' => $iProfileId . $sConv,
  521. ]);
  522. if ($sNewThread === '' || $sNewThread === $sThreadId)
  523. continue;
  524. $aMember = $this->getRow("SELECT `id`, `messages` FROM `sys_agents_chat_history` WHERE `thread_id` = :t", [
  525. 't' => $sNewThread,
  526. ]);
  527. $sGuestMsg = trim((string)($aRow['messages'] ?? ''));
  528. $bGuestHas = $sGuestMsg !== '' && $sGuestMsg !== '[]';
  529. $sMemberMsg = is_array($aMember) ? trim((string)($aMember['messages'] ?? '')) : '';
  530. $bMemberHas = $sMemberMsg !== '' && $sMemberMsg !== '[]';
  531. if ($bMemberHas) {
  532. $this->query("DELETE FROM `sys_agents_chat_history` WHERE `id` = :id", ['id' => (int)$aRow['id']]);
  533. continue;
  534. }
  535. if (is_array($aMember) && (int)($aMember['id'] ?? 0) > 0)
  536. $this->query("DELETE FROM `sys_agents_chat_history` WHERE `id` = :id", ['id' => (int)$aMember['id']]);
  537. if (!$bGuestHas && is_array($aMember))
  538. continue;
  539. $iAffected += (int)$this->query("UPDATE `sys_agents_chat_history` SET `thread_id` = :n WHERE `id` = :id", [
  540. 'n' => $sNewThread,
  541. 'id' => (int)$aRow['id'],
  542. ]);
  543. }
  544. return $iAffected;
  545. }
  546. static public function getAlert($s) {
  547. if (!$s)
  548. return false;
  549. $a = explode(':', $s);
  550. $oDb = BxDolDb::getInstance();
  551. return $oDb->getRow("SELECT * FROM `sys_alerts_log` WHERE `unit` = :unit AND `action` = :action", [
  552. 'unit' => $a[0] ?? '',
  553. 'action' => $a[1] ?? '',
  554. ]);
  555. }
  556. public function getAlerts()
  557. {
  558. $aValues = [];
  559. $aAlerts = $this->getAll("SELECT `unit`, `action`, `counter_24h`, `counter_per_request` FROM `sys_alerts_log` ORDER BY `unit`, `action`");
  560. foreach ($aAlerts as $a) {
  561. $sKey = $a['unit'] . ':' . $a['action'];
  562. $aValues[$sKey] = [
  563. 'key' => $sKey,
  564. 'unit' => $a['unit'],
  565. 'action' => $a['action'],
  566. 'name' => $a['unit'] . ' - ' . $a['action'],
  567. 'desc' => $this->getAlertDesc($a['unit'] . ':' . $a['action']),
  568. 'counter_24h' => $a['counter_24h'],
  569. 'counter_per_request' => $a['counter_per_request'],
  570. ];
  571. }
  572. return $aValues;
  573. }
  574. public function getFormDisplay($sObject)
  575. {
  576. $aDisplays = $this->getColumn("SELECT `display_name` FROM `sys_form_displays` WHERE `object` = :object", ['object' => $sObject]);
  577. return $aDisplays ? current($aDisplays) : null;
  578. }
  579. public function getFormObjects()
  580. {
  581. $aValues = [];
  582. $aForms = $this->getAll("SELECT `f`.`object`, `f`.`title`, `f`.`module`, `m`.`title` AS `module_title` FROM `sys_objects_form` AS f INNER JOIN `sys_modules` as `m` ON `m`.`name` = `f`.`module` ORDER BY `f`.`module`, `f`.`object` ASC");
  583. foreach ($aForms as $r) {
  584. if ('system' != $r['module']) {
  585. $oModule = BxDolModule::getInstance($r['module']);
  586. if (!$oModule || !$oModule->isEnabled())
  587. continue;
  588. }
  589. $sDisplay = $this->getFormDisplay($r['object']);
  590. if (!$sDisplay)
  591. continue;
  592. $oForm = BxDolForm::getObjectInstance($r['object'], $sDisplay);
  593. $sFormId = $oForm->getId();
  594. $aValues[$r['object']] = [
  595. 'form_id' => $sFormId,
  596. 'form_object' => $r['object'],
  597. 'module' => $r['module'],
  598. 'module_title' => $r['module_title'],
  599. 'form_title' => _t($r['title']),
  600. ];
  601. }
  602. return $aValues;
  603. }
  604. static public function getAlertDesc($sAlert)
  605. {
  606. if (!$sAlert)
  607. return '';
  608. $oDb = BxDolDb::getInstance();
  609. [$sUnit, $sAction] = explode(':', $sAlert);
  610. $sDesc = $oDb->getOne("SELECT `description` FROM `sys_alerts_desc` WHERE `unit` = :unit AND `action` = :action LIMIT 1", [
  611. 'unit' => $sUnit,
  612. 'action' => $sAction,
  613. ]);
  614. if (!$sDesc) {
  615. $sDesc = $oDb->getOne("SELECT `description` FROM `sys_alerts_desc` WHERE `unit` LIKE '{%}' AND `action` = :action LIMIT 1", [
  616. 'action' => $sAction,
  617. ]);
  618. }
  619. return $sDesc;
  620. }
  621. }
  622. /** @} */