30if (!defined(
'NOTOKENRENEWAL')) {
31 define(
'NOTOKENRENEWAL', 1);
33if (!defined(
'NOREQUIREMENU')) {
34 define(
'NOREQUIREMENU', 1);
36if (!defined(
'NOREQUIREHTML')) {
37 define(
'NOREQUIREHTML', 1);
39if (!defined(
'NOREQUIREAJAX')) {
40 define(
'NOREQUIREAJAX', 1);
44if (!defined(
'NOCSRFCHECK')) {
45 define(
'NOCSRFCHECK', 1);
48require
'../../main.inc.php';
49require_once DOL_DOCUMENT_ROOT.
'/ai/lib/ai.lib.php';
57if (!$user->hasRight(
'ai',
'assistant',
'use')) {
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;
81 $input = json_decode((
string) file_get_contents(
'php://input'),
true);
82 if (!is_array($input) || empty($input[
'action'])) {
85 $action = (string) $input[
'action'];
88 if ($action ===
'list') {
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));
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);
113 } elseif ($action ===
'load') {
114 $convid = (int) ($input[
'id'] ?? 0);
116 throw new Exception(
'Conversation not found');
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,
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;
142 if ($raw ===
'' && $html ===
'') {
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);
156 throw new Exception(
'Conversation not found');
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)) {
167 $convid = (int) $db->last_insert_id($db->prefix().
"ai_chat_conversation");
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;
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)) {
181 $msgid = (int) $db->last_insert_id($db->prefix().
"ai_chat_message");
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;
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);
202 if ($db->affected_rows($resql) < 1) {
203 throw new Exception(
'Message not found');
206 } elseif ($action ===
'rename') {
207 $convid = (int) ($input[
'id'] ?? 0);
209 throw new Exception(
'Conversation not found');
216 $db->query(
"UPDATE ".$db->prefix().
"ai_chat_conversation SET title = '".$db->escape($title).
"' WHERE rowid = ".((
int) $convid));
218 $out[
'title'] = $title;
219 } elseif ($action ===
'delete') {
220 $convid = (int) ($input[
'id'] ?? 0);
222 throw new Exception(
'Conversation not found');
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));
231 echo json_encode($out);
232}
catch (Throwable $e) {
233 http_response_code(400);
234 echo json_encode(array(
'error' => $e->getMessage()));
aiCheckCsrfToken($context='')
Check the anti-CSRF token of a request sent to one of the AI Assistant endpoints.
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.