dolibarr 25.0.0-alpha
chat_history.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2026 Jose Martinez <jose.martinez@pichinov.com>
3 * Copyright (C) 2026 Nick Fragoulis
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
30if (!defined('NOTOKENRENEWAL')) {
31 define('NOTOKENRENEWAL', 1);
32}
33if (!defined('NOREQUIREMENU')) {
34 define('NOREQUIREMENU', 1);
35}
36if (!defined('NOREQUIREHTML')) {
37 define('NOREQUIREHTML', 1);
38}
39if (!defined('NOREQUIREAJAX')) {
40 define('NOREQUIREAJAX', 1);
41}
42// The payload is read from the raw php://input body, so the CSRF token cannot be checked by
43// main.inc.php. It is checked explicitly below by aiCheckCsrfToken().
44if (!defined('NOCSRFCHECK')) {
45 define('NOCSRFCHECK', 1);
46}
47
48require '../../main.inc.php';
49require_once DOL_DOCUMENT_ROOT.'/ai/lib/ai.lib.php';
50
51if (!isModEnabled('ai') || !getDolGlobalString('AI_ASSISTANT_ENABLED')) {
52 accessforbidden('Module or feature not allowed');
53}
54
55global $db, $user, $conf;
56
57if (!$user->hasRight('ai', 'assistant', 'use')) {
59}
60
61aiCheckCsrfToken('ai/ajax/chat_history.php');
62
63top_httphead('application/json');
64
73function aiChatOwnsConversation($db, $user, int $convid): bool
74{
75 $sql = "SELECT rowid FROM ".$db->prefix()."ai_chat_conversation WHERE rowid = ".((int) $convid)." AND fk_user = ".((int) $user->id)." AND entity = ".((int) getEntity('ai'));
76 $resql = $db->query($sql);
77 return $resql && $db->num_rows($resql) > 0;
78}
79
80try {
81 $input = json_decode((string) file_get_contents('php://input'), true);
82 if (!is_array($input) || empty($input['action'])) {
83 throw new Exception('Invalid request');
84 }
85 $action = (string) $input['action'];
86 $out = array();
87
88 if ($action === 'list') {
89 // Opportunistic retention purge: no cron to register, the cost is one
90 // indexed DELETE per listing. 0 disables the purge (keep forever).
91 $days = getDolGlobalInt('AI_CHAT_HISTORY_RETENTION_DAYS', 90);
92 if ($days > 0) {
93 $limitdate = $db->idate(dol_now() - $days * 86400);
94 $sqlold = "SELECT rowid FROM ".$db->prefix()."ai_chat_conversation WHERE fk_user = ".((int) $user->id)." AND entity = ".((int) getEntity('ai'))." AND tms < '".$db->escape($limitdate)."'";
95 $resold = $db->query($sqlold);
96 while ($resold && ($objold = $db->fetch_object($resold))) {
97 $db->query("DELETE FROM ".$db->prefix()."ai_chat_message WHERE fk_conversation = ".((int) $objold->rowid));
98 $db->query("DELETE FROM ".$db->prefix()."ai_chat_conversation WHERE rowid = ".((int) $objold->rowid));
99 }
100 }
101
102 $sql = "SELECT c.rowid, c.title, c.tms, COUNT(m.rowid) as nbmsg";
103 $sql .= " FROM ".$db->prefix()."ai_chat_conversation as c";
104 $sql .= " LEFT JOIN ".$db->prefix()."ai_chat_message as m ON m.fk_conversation = c.rowid";
105 $sql .= " WHERE c.fk_user = ".((int) $user->id)." AND c.entity = ".((int) getEntity('ai'));
106 $sql .= " GROUP BY c.rowid, c.title, c.tms ORDER BY c.tms DESC";
107 $sql .= $db->plimit(30);
108 $resql = $db->query($sql);
109 $out['conversations'] = array();
110 while ($resql && ($obj = $db->fetch_object($resql))) {
111 $out['conversations'][] = array('id' => (int) $obj->rowid, 'title' => (string) $obj->title, 'date' => dol_print_date($db->jdate($obj->tms), 'dayhour'), 'ts' => (int) $db->jdate($obj->tms), 'nb' => (int) $obj->nbmsg);
112 }
113 } elseif ($action === 'load') {
114 $convid = (int) ($input['id'] ?? 0);
115 if (!aiChatOwnsConversation($db, $user, $convid)) {
116 throw new Exception('Conversation not found');
117 }
118 $sql = "SELECT rowid, role, content_raw, content_html, tool_name, pinned, is_error FROM ".$db->prefix()."ai_chat_message";
119 $sql .= " WHERE fk_conversation = ".((int) $convid)." ORDER BY position, rowid";
120 $resql = $db->query($sql);
121 $out['id'] = $convid;
122 $out['messages'] = array();
123 while ($resql && ($obj = $db->fetch_object($resql))) {
124 $out['messages'][] = array(
125 'id' => (int) $obj->rowid,
126 'role' => (string) $obj->role,
127 'raw' => (string) $obj->content_raw,
128 'html' => (string) $obj->content_html,
129 'tool' => (string) $obj->tool_name,
130 'pinned' => (int) $obj->pinned,
131 'error' => (int) $obj->is_error,
132 );
133 }
134 } elseif ($action === 'save') {
135 $convid = (int) ($input['id'] ?? 0);
136 $role = (($input['role'] ?? '') === 'assistant') ? 'assistant' : 'user';
137 $raw = (string) ($input['raw'] ?? '');
138 $html = (string) ($input['html'] ?? '');
139 $toolname = dol_trunc((string) ($input['tool'] ?? ''), 250, 'right', 'UTF-8', 1);
140 $pinned = empty($input['pinned']) ? 0 : 1;
141 $iserror = empty($input['error']) ? 0 : 1; // provider failure: never context by default
142 if ($raw === '' && $html === '') {
143 throw new Exception('Empty message');
144 }
145
146 // The stored HTML is re-injected on reopen: sanitize it at SAVE time with
147 // the core whitelist, so nothing executable can ever be persisted. Action
148 // buttons (download, open record...) are stripped on purpose: they carry
149 // one-shot client state that would be dead on reopen anyway.
150 // ($cleanalsosomestyles=1, keep class attributes=0 - the chat tables and
151 // badges style through classes -, $cleanalsojavascript=1, no iframe,
152 // explicit tag whitelist, links allowed, no script/style/php)
153 $html = dol_string_onlythesehtmltags($html, 1, 0, 1, 0, array('a', 'b', 'strong', 'em', 'i', 'u', 'br', 'p', 'span', 'div', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tr', 'td', 'th', 'code', 'pre', 'hr'), 1, 0, 0, 0);
154
155 if ($convid > 0 && !aiChatOwnsConversation($db, $user, $convid)) {
156 throw new Exception('Conversation not found');
157 }
158 if ($convid <= 0) {
159 // The whole first question (the list truncates it with an ellipsis, the
160 // hover preview shows it in full); 250 keeps under the column's 255.
161 $title = dol_trunc(preg_replace('/\s+/', ' ', ($role === 'user' && $raw !== '') ? $raw : 'Conversation'), 250, 'right', 'UTF-8', 1);
162 $sql = "INSERT INTO ".$db->prefix()."ai_chat_conversation (entity, fk_user, title, date_creation)";
163 $sql .= " VALUES (".((int) $conf->entity).", ".((int) $user->id).", '".$db->escape($title)."', '".$db->idate(dol_now())."')";
164 if (!$db->query($sql)) {
165 throw new Exception($db->lasterror());
166 }
167 $convid = (int) $db->last_insert_id($db->prefix()."ai_chat_conversation");
168 }
169
170 $sql = "SELECT MAX(position) as maxpos FROM ".$db->prefix()."ai_chat_message WHERE fk_conversation = ".((int) $convid);
171 $resql = $db->query($sql);
172 $objpos = $resql ? $db->fetch_object($resql) : null;
173 $position = $objpos ? ((int) $objpos->maxpos + 1) : 1;
174
175 $sql = "INSERT INTO ".$db->prefix()."ai_chat_message (fk_conversation, role, content_raw, content_html, tool_name, pinned, is_error, position, datec)";
176 $sql .= " VALUES (".((int) $convid).", '".$db->escape($role)."', '".$db->escape($raw)."', '".$db->escape($html)."', '".$db->escape($toolname)."', ".((int) $pinned).", ".((int) $iserror).", ".((int) $position).", '".$db->idate(dol_now())."')";
177 if (!$db->query($sql)) {
178 throw new Exception($db->lasterror());
179 }
180 // Read the id BEFORE any other statement (last_insert_id is per statement)
181 $msgid = (int) $db->last_insert_id($db->prefix()."ai_chat_message");
182 // Touch the conversation so the list sorts by real activity ("SET tms = tms"
183 // is a no-op for MySQL: an unchanged row does not refresh its timestamp)
184 $db->query("UPDATE ".$db->prefix()."ai_chat_conversation SET tms = '".$db->idate(dol_now())."' WHERE rowid = ".((int) $convid));
185 $out['id'] = $convid;
186 $out['message_id'] = $msgid;
187 } elseif ($action === 'pin') {
188 $msgid = (int) ($input['message_id'] ?? 0);
189 $pinned = empty($input['pinned']) ? 0 : 1;
190 // Ownership travels through the conversation. 'error' (optional) marks a
191 // turn that must stay out of the context window on reopen, e.g. the
192 // question behind an action the user cancelled.
193 $sql = "UPDATE ".$db->prefix()."ai_chat_message as m";
194 $sql .= " INNER JOIN ".$db->prefix()."ai_chat_conversation as c ON c.rowid = m.fk_conversation AND c.fk_user = ".((int) $user->id);
195 $sql .= " SET m.pinned = ".((int) $pinned).(isset($input['error']) ? ", m.is_error = ".(empty($input['error']) ? 0 : 1) : "")." WHERE m.rowid = ".((int) $msgid);
196 $resql = $db->query($sql);
197 if (!$resql) {
198 throw new Exception($db->lasterror());
199 }
200 // A message that is not the caller's (or does not exist) matches no row:
201 // say so, a silent "ok" would let the client believe the pin was kept
202 if ($db->affected_rows($resql) < 1) {
203 throw new Exception('Message not found');
204 }
205 $out['ok'] = 1;
206 } elseif ($action === 'rename') {
207 $convid = (int) ($input['id'] ?? 0);
208 if (!aiChatOwnsConversation($db, $user, $convid)) {
209 throw new Exception('Conversation not found');
210 }
211 // Plain text only, one line, within the column size; an empty title is refused
212 $title = dol_trunc(trim(preg_replace('/\s+/', ' ', dol_string_nohtmltag((string) ($input['title'] ?? ''), 0))), 250, 'right', 'UTF-8', 1);
213 if ($title === '') {
214 throw new Exception('Empty title');
215 }
216 $db->query("UPDATE ".$db->prefix()."ai_chat_conversation SET title = '".$db->escape($title)."' WHERE rowid = ".((int) $convid));
217 $out['ok'] = 1;
218 $out['title'] = $title;
219 } elseif ($action === 'delete') {
220 $convid = (int) ($input['id'] ?? 0);
221 if (!aiChatOwnsConversation($db, $user, $convid)) {
222 throw new Exception('Conversation not found');
223 }
224 $db->query("DELETE FROM ".$db->prefix()."ai_chat_message WHERE fk_conversation = ".((int) $convid));
225 $db->query("DELETE FROM ".$db->prefix()."ai_chat_conversation WHERE rowid = ".((int) $convid));
226 $out['ok'] = 1;
227 } else {
228 throw new Exception('Unknown action');
229 }
230
231 echo json_encode($out);
232} catch (Throwable $e) {
233 http_response_code(400);
234 echo json_encode(array('error' => $e->getMessage()));
235}
aiCheckCsrfToken($context='')
Check the anti-CSRF token of a request sent to one of the AI Assistant endpoints.
Definition ai.lib.php:1260
aiChatOwnsConversation($db, $user, int $convid)
Ownership guard: the conversation must exist and belong to the current user.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
dol_now($mode='gmt')
Return date for now.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles=1, $removeclassattribute=1, $cleanalsojavascript=0, $allowiframe=0, $allowed_tags=array(), $allowlink=0, $allowscript=0, $allowstyle=0, $allowphp=0)
Clean a string to keep only desirable HTML tags.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
if(!defined( 'NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.