29include_once DOL_DOCUMENT_ROOT.
'/ai/class/ai.class.php';
41 $arrayofaifeatures = array(
42 'textgenerationemail' => array(
'label' => $langs->trans(
'TextGeneration').
' ('.$langs->trans(
"EmailContent").
')',
'picto' =>
'',
'status' =>
'dolibarr',
'function' =>
'TEXT',
'placeholder' => Ai::AI_DEFAULT_PROMPT_FOR_EMAIL),
43 'textgenerationwebpage' => array(
'label' => $langs->trans(
'TextGeneration').
' ('.$langs->trans(
"WebsitePage").
')',
'picto' =>
'',
'status' =>
'dolibarr',
'function' =>
'TEXT',
'placeholder' => Ai::AI_DEFAULT_PROMPT_FOR_WEBPAGE),
44 'textgeneration' => array(
'label' => $langs->trans(
'TextGeneration').
' ('.$langs->trans(
"Other").
')',
'picto' =>
'',
'status' =>
'notused',
'function' =>
'TEXT'),
46 'texttranslation' => array(
'label' => $langs->trans(
'TextTranslation'),
'picto' =>
'',
'status'=>
'dolibarr',
'function' =>
'TEXT',
'placeholder' => Ai::AI_DEFAULT_PROMPT_FOR_TEXT_TRANSLATION),
47 'textsummarize' => array(
'label' => $langs->trans(
'TextSummarize'),
'picto' =>
'',
'status'=>
'dolibarr',
'function' =>
'TEXT',
'placeholder' => Ai::AI_DEFAULT_PROMPT_FOR_TEXT_SUMMARIZE),
48 'textspellchecker' => array(
'label' => $langs->trans(
'TextSpellChecker'),
'picto' =>
'',
'status'=>
'dolibarr',
'function' =>
'TEXT',
'placeholder' => Ai::AI_DEFAULT_PROMPT_FOR_TEXT_SPELLCHECKER),
49 'textrephraser' => array(
'label' => $langs->trans(
'TextRephraser'),
'picto' =>
'',
'status'=>
'dolibarr',
'function' =>
'TEXT',
'placeholder' => Ai::AI_DEFAULT_PROMPT_FOR_TEXT_REPHRASER),
51 'textgenerationextrafield' => array(
'label' => $langs->trans(
'TextGeneration').
' ('.$langs->trans(
"ExtrafieldFiller").
')',
'picto' =>
'',
'status'=>
'dolibarr',
'function' =>
'TEXT',
'placeholder' => Ai::AI_DEFAULT_PROMPT_FOR_EXTRAFIELD_FILLER),
53 'imagegeneration' => array(
'label' =>
'ImageGeneration',
'picto' =>
'',
'status' =>
'notused',
'function' =>
'IMAGE'),
54 'videogeneration' => array(
'label' =>
'VideoGeneration',
'picto' =>
'',
'status' =>
'notused',
'function' =>
'VIDEO'),
55 'audiogeneration' => array(
'label' =>
'AudioGeneration',
'picto' =>
'',
'status' =>
'notused',
'function' =>
'AUDIO'),
56 'transcription' => array(
'label' =>
'AudioTranscription',
'picto' =>
'',
'status' =>
'notused',
'function' =>
'TRANSCRIPT'),
57 'translation' => array(
'label' =>
'AudioTranslation',
'picto' =>
'',
'status' =>
'notused',
'function' =>
'TRANSLATE'),
58 'docparsing' => array(
'label' =>
'DocumentParsing',
'picto' =>
'',
'status' =>
'experimental',
'function' =>
'DOCPARSING')
61 return $arrayofaifeatures;
74 '-1' => array(
'label' => $langs->trans(
'SelectAService')),
76 'label' =>
'ChatGPT (OpenAI)',
77 'url' =>
'https://api.openai.com/v1/',
78 'setup' =>
'https://platform.openai.com/account/api-keys',
79 'textgeneration' => array(
'default' =>
'gpt-5.6'),
80 'imagegeneration' => array(
'default' =>
'gpt-image-2'),
81 'audiogeneration' => array(
'default' =>
'gpt-audio-1.5'),
82 'videogeneration' => array(
'default' =>
'sora-2'),
83 'transcription' => array(
'default' =>
'gpt-transcribe'),
84 'translation' => array(
'default' =>
'gpt-5.6'),
85 'docparsing' => array(
'default' =>
'gpt-5.6'),
86 'adapter_type' =>
'openai'
89 'label' =>
'Groq (LPU Inference)',
90 'url' =>
'https://api.groq.com/openai/v1/',
91 'setup' =>
'https://console.groq.com/keys',
92 'textgeneration' => array(
'default' =>
'llama-4-8b-instant'),
93 'imagegeneration' => array(
'default' =>
'na'),
94 'audiogeneration' => array(
'default' =>
'na'),
95 'videogeneration' => array(
'default' =>
'na'),
96 'transcription' => array(
'default' =>
'whisper-large-v3-turbo'),
97 'translation' => array(
'default' =>
'whisper-large-v3-turbo'),
98 'docparsing' => array(
'default' =>
'llama-4-70b-versatile'),
99 'adapter_type' =>
'openai'
102 'label' =>
'Mistral AI',
103 'url' =>
'https://api.mistral.ai/v1/',
104 'setup' =>
'https://console.mistral.ai/api-keys/',
105 'textgeneration' => array(
'default' =>
'mistral-medium-latest',
'examples' =>
'mistral-tiny-latest, mistral-small-latest, mistral-medium-latest, mistral-large-latest'),
106 'imagegeneration' => array(
'default' =>
'na'),
107 'audiogeneration' => array(
'default' =>
'na'),
108 'videogeneration' => array(
'default' =>
'na'),
109 'transcription' => array(
'default' =>
'na'),
110 'translation' => array(
'default' =>
'na'),
111 'docparsing' => array(
'default' =>
'mistral-ocr-latest'),
112 'adapter_type' =>
'openai'
115 'label' =>
'DeepSeek',
116 'url' =>
'https://api.deepseek.com',
117 'setup' =>
'https://platform.deepseek.com/api_keys',
118 'textgeneration' => array(
'default' =>
'deepseek-v4'),
119 'imagegeneration' => array(
'default' =>
'deepseek-janus-2'),
120 'audiogeneration' => array(
'default' =>
'na'),
121 'videogeneration' => array(
'default' =>
'na'),
122 'transcription' => array(
'default' =>
'na'),
123 'translation' => array(
'default' =>
'na'),
124 'docparsing' => array(
'default' =>
'deepseek-v4'),
125 'adapter_type' =>
'openai'
127 'perplexity' => array(
128 'label' =>
'Perplexity (Sonar)',
129 'url' =>
'https://api.perplexity.ai',
130 'setup' =>
'https://www.perplexity.ai/settings/api',
131 'textgeneration' => array(
'default' =>
'sonar-pro'),
132 'imagegeneration' => array(
'default' =>
'na'),
133 'audiogeneration' => array(
'default' =>
'na'),
134 'videogeneration' => array(
'default' =>
'na'),
135 'transcription' => array(
'default' =>
'na'),
136 'translation' => array(
'default' =>
'na'),
137 'docparsing' => array(
'default' =>
'sonar-reasoning'),
138 'adapter_type' =>
'openai'
141 'label' =>
'Zhipu AI (GLM)',
142 'url' =>
'https://api.z.ai/api/paas/v4',
143 'setup' =>
'https://docs.z.ai/guides/overview/quick-start',
144 'textgeneration' => array(
'default' =>
'glm-5'),
145 'imagegeneration' => array(
'default' =>
'cogview-4'),
146 'audiogeneration' => array(
'default' =>
'cogvlm2-audio'),
147 'videogeneration' => array(
'default' =>
'cogvideox-2'),
148 'transcription' => array(
'default' =>
'na'),
149 'translation' => array(
'default' =>
'na'),
150 'docparsing' => array(
'default' =>
'glm-5'),
151 'adapter_type' =>
'openai'
155 'url' =>
'https://domainofapi.com/v1/',
156 'setup' =>
'Ask your AI provider how to get your API key',
157 'textgeneration' => array(
'default' =>
'tinyllama-1.1b'),
158 'imagegeneration' => array(
'default' =>
'mixtral-8x7b-32768'),
159 'audiogeneration' => array(
'default' =>
'mixtral-8x7b-32768'),
160 'videogeneration' => array(
'default' =>
'na'),
161 'transcription' => array(
'default' =>
'mixtral-8x7b-32768'),
162 'translation' => array(
'default' =>
'mixtral-8x7b-32768'),
163 'docparsing' => array(
'default' =>
'na'),
164 'adapter_type' =>
'openai'
167 'anthropic' => array(
168 'label' =>
'Anthropic (Claude)',
169 'url' =>
'https://api.anthropic.com/v1/',
170 'setup' =>
'https://console.anthropic.com/',
171 'textgeneration' => array(
'default' =>
'claude-opus-5'),
172 'imagegeneration' => array(
'default' =>
'na'),
173 'audiogeneration' => array(
'default' =>
'na'),
174 'videogeneration' => array(
'default' =>
'na'),
175 'transcription' => array(
'default' =>
'na'),
176 'translation' => array(
'default' =>
'na'),
177 'docparsing' => array(
'default' =>
'claude-opus-5'),
178 'adapter_type' =>
'anthropic'
181 'label' =>
'Google Gemini',
182 'url' =>
'https://generativelanguage.googleapis.com/v1beta/',
183 'setup' =>
'https://aistudio.google.com/',
184 'textgeneration' => array(
'default' =>
'gemini-3.1-pro-preview'),
185 'imagegeneration' => array(
'default' =>
'nano-banana-pro'),
186 'audiogeneration' => array(
'default' =>
'gemini-2.5-pro-tts'),
187 'videogeneration' => array(
'default' =>
'veo-3.1'),
188 'transcription' => array(
'default' =>
'gemini-3.1-pro-preview'),
189 'translation' => array(
'default' =>
'gemini-3.1-pro-preview'),
190 'docparsing' => array(
'default' =>
'gemini-3.1-pro-preview'),
191 'adapter_type' =>
'google'
216 return [
'success' =>
false,
'message' =>
'API Key is empty'];
220 if (!function_exists(
'getListOfAIServices')) {
221 return [
'success' =>
false,
'message' =>
'Configuration helper function missing.'];
225 $defUrl = $list[$service][
'url'] ??
'';
227 $defaultModel = $list[$service][
'model'] ??
'unknown';
233 $url = rtrim($url,
'/');
236 $headers = [
"Content-Type: application/json"];
244 if ($service ==
'google' || strpos($url,
'googleapis') !==
false) {
245 if (strpos($url,
':generateContent') ===
false) {
246 if (strpos($url,
'models') ===
false) {
247 $url .=
"/models/$model:generateContent";
249 $url .=
"/$model:generateContent";
252 $url .=
"?key=" . $key;
253 $data = [
"contents" => [ [
"parts" => [ [
"text" =>
"Hello"] ] ] ],
"generationConfig" => [
"maxOutputTokens" => 5]];
254 } elseif ($service ==
'anthropic' || strpos($url,
'anthropic') !==
false) {
255 if (strpos($url,
'messages') ===
false) $url .=
'/messages';
256 $headers[] =
"x-api-key: $key";
257 $headers[] =
"anthropic-version: 2023-06-01";
260 "messages" => [[
"role" =>
"user",
"content" =>
"Hello"]],
264 if (strpos($url,
'/chat/completions') ===
false) $url .=
'/chat/completions';
265 $headers[] =
"Authorization: Bearer $key";
269 "messages" => [[
"role" =>
"user",
"content" =>
"Hello"]],
275 include_once DOL_DOCUMENT_ROOT.
'/core/lib/geturl.lib.php';
279 global $dolibarr_ai_allow_local_endpoints;
280 $localurl = empty($dolibarr_ai_allow_local_endpoints) ? 0 : 2;
282 $result =
getURLContent($url,
'POST', json_encode($data), 1, $headers, array(
'http',
'https'), $localurl, -1, 0, 10);
283 $httpCode = (int) ($result[
'http_code'] ?? 0);
284 $responseContent = (string) ($result[
'content'] ??
'');
286 if (!empty($result[
'curl_error_no'])) {
287 return [
'success' =>
false,
'message' =>
"Curl Error: ".($result[
'curl_error_msg'] ??
'')];
290 if ($httpCode >= 200 && $httpCode < 300) {
291 return [
'success' =>
true,
'message' =>
"OK (HTTP $httpCode)."];
293 $json = json_decode($responseContent,
true);
295 $msg = $json[
'error'][
'message'] ?? $json[
'message'] ?? substr($responseContent, 0, 150);
296 return [
'success' =>
false,
'message' =>
"HTTP $httpCode. Error: $msg"];
322 if (empty($attachments)) {
325 $langs->load(
"other");
328 $error = $langs->trans(
"AIAttachmentBlockedByPrivacy");
336 if ($maxfiles > 0 && count($attachments) > $maxfiles) {
337 $error = $langs->trans(
"AIAttachmentTooMany", (
string) $maxfiles);
342 $allowedmimes = array(
'application/pdf',
'image/png',
'image/jpeg',
'image/gif',
'image/webp');
347 $allowedmimes[] =
'image/heic';
348 $allowedmimes[] =
'image/heif';
352 foreach ($attachments as $att) {
353 if (!in_array($att[
'mime'], $allowedmimes,
true)) {
354 $error = $langs->trans(
"AIAttachmentTypeNotAllowed", $att[
'mime']);
359 $bytes = (int) (strlen($att[
'data']) * 3 / 4);
360 $totalbytes += $bytes;
361 if ($bytes > $maxbytes || $totalbytes > $maxbytes) {
362 $error = $langs->trans(
"AIAttachmentTooLarge", (
string)
getDolGlobalInt(
'AI_ATTACHMENT_MAX_MB', 10));
389 $head = (int) floor($max / 2);
390 $tail = $max - $head;
393 .
"\n... [Truncated ".($len - $max).
" chars] ...\n"
416function ai_log_request($db, $user, $query, array $response, $provider,
float $time,
float $confidence, $status, $error =
'', $rawReq =
'', $rawRes =
'', array
$context = array(), &$logId =
null)
426 $tool = isset($response[
'tool']) ? (string) $response[
'tool'] :
'';
433 $rawResStr = (string) $rawRes;
434 if (empty(
$context[
'preserve_payloads'])) {
439 $sql =
"INSERT INTO " . $db->prefix() .
"ai_request_log (";
440 $sql .=
"entity, date_request, fk_user, query_text, tool_name, provider, ";
441 $sql .=
"execution_time, confidence, status, error_msg, raw_request_payload, raw_response_payload";
447 $sql .=
", fk_actioncomm, input_hash, output_hash, security_hash";
450 $sql .=
", tokens_input, tokens_output, model";
452 $sql .=
") VALUES (";
453 $sql .= ((int)
$conf->entity) .
", ";
454 $sql .=
"'" . $db->idate(
dol_now()) .
"', ";
455 $sql .= ((int) $user->id) .
", ";
456 $sql .=
"'" . $db->escape($query) .
"', ";
457 $sql .=
"'" . $db->escape($tool) .
"', ";
458 $sql .=
"'" . $db->escape($provider) .
"', ";
459 $sql .= ((float) $time) .
", ";
460 $sql .= ((float) $confidence) .
", ";
461 $sql .=
"'" . $db->escape($status) .
"', ";
462 $sql .=
"'" . $db->escape($error) .
"', ";
463 $sql .=
"'" . $db->escape($rawReq) .
"', ";
464 $sql .=
"'" . $db->escape($rawResStr) .
"'";
466 $sql .=
", ".(!empty(
$context[
'fk_actioncomm']) &&
$context[
'fk_actioncomm'] > 0 ? (int)
$context[
'fk_actioncomm'] :
'NULL');
467 $sql .=
", '".$db->escape(
$context[
'input_hash'] ??
'').
"'";
468 $sql .=
", '".$db->escape(
$context[
'output_hash'] ??
'').
"'";
469 $sql .=
", '".$db->escape(
$context[
'security_hash'] ??
'').
"'";
472 $sql .=
", ".(isset(
$context[
'tokens_input']) ? (int)
$context[
'tokens_input'] :
'NULL');
473 $sql .=
", ".(isset(
$context[
'tokens_output']) ? (int)
$context[
'tokens_output'] :
'NULL');
474 $sql .=
", '".$db->escape((
string) (
$context[
'model'] ??
'')).
"'";
478 $resql = $db->query($sql);
480 dol_syslog(__FUNCTION__.
": ".$db->lasterror(), LOG_ERR);
482 $logId = (int) $db->last_insert_id($db->prefix().
"ai_request_log");
495 $arrayforaisummarize = array(
497 '50_w' =>
'SummarizeFiftyWords',
498 '100_w' =>
'SummarizeHundredWords',
499 '200_w' =>
'SummarizeTwoHundredWords',
500 '1_p' =>
'SummarizeOneParagraphs',
501 '2_p' =>
'SummarizeTwoParagraphs',
502 '25_pc' =>
'SummarizeTwentyFivePercent',
503 '50_pc' =>
'SummarizeFiftyPercent',
504 '75_pc' =>
'SummarizeSeventyFivePercent'
507 return $arrayforaisummarize;
517 $arrayforaierephrasestyle = array(
518 'spellchecker' =>
'RephraseSpellChecker',
519 'professional' =>
'RephraseStyleProfessional',
520 'humouristic' =>
'RephraseStyleHumouristic',
523 return $arrayforaierephrasestyle;
536 if (!empty($result[
'curl_error_no']) && $result[
'curl_error_no'] == 28) {
537 $langs->load(
"errors");
538 return $langs->transnoentitiesnoconv(
"ErrorAIServiceTimeout", (empty($result[
'model']) ? (empty($result[
'service']) ?
'?' : $result[
'service']) : $result[
'model']));
540 return (empty($result[
'message']) ?
'Unknown error from AI service' : $result[
'message']);
550 global $langs,
$conf;
552 $langs->load(
"agenda");
558 $head[$h][1] = $langs->trans(
"Settings");
559 $head[$h][2] =
'settings';
562 $head[$h][0] =
dol_buildpath(
"/ai/admin/custom_prompt.php", 1);
563 $head[$h][1] = $langs->trans(
"CustomPrompt");
564 $head[$h][2] =
'custom';
569 $head[$h][1] = $langs->trans(
"Assistant");
570 $head[$h][2] =
'assistant';
576 $head[$h][1] = $langs->trans(
"MCPServer");
577 $head[$h][2] =
'servermcp';
582 $head[$h][0] =
dol_buildpath(
"/ai/admin/configure_tools.php", 1);
583 $head[$h][1] = $langs->trans(
"ToolAccessControl");
584 $head[$h][2] =
'tools';
621 if (empty($serviceKey) || $serviceKey ===
'-1') {
627 return isset($services[$serviceKey][
'label']) ? (string) $services[$serviceKey][
'label'] : (string) $serviceKey;
639 if (empty($serviceKey) || $serviceKey ===
'-1') {
644 $prefix =
'AI_API_'.strtoupper($serviceKey);
647 ?: ($services[$serviceKey][
'textgeneration'][
'default'] ??
'');
649 return is_string($model) ? $model :
'';
661 if (empty($serviceKey) || $serviceKey ===
'-1') {
667 return (
string) (
getDolGlobalString(
'AI_API_'.strtoupper($serviceKey).
'_URL') ?: ($services[$serviceKey][
'url'] ??
''));
686 if (empty($serviceKey) || $serviceKey ==
'-1') {
687 return array(
'service' =>
'',
'models' => array());
690 if (!$forcerefresh) {
693 $cache = json_decode($cacheraw,
true);
694 if (is_array($cache) && !empty($cache[
'service']) && $cache[
'service'] === $serviceKey
695 && !empty($cache[
'ts']) && (
dol_now() - (
int) $cache[
'ts']) < 3600
696 && !empty($cache[
'models']) && is_array($cache[
'models'])) {
697 return array(
'service' => $serviceKey,
'models' => $cache[
'models']);
702 include_once DOL_DOCUMENT_ROOT.
'/core/lib/geturl.lib.php';
703 include_once DOL_DOCUMENT_ROOT.
'/core/lib/admin.lib.php';
706 $adapterType = $servicesList[$serviceKey][
'adapter_type'] ??
'openai';
707 $defUrl = $servicesList[$serviceKey][
'url'] ??
'';
708 $baseUrl = rtrim(
getDolGlobalString(
'AI_API_'.strtoupper($serviceKey).
'_URL') ?: $defUrl,
'/');
711 if (preg_match(
'/^crypt:/', $apiKey)) {
714 if (empty($apiKey) || empty($baseUrl)) {
715 return array(
'service' => $serviceKey,
'models' => array());
719 if ($adapterType ===
'anthropic') {
720 $headers = array(
'x-api-key: '.$apiKey,
'anthropic-version: 2023-06-01');
721 $res =
getURLContent($baseUrl.
'/models?limit=100',
'GET',
'', 1, $headers, array(
'http',
'https'), 2);
722 $json = json_decode($res[
'content'] ??
'',
true);
723 foreach ((array) ($json[
'data'] ?? array()) as $m) {
724 if (!empty($m[
'id'])) {
725 $models[] = (string) $m[
'id'];
728 } elseif ($adapterType ===
'google') {
729 $res =
getURLContent($baseUrl.
'/models?pageSize=200&key='.urlencode($apiKey),
'GET',
'', 1, array(), array(
'http',
'https'), 2);
730 $json = json_decode($res[
'content'] ??
'',
true);
731 foreach ((array) ($json[
'models'] ?? array()) as $m) {
732 if (!empty($m[
'name'])) {
733 $models[] = preg_replace(
'/^models\//',
'', (
string) $m[
'name']);
738 $headers = array(
'Authorization: Bearer '.$apiKey);
739 $res =
getURLContent($baseUrl.
'/models',
'GET',
'', 1, $headers, array(
'http',
'https'), 2);
740 $json = json_decode($res[
'content'] ??
'',
true);
741 foreach ((array) ($json[
'data'] ?? array()) as $m) {
742 if (!empty($m[
'id'])) {
743 $models[] = (string) $m[
'id'];
748 $models = array_values(array_unique($models));
751 if (count($models)) {
752 dolibarr_set_const($db,
'AI_MODELS_LIST_CACHE', json_encode(array(
'service' => $serviceKey,
'ts' =>
dol_now(),
'models' => $models)),
'chaine', 0,
'',
$conf->entity);
755 return array(
'service' => $serviceKey,
'models' => $models);
772 foreach ($models as $cand) {
774 if (similar_text(strtolower($missing), strtolower($cand), $pct) === 0) {
778 if (strtok(strtolower($missing),
'-') === strtok(strtolower($cand),
'-')) {
781 if ($score > $bestScore) {
786 return ($bestScore >= 50.0) ? $best :
'';
797 global
$conf, $langs, $user;
799 $langs->loadLangs(array(
'main',
'admin',
'bills',
'companies',
'products',
'other'));
803 'AIAttachmentBlockedByPrivacy',
'AIAttachmentHeicUnsupported',
'AIAttachmentTooMany',
'MissingInformation',
'CouldYouClarify',
804 'Ref',
'Label',
'ThirdParty',
'Customer',
'Paid',
'Status',
'Type',
'Email',
'Town',
'Date',
805 'DateInvoice',
'DateMaxPayment',
'AmountHT',
'AmountTTC',
'AmountVAT',
'RemainderToPay',
806 'Price',
'PriceTTC',
'VATRate',
'CustomerCode',
'SupplierCode',
'Supplier',
'TotalHT',
'TotalTTC',
814 'ConfirmAiAction',
'ConfirmAiWrite',
815 'ClearChatHistoryTitle',
819 'VersionExperimental',
841 'UnsupportedFileType',
854 'ConnectionBlockedHelp',
859 'BrowserNotSupported',
860 'AISessionExpiredReload',
869 'AIContextAutoTitle',
872 'AIContextClearTitle',
875 'AIContextAttachmentOnly',
881 'AIHistoryYesterday',
882 'AIHistoryLast7Days',
886 'AIHideConversations',
887 'AIShowConversations',
899 'AISearchDoneNowPreparingAction',
912 'AIMentionThirdpartyHint',
913 'AIMentionProductHint',
925 'AIHelpMentionThirdparty',
926 'AIHelpMentionProduct',
950 $ai_translations = array();
951 foreach ($keys as $key) {
952 $ai_translations[$key] = $langs->transnoentitiesnoconv($key);
958 $ai_translations[
'AIContextCounter'] = $langs->transnoentitiesnoconv(
'AIContextCounter',
'%s',
'%s',
'%s');
959 $ai_translations[
'AIContextAuto'] = $langs->transnoentitiesnoconv(
'AIContextAuto',
'%s');
960 $ai_translations[
'AIContextTokens'] = $langs->transnoentitiesnoconv(
'AIContextTokens',
'%s');
961 $ai_translations[
'AIContextAutoTitle'] = $langs->transnoentitiesnoconv(
'AIContextAutoTitle',
'%s');
962 $ai_translations[
'AIAttachmentTooMany'] = $langs->transnoentitiesnoconv(
'AIAttachmentTooMany',
'%s');
963 $ai_translations[
'ErrorFieldRequired'] = $langs->transnoentitiesnoconv(
'ErrorFieldRequired',
'%s');
964 $ai_translations[
'AIPaletteBadJson'] = $langs->transnoentitiesnoconv(
'AIPaletteBadJson',
'%s');
965 $ai_translations[
'AIReloadDone'] = $langs->transnoentitiesnoconv(
'AIReloadDone',
'%s');
966 $ai_translations[
'AIPaletteTypeToSearch'] = $langs->transnoentitiesnoconv(
'AIPaletteTypeToSearch',
'%s');
967 $ai_translations[
'DownloadPdf'] = $langs->transnoentitiesnoconv(
"Download").
' PDF';
968 $ai_translations[
'CloudVoiceRequiresSecureContext'] = $langs->trans(
969 "CloudVoiceRequiresSecureContext",
977 if (is_object($user)) {
978 $namesource = $user->firstname ? $user->firstname : ($user->login ? $user->login :
'');
983 if ($defaultmode ===
'native') {
984 $defaultmode =
'cloud';
994 if ($defaultmode ===
'cloud' && !empty(
$conf->dol_use_jmobile)) {
999 'mode' => $defaultmode,
1000 'labels' => $ai_translations,
1011 'autoContext' =>
getDolGlobalInt(
'AI_CHAT_CONTEXT_AUTO_EXCHANGES', 2),
1018 'modelPresets' =>
getDolGlobalInt(
'AI_SUGGESTS_PRESETS_TO_TRY_TO_CHANGE_MODEL_DYNAMICALLY', 0),
1022 'currency' =>
$conf->currency,
1023 'locale' => str_replace(
'_',
'-', $langs->getDefaultLang()),
1024 'urlRoot' => DOL_URL_ROOT,
1030 'userInitial' => $userinitial,
1033 'historyKey' =>
'aiChatHistory_'.((int)
$conf->entity).
'_'.((int) $user->id),
1048 global $langs, $user,
$conf;
1055 $out .=
'<div class="ai-chat-container'.($mode ===
'popover' ?
' ai-in-popover' :
'').
'"';
1057 if ($mode ===
'page') {
1058 $out .=
' data-ai-autoinit="1"';
1059 if ((
int) $openconversation > 0) {
1061 $out .=
' data-ai-open-conversation="'.((int) $openconversation).
'"';
1067 $out .=
'<div class="chat-header">';
1068 if ($mode ===
'popover') {
1070 $title = img_picto(
'',
'fa-robot',
'', 0, 0, 0,
'',
'paddingright').$langs->trans(
"AIAssistant");
1071 $title =
'<a href="'.dol_buildpath(
'/ai/assistant/index.php', 1).
'" class="ai-header-link" title="'.
dol_escape_htmltag($langs->trans(
"AIOpenFullPage")).
'">'.$title.
'</a>';
1072 $out .=
'<span class="chat-header-text">';
1073 $out .=
'<h2>'.$title.
'</h2>';
1076 if ($aiprovider !==
'') {
1077 $out .=
'<span class="chat-header-status" title="'.dol_escape_htmltag($langs->trans(
"AIProviderInUse")).
'">'.
dol_escape_htmltag($aiprovider).
'</span>';
1082 $out .=
'<div class="chat-header-id">';
1085 $out .=
'<span class="chat-header-text">';
1086 $out .=
'<span class="chat-header-title hideonsmartphone">'.img_picto(
'',
'fa-robot',
'', 0, 0, 0,
'',
'paddingright').$langs->trans(
"AIAssistant").
'</span>';
1088 if ($aiprovider !==
'') {
1089 $out .=
'<span class="chat-header-status" title="'.dol_escape_htmltag($langs->trans(
"AIProviderInUse")).
'">'.
dol_escape_htmltag($aiprovider).
'</span>';
1094 $out .=
'<div class="header-controls">';
1097 $modelSelectTitle = $langs->transnoentitiesnoconv(
"AIModelToUse");
1099 if ($aiproviderurl !==
'') {
1100 $modelSelectTitle .=
"\n".$langs->transnoentitiesnoconv(
"URL").
': '.$aiproviderurl;
1102 $out .=
'<select id="model-select" class="engine-select model-select" title="'.dol_escape_htmltag($modelSelectTitle, 0, 1).
'">';
1103 $autoLabel = $langs->transnoentitiesnoconv(
"AIModelAuto");
1105 if ($defaultModel !==
'') {
1106 $autoLabel .=
' ('.$defaultModel.
')';
1108 $out .=
'<option value="" data-picto="ai-picto-sparkle">'.dol_escape_htmltag($autoLabel).
'</option>';
1109 $out .=
'</select>';
1113 $out .=
'<select id="engine-select" class="engine-select">';
1115 $out .=
'<option value="text" data-picto="fa fa-keyboard">'.$langs->transnoentitiesnoconv(
"OptionTextOnly").
'</option>';
1119 if (empty(
$conf->dol_use_jmobile)) {
1120 $out .=
'<option value="cloud" data-picto="fa fa-cloud">'.$langs->transnoentitiesnoconv(
"OptionCloudFast").
'</option>';
1124 $out .=
'<option value="whisper" data-picto="fa fa-microphone" data-experimental="1">'.$langs->transnoentitiesnoconv(
"OptionWhisperLocal").
'</option>';
1129 $out .=
'</select>';
1133 $out .=
'<button type="button" id="clear-btn" class="icon-btn" title="'.dol_escape_htmltag($langs->trans(
"AINewConversation")).
'">';
1134 $out .= img_picto(
'',
'fa-trash').
' <span class="ai-btn-label">'.$langs->trans(
"Reset").
'</span>';
1135 $out .=
'</button>';
1137 $out .=
'<button type="button" id="ai-history-btn" class="icon-btn ai-window-btn" title="'.dol_escape_htmltag($langs->trans(
"AIHistory")).
'"><i class="fa fa-history"></i></button>';
1138 if ($mode ===
'popover') {
1142 $out .=
'<button type="button" id="ai-expand-btn" class="icon-btn ai-window-btn" title="'.dol_escape_htmltag($langs->trans(
"AIOpenFullPage")).
'" data-fullscreen-url="'.
dol_buildpath(
'/ai/assistant/index.php', 1).
'"><i class="fa fa-expand"></i></button>';
1143 $out .=
'<button type="button" id="ai-close-btn" class="icon-btn ai-window-btn" title="'.dol_escape_htmltag($langs->trans(
"Close")).
'"><i class="fa fa-times"></i></button>';
1148 if ($mode ===
'page') {
1152 $out .=
'<div class="ai-chat-body">';
1153 $out .=
'<aside id="ai-history-sidebar" class="ai-history-sidebar" aria-label="'.dol_escape_htmltag($langs->trans(
"AIHistory")).
'">';
1154 $out .=
'<div class="ai-sidebar-head">';
1155 $out .=
'<button type="button" id="ai-new-chat" class="ai-sidebar-new"><i class="fa fa-plus"></i> '.$langs->trans(
"AINewConversation").
'</button>';
1156 $out .=
'<button type="button" id="ai-sidebar-collapse" class="ai-sidebar-collapse" title="'.dol_escape_htmltag($langs->trans(
"AIHideConversations")).
'"><i class="fa fa-angle-double-left"></i></button>';
1158 $out .=
'<div id="ai-sidebar-list" class="ai-sidebar-list"><div class="opacitymedium ai-sidebar-empty">…</div></div>';
1161 $out .=
'<button type="button" id="ai-sidebar-expand" class="ai-sidebar-expand" title="'.dol_escape_htmltag($langs->trans(
"AIShowConversations")).
'"><i class="fa fa-angle-double-right"></i></button>';
1162 $out .=
'<div class="ai-chat-main">';
1166 $out .=
'<div id="chat-history" class="chat-history">';
1167 if ($mode ===
'popover') {
1169 $out .=
'<div class="msg system">'.$langs->trans(
"AIWelcomeMessage").
'</div>';
1174 $welcomename = $user->firstname ? $user->firstname : (is_object($user) ? $user->login :
'');
1175 $quickcards = array(
1176 array(
'icon' =>
'fa-file-invoice-dollar',
'key' =>
'Invoices'),
1177 array(
'icon' =>
'fa-chart-line',
'key' =>
'Revenue'),
1178 array(
'icon' =>
'fa-coins',
'key' =>
'Finance'),
1179 array(
'icon' =>
'fa-warehouse',
'key' =>
'Inventory'),
1181 $out .=
'<div class="chat-welcome">';
1182 $out .=
'<div class="chat-welcome-avatar">'.img_picto(
'',
'fa-robot').
'</div>';
1183 $out .=
'<h2 class="chat-welcome-title">'.dol_escape_htmltag($langs->trans(
"AIGreeting", $welcomename)).
'</h2>';
1184 $out .=
'<p class="chat-welcome-subtitle">'.dol_escape_htmltag($langs->trans(
"AIGreetingSubtitle")).
'</p>';
1185 $out .=
'<div class="chat-welcome-actions">';
1186 foreach ($quickcards as $card) {
1187 $out .=
'<button type="button" class="ai-quick-card" data-prompt="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"AIQuick".$card[
'key'].
"Prompt")).
'">';
1188 $out .=
'<span class="ai-quick-icon">'.img_picto(
'', $card[
'icon']).
'</span>';
1189 $out .=
'<span class="ai-quick-text">';
1190 $out .=
'<span class="ai-quick-title">'.dol_escape_htmltag($langs->trans(
"AIQuick".$card[
'key'].
"Title")).
'</span>';
1191 $out .=
'<span class="ai-quick-desc">'.dol_escape_htmltag($langs->trans(
"AIQuick".$card[
'key'].
"Desc")).
'</span>';
1193 $out .=
'</button>';
1202 $out .=
'<div class="chat-controls">';
1206 $out .=
'<div id="file-chip-area" class="file-chip-area ai-hidden"></div>';
1207 $out .=
'<div class="chat-input-pill">';
1209 $out .=
'<div id="upload-wrapper" class="upload-wrapper">';
1210 $out .=
'<input type="file" id="file-upload" multiple accept=".pdf,.txt,.xml,.png,.jpg,.jpeg,.heic,.heif,.doc,.docx,.xls,.xlsx,.odt,.ods" style="display: none;">';
1211 $out .=
'<button type="button" id="upload-btn" class="round-btn" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"AttachFile")).
'">'.img_picto(
'',
'fa-paperclip').
'</button>';
1214 $out .=
'<div id="mic-wrapper" class="mic-wrapper ai-hidden">';
1215 $out .=
'<button type="button" id="mic-btn" class="round-btn mic-btn" title="'.dol_escape_htmltag($langs->trans(
"ToggleMicrophone")).
'">'.img_picto(
'',
'fa-microphone').
'</button>';
1218 $out .=
'<textarea id="user-input" class="ia-input" rows="1"';
1219 if (empty(
$conf->dol_optimize_smallscreen)) {
1220 $out .=
' placeholder="'.dol_escape_htmltag($langs->trans(
"TypeYourQuestion")).
'"';
1222 $out .=
' autocomplete="off" spellcheck="false"></textarea>';
1224 $out .=
'<button type="button" id="send-btn" class="chat-send-btn" title="'.dol_escape_htmltag($langs->trans(
"SendPrompt")).
'">'.img_picto(
'',
'fa-paper-plane').
'</button>';
1228 $out .=
'<div id="status-bar"></div>';
1230 if ($mode ===
'page') {
1263 if (!empty($_SERVER[
'HTTP_X_CSRF_TOKEN'])) {
1264 $token = (string) $_SERVER[
'HTTP_X_CSRF_TOKEN'];
1266 $token =
GETPOST(
'token',
'alpha');
1269 $sessiontokens = array();
1270 if (!empty($_SESSION[
'token'])) {
1271 $sessiontokens[] = (string) $_SESSION[
'token'];
1273 if (!empty($_SESSION[
'newtoken'])) {
1274 $sessiontokens[] = (string) $_SESSION[
'newtoken'];
1278 foreach ($sessiontokens as $sessiontoken) {
1279 if (!empty($token) && hash_equals($sessiontoken, $token)) {
1288 .
' refused by CSRF protection (invalid or missing token).',
1292 http_response_code(403);
1293 header(
'Content-Type: application/json');
1294 echo json_encode(array(
'error' =>
'Invalid CSRF token'));
1319 if (!is_array($payload) || $elementtype ===
'') {
1323 static $cache = array();
1324 if (!isset($cache[$elementtype])) {
1325 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
1327 $extrafields->fetch_name_optionals_label($elementtype);
1328 $attrs = $extrafields->attributes[$elementtype] ?? array();
1329 $personal = array();
1330 foreach (($attrs[
'personal_data'] ?? array()) as $code => $flag) {
1331 if (!empty($flag)) {
1332 $personal[] =
'options_'.$code;
1335 $cache[$elementtype] = $personal;
1337 if (empty($cache[$elementtype])) {
1341 foreach ($payload as $key => $value) {
1342 if ($key ===
'array_options' && is_array($value)) {
1343 foreach ($cache[$elementtype] as $personalKey) {
1344 unset($payload[$key][$personalKey]);
1346 } elseif (is_array($value)) {
1367 if (preg_match_all(
'/[\p{L}\p{N}]+/u', (
string) $text, $m, PREG_OFFSET_CAPTURE)) {
1368 foreach ($m[0] as $w) {
1370 if (class_exists(
'Normalizer')) {
1372 $norm = (string) preg_replace(
'/\p{Mn}+/u',
'', (
string) Normalizer::normalize($norm, Normalizer::FORM_D));
1374 $out[] = array($norm, (
int) $w[1], (
int) $w[1] + strlen((
string) $w[0]));
1393 $langs->loadLangs(array(
'companies',
'bills'));
1395 'supplier' => array(
'supplier',
'vendor', $langs->transnoentitiesnoconv(
'Supplier')),
1396 'customer' => array(
'customer', $langs->transnoentitiesnoconv(
'Customer'))
1400 foreach ($stems as $nature => $list) {
1401 foreach ($list as $kw) {
1403 $kw = isset($kww[0]) ? $kww[0][0] :
'';
1406 foreach ($words as $w) {
1407 if (
dol_strlen($stem) >= 5 && strpos($w, $stem) === 0) {
1408 $found[$nature] =
true;
1415 return count($found) === 1 ? (string) key($found) :
'';
1435 if (min($la, $lb) < 4 || abs($la - $lb) > 2) {
1439 return ($la < $lb) ? (strpos($b, $a) === 0) : (strpos($a, $b) === 0);
1452 $lp = count($phrase);
1454 for ($j = 0; $j + $lp <= $ln; $j++) {
1456 for ($k = 0; $k < $lp; $k++) {
1493 if (empty($words)) {
1498 foreach ($stopwords as $sw) {
1500 $stop[$sww[0]] =
true;
1504 $legal = array_flip(array(
'llc',
'ltd',
'limited',
'inc',
'corp',
'co',
'plc',
'gmbh',
'ag',
'sa',
'sas',
'sarl',
'srl',
'spa',
'bv',
'nv',
'pc',
'αε',
'ικε',
'επε',
'οε',
'εε',
'μον'));
1510 foreach ($words as $w) {
1511 if (
dol_strlen($w[0]) >= 3 && !ctype_digit($w[0])) {
1512 $lookup[$w[0]] = substr((
string) $text, $w[1], $w[2] - $w[1]);
1513 if (count($lookup) >= $maxwords) {
1518 if (empty($lookup)) {
1524 $sql =
"SELECT s.rowid, s.nom, s.name_alias, s.client, s.fournisseur, s.town";
1525 $sql .=
" FROM ".$db->prefix().
"societe as s";
1526 $sql .=
" WHERE s.entity IN (".getEntity(
'societe').
")";
1527 $sql .=
" AND (1 = 0";
1528 foreach ($lookup as $norm => $raw) {
1531 $forms = array($raw, $norm);
1535 foreach (array_unique($forms) as $w) {
1536 $sql .=
" OR s.nom LIKE '".$db->escape($db->escapeforlike($w)).
"%' OR s.name_alias LIKE '".$db->escape($db->escapeforlike($w)).
"%'";
1540 $sql .=
" LIMIT 1000";
1541 $resql = $db->query($sql);
1543 dol_syslog(__FUNCTION__.
" ".$db->lasterror(), LOG_ERR);
1547 $companies = array();
1548 $wordlists = array();
1549 while ($obj = $db->fetch_object($resql)) {
1550 $id = (int) $obj->rowid;
1551 $companies[
$id] = array(
'id' =>
$id,
'name' => (
string) $obj->nom,
'name_alias' => (
string) $obj->name_alias,
'client' => (
int) $obj->client,
'fournisseur' => (
int) $obj->fournisseur,
'town' => (
string) $obj->town,
'visible' =>
false);
1552 foreach (array((
string) $obj->nom, (
string) $obj->name_alias) as $source) {
1555 $wordlists[] = array(
$id, $ws);
1560 if (empty($wordlists)) {
1568 $count = count($words);
1570 while ($i < $count) {
1572 for ($len = min(10, $count - $i); $len >= 1; $len--) {
1573 $phrase = array_column(array_slice($words, $i, $len), 0);
1574 $key = implode(
' ', $phrase);
1580 $distinctive =
false;
1582 foreach ($phrase as $pw) {
1583 if (
dol_strlen($pw) >= 4 && empty($stop[$pw]) && !isset($legal[$pw]) && !ctype_digit($pw)) {
1584 $distinctive =
true;
1596 $exactIds = array();
1597 $firstIds = array();
1598 foreach ($wordlists as $wl) {
1599 list(
$id, $ws) = $wl;
1600 if (count($ws) < $len) {
1607 foreach ($phrase as $pw) {
1609 foreach ($free as $fk => $nw) {
1611 $strict = $strict && ($pw === $nw);
1625 $whole = ($strict && empty($free));
1631 $exactIds[
$id] =
true;
1634 $firstIds[
$id] =
true;
1637 if (!$distinctive) {
1643 $hit = array($len, !empty($exactIds) ? array_keys($exactIds) : array_keys($ids), $key, !empty($exactIds), count($firstIds) === count($ids));
1646 if ($hit ===
null) {
1650 list($len, $ids, $key, $exact, $first) = $hit;
1651 $start = $words[$i][1];
1652 $end = $words[$i + $len - 1][2];
1654 foreach ($ids as
$id) {
1655 $cands[
$id] = $companies[
$id];
1657 if ($nature ===
'supplier' || $nature ===
'customer') {
1658 $narrow = array_filter($cands,
1663 function (
$c) use ($nature) {
1664 return $nature ===
'supplier' ? (
$c[
'fournisseur'] == 1) : in_array(
$c[
'client'], array(1, 2, 3));
1667 if (!empty($narrow)) {
1671 $matches[] = array(
'phrase' => $key,
'raw' => substr((
string) $text, $start, $end - $start),
'start' => $start,
'end' => $end,
'exact' => $exact,
'first' => $first,
'words' => $len,
'candidates' => $cands);
1677 if (!empty($matches) && $user->hasRight(
'societe',
'lire')) {
1679 foreach ($matches as $mt) {
1680 $allIds = array_merge($allIds, array_keys($mt[
'candidates']));
1683 if ($user->hasRight(
'societe',
'client',
'voir')) {
1684 $seen = array_flip($allIds);
1685 } elseif (!empty($allIds)) {
1686 $sql =
"SELECT sc.fk_soc FROM ".$db->prefix().
"societe_commerciaux as sc";
1687 $sql .=
" WHERE sc.fk_user = ".((int) $user->id).
" AND sc.fk_soc IN (".$db->sanitize(implode(
',', array_map(
'intval', $allIds))).
")";
1688 $resql = $db->query($sql);
1689 while ($resql && ($obj = $db->fetch_object($resql))) {
1690 $seen[(int) $obj->fk_soc] =
true;
1693 foreach ($matches as $mi => $mt) {
1694 foreach ($mt[
'candidates'] as
$id =>
$c) {
1695 $matches[$mi][
'candidates'][
$id][
'visible'] = isset($seen[
$id]);
1716 $out = array(
'text' => (
string) $text,
'blocks' => array());
1717 $intros = array_unique(array($langs->transnoentitiesnoconv(
'DocContextIntro'),
'Document Content:'));
1718 $outros = array_unique(array($langs->transnoentitiesnoconv(
'DocContextOutro'),
'End of document'));
1720 foreach ($intros as $v) {
1721 $introRe[] = preg_quote((
string) $v,
'/');
1724 foreach ($outros as $v) {
1725 $outroRe[] = preg_quote((
string) $v,
'/');
1727 $introRe = implode(
'|', $introRe);
1728 $outroRe = implode(
'|', $outroRe);
1730 if (!preg_match_all(
'/(?:'.$introRe.
')\s.*?---\s*(?:'.$outroRe.
')\s*---/su', $out[
'text'], $m)) {
1733 foreach ($m[0] as $i => $block) {
1734 $mark =
"\x02DOC".$i.
"\x02";
1735 $pos = strpos($out[
'text'], $block);
1736 if ($pos ===
false) {
1739 $out[
'text'] = substr($out[
'text'], 0, $pos).$mark.substr($out[
'text'], $pos + strlen($block));
1740 $out[
'blocks'][$mark] = $block;
1755 return empty($blocks) ? (string) $text : strtr((
string) $text, $blocks);
1775 $names[] = $mt[
'raw'];
1776 foreach ($mt[
'candidates'] as
$c) {
1777 $names[] =
$c[
'name'];
1778 $names[] =
$c[
'name_alias'];
1781 if (is_array($data)) {
1782 $keys = array(
'name' =>
true,
'nom' =>
true,
'name_alias' =>
true,
'socname' =>
true,
'thirdparty_name' =>
true,
'company' =>
true);
1783 array_walk_recursive($data,
1789 function ($value, $key) use (&$names, $keys) {
1790 if (is_string($key) && isset($keys[$key]) && is_string($value)) {
1797 return array_values(array_unique(array_filter($names,
1819 static $unitNames =
null;
1825 if (is_numeric($want)) {
1828 if ($unitNames ===
null) {
1830 $langs->load(
'products');
1831 $unitNames = array();
1832 $resql = $db->query(
"SELECT rowid, code, label, short_label FROM ".$db->prefix().
"c_units WHERE active = 1 LIMIT 500");
1833 while ($resql && ($obj = $db->fetch_object($resql))) {
1835 if ($obj->code ===
'P') {
1839 $unitNames[(int) $obj->rowid] = $names;
1842 $forms = array_unique(array($want, (
string) preg_replace(
'/s$/',
'', $want), (
string) preg_replace(
'/es$/',
'', $want)));
1844 foreach ($unitNames as $rowid => $names) {
1845 if (array_intersect($forms, $names)) {
1846 $ids[$rowid] =
true;
1850 return count($ids) === 1 ? (int) key($ids) : 0;
1876 $out = array(
'name' =>
'',
'ref' =>
'',
'lines' => array(),
'error' =>
'');
1877 $text = trim((
string) $text);
1879 if (preg_match(
'/(?:^|\s)ref:(\S+)/i', $text, $m)) {
1880 $out[
'ref'] = $m[1];
1881 $text = trim((
string) preg_replace(
'/(?:^|\s)ref:\S+/i',
' ', $text));
1887 $asProduct = array();
1888 if (preg_match_all(
'/"([^"]+)"/', $text, $m) > 0) {
1889 foreach ($m[0] as $i => $whole) {
1890 $mark =
"\x01".$i.
"\x01";
1891 $text = str_replace($whole, $mark, $text);
1892 $asName[$mark] = trim($m[1][$i]);
1893 $asProduct[$mark] =
'"'.trim($m[1][$i]).
'"';
1896 $num =
'\d+(?:[.,]\d+)?';
1897 if (!preg_match(
'/(?:^|\s)('.$num.
')(?=\s|$)/', $text, $m, PREG_OFFSET_CAPTURE)) {
1898 $out[
'name'] = strtr($text, $asName);
1899 $out[
'error'] =
'nolines';
1902 $start = (int) $m[1][1];
1903 $out[
'name'] = trim(strtr(substr($text, 0, $start), $asName));
1904 $rest = substr($text, $start);
1905 foreach (preg_split(
'/\s*;\s*|,\s+(?=\d)/', $rest) ?: array() as $group) {
1906 $tokens = preg_split(
'/\s+/', trim((
string) $group), -1, PREG_SPLIT_NO_EMPTY) ?: array();
1908 $out[
'lines'][] = $line;
1911 if (empty($out[
'lines'])) {
1912 $out[
'error'] =
'nolines';
1932 $num =
'/^\d+(?:[.,]\d+)?$/';
1933 if (empty($tokens) || !preg_match($num, $tokens[0])) {
1936 $line = array(
'qty' => (
float) str_replace(
',',
'.', array_shift($tokens)));
1937 if (count($tokens) >= 2 && preg_match($num, (
string) end($tokens))) {
1938 $line[
'subprice'] = (float) str_replace(
',',
'.', (
string) array_pop($tokens));
1941 $line[
'unit'] = array_shift($tokens);
1943 if (empty($tokens)) {
1946 $line[
'product_ref'] = strtr(implode(
' ', $tokens), $asProduct);
1951 if ($user !==
null && count($tokens) >= 3 && !
aiDocumentProductExists($db, $user, $line[
'product_ref'], $side)) {
1952 $n = count($tokens);
1953 for ($i = 1; $i < $n - 1; $i++) {
1954 if (!preg_match($num, $tokens[$i]) || preg_match($num, $tokens[$i + 1])) {
1957 $left = array_slice($tokens, 0, $i);
1959 unset($first[
'subprice']);
1960 if (count($left) >= 2 && preg_match($num, (
string) end($left))) {
1961 $first[
'subprice'] = (float) str_replace(
',',
'.', (
string) array_pop($left));
1963 $first[
'product_ref'] = strtr(implode(
' ', $left), $asProduct);
1967 $right = array_slice($tokens, $i);
1968 if (isset($line[
'subprice'])) {
1969 $right[] = (string) $line[
'subprice'];
1972 $allFound = !empty($more);
1973 foreach ($more as $next) {
1980 return array_merge(array($first), $more);
1985 return array($line);
2000 $search = trim(str_replace(
'"',
' ', ltrim((
string) $typed,
'#')));
2002 return $search !==
'' && !empty(
aiFindProducts($db, $user, $search, $side, 1));
2021 if ($user->hasRight(
'produit',
'lire')) {
2024 if ($user->hasRight(
'service',
'lire')) {
2027 $words = preg_split(
'/\s+/', trim((
string) $text), -1, PREG_SPLIT_NO_EMPTY) ?: array();
2028 if (empty($types) || empty($words)) {
2031 $sql =
"SELECT p.rowid, p.ref, p.label, p.price, p.fk_unit, p.stock";
2032 $sql .=
" FROM ".$db->prefix().
"product as p";
2033 $sql .=
" WHERE p.entity IN (".getEntity(
'product').
")";
2034 $sql .=
" AND p.fk_product_type IN (".$db->sanitize(implode(
',', $types)).
")";
2035 $sql .= ($side ===
'buy') ?
" AND p.tobuy = 1" :
" AND p.tosell = 1";
2036 foreach (array_slice($words, 0, 6) as $w) {
2037 $like = $db->escape($db->escapeforlike($w));
2038 $sql .=
" AND (p.ref LIKE '%".$like.
"%' OR p.label LIKE '%".$like.
"%')";
2040 $sql .=
" ORDER BY p.ref";
2041 $sql .=
" LIMIT 200";
2042 $resql = $db->query($sql);
2044 dol_syslog(__FUNCTION__.
' '.$db->lasterror(), LOG_ERR);
2050 while ($obj = $db->fetch_object($resql)) {
2051 $row = array(
'id' => (
int) $obj->rowid,
'ref' => (
string) $obj->ref,
'label' => (
string) $obj->label,
'price' => (
float) $obj->price,
'fk_unit' => (
int) $obj->fk_unit,
'stock' => (
float) $obj->stock,
'exact' =>
false);
2053 $row[
'exact'] =
true;
2061 return array_slice(array_merge($exact, $other), 0, $limit);
2077 if ($socid <= 0 || !$user->hasRight($side ===
'buy' ?
'fournisseur' :
'facture', $side ===
'buy' ?
'facture' :
'lire', $side ===
'buy' ?
'lire' :
'')
2078 || (!$user->hasRight(
'produit',
'lire') && !$user->hasRight(
'service',
'lire'))) {
2086 $doc = ($side ===
'buy') ?
'facture_fourn' :
'facture';
2087 $det = ($side ===
'buy') ?
'facture_fourn_det' :
'facturedet';
2088 $link = ($side ===
'buy') ?
'fk_facture_fourn' :
'fk_facture';
2089 $sql =
"SELECT p.rowid, p.ref, p.label, p.price, p.fk_unit, p.stock, MAX(f.rowid) as lastdoc";
2090 $sql .=
" FROM ".$db->prefix().$db->sanitize($det).
" as d";
2091 $sql .=
" INNER JOIN ".$db->prefix().$db->sanitize($doc).
" as f ON f.rowid = d.".$db->sanitize($link);
2092 $sql .=
" INNER JOIN ".$db->prefix().
"product as p ON p.rowid = d.fk_product";
2093 $sql .=
" WHERE f.fk_soc = ".((int) $socid);
2094 $sql .=
" AND f.entity IN (".getEntity($side ===
'buy' ?
'supplier_invoice' :
'invoice').
")";
2095 $sql .= ($side ===
'buy') ?
" AND p.tobuy = 1" :
" AND p.tosell = 1";
2096 $sql .=
" GROUP BY p.rowid, p.ref, p.label, p.price, p.fk_unit, p.stock";
2097 $sql .=
" ORDER BY lastdoc DESC";
2098 $sql .=
" LIMIT ".((int) $limit);
2099 $resql = $db->query($sql);
2101 while ($resql && ($obj = $db->fetch_object($resql))) {
2102 $out[] = array(
'id' => (
int) $obj->rowid,
'ref' => (
string) $obj->ref,
'label' => (
string) $obj->label,
'price' => (
float) $obj->price,
'fk_unit' => (
int) $obj->fk_unit,
'stock' => (
float) $obj->stock,
'exact' =>
false);
2121 if (empty($route)) {
2122 return dol_ucfirst(str_replace(
'_',
' ', (
string) $name));
2127 'invoices' => array(
'bills',
'Invoice',
'Invoices'),
2128 'supplier_invoices' => array(
'bills',
'SupplierInvoice',
'BillsSuppliers'),
2129 'orders' => array(
'orders',
'Order',
'Orders'),
2130 'supplier_orders' => array(
'orders',
'SupplierOrder',
'SuppliersOrders'),
2131 'proposals' => array(
'propal',
'Proposal',
'Proposals'),
2132 'thirdparties' => array(
'companies',
'ThirdParty',
'ThirdParties'),
2133 'products' => array(
'products',
'Product',
'Products'),
2134 'projects' => array(
'main',
'Project',
'Projects'),
2135 'tasks' => array(
'projects',
'Task',
'Tasks'),
2136 'tickets' => array(
'ticket',
'Ticket',
'Tickets'),
2137 'warehouses' => array(
'stocks',
'Warehouse',
'Warehouses'),
2138 'stockmovements' => array(
'stocks',
'StockMovement',
'StockMovements'),
2139 'categories' => array(
'main',
'Category',
'Categories'),
2140 'interventions' => array(
'interventions',
'Intervention',
'Interventions'),
2141 'contracts' => array(
'contracts',
'Contract',
'Contracts'),
2142 'shipments' => array(
'sendings',
'Shipment',
'Shipments'),
2143 'receptions' => array(
'receptions',
'Reception',
'Receptions'),
2144 'members' => array(
'members',
'Member',
'Members'),
2145 'expensereports' => array(
'main',
'ExpenseReport',
'ExpenseReports'),
2146 'bankaccounts' => array(
'banks',
'BankAccount',
'BankAccounts'),
2147 'donations' => array(
'donations',
'Donation',
'Donations'),
2148 'agendaevents' => array(
'main',
'Event',
'Events'),
2149 'holidays' => array(
'holiday',
'Holiday',
'Holidays'),
2150 'users' => array(
'main',
'User',
'Users'),
2151 'supplier_proposals' => array(
'supplier_proposal',
'SupplierProposalShort',
'SupplierProposalsShort'),
2152 'boms' => array(
'mrp',
'BillOfMaterials',
'Bom'),
2153 'mos' => array(
'mrp',
'ManufacturingOrder',
'MOs'),
2154 'workstations' => array(
'mrp',
'Workstation',
'Workstations'),
2155 'productlots' => array(
'productbatch',
'Batch',
''),
2156 'memberstypes' => array(
'members',
'MemberType',
'MembersTypes'),
2157 'subscriptions' => array(
'members',
'Subscription',
'Subscriptions'),
2158 'partnerships' => array(
'partnership',
'Partnership',
'Partnerships'),
2159 'multicurrencies' => array(
'main',
'Currency',
''),
2160 'socialcontributions' => array(
'compta',
'SocialContribution',
'SocialContributions'),
2161 'vatpayments' => array(
'compta',
'VATDeclaration',
'VATDeclarations'),
2162 'variouspayments' => array(
'banks',
'VariousPayment',
'VariousPayments')
2164 $endpoint = (string) $route[
'endpoint'];
2166 $several = trim((
string) preg_replace(
'/\s*\(.*\)\s*$/',
'', (
string) $route[
'label']));
2167 $several = ($several !==
'') ? $several : str_replace(
'_',
' ', $endpoint);
2168 $one = (string) preg_replace(array(
'/ies$/',
'/(?<!s)s$/'), array(
'y',
''), $several);
2169 if (isset($nouns[$endpoint])) {
2170 $langs->load($nouns[$endpoint][0]);
2171 $one = $langs->transnoentitiesnoconv($nouns[$endpoint][1]);
2172 if ($nouns[$endpoint][2] !==
'') {
2173 $several = $langs->transnoentitiesnoconv($nouns[$endpoint][2]);
2180 'list' => array(
'AIToolTitleList', $several),
2181 'get' => array(
'AIToolTitleGet', $one),
2182 'get_by_ref' => array(
'AIToolTitleGetByRef', $one),
2183 'get_by_email' => array(
'AIToolTitleGetByEmail', $one),
2184 'get_by_barcode' => array(
'AIToolTitleGetByBarcode', $one),
2185 'get_by_code' => array(
'AIToolTitleGetByCode', $one),
2186 'get_by_track_id' => array(
'AIToolTitleGetByTrackId', $one),
2187 'get_by_thirdparty' => array(
'AIToolTitleGetByThirdparty', $one),
2188 'create' => array(
'AIToolTitleCreate', $one),
2189 'update' => array(
'AIToolTitleUpdate', $one),
2190 'delete' => array(
'AIToolTitleDelete', $one),
2191 'validate' => array(
'AIToolTitleValidate', $one),
2192 'add_payment' => array(
'AIToolTitleAddPayment', $one),
2193 'add_line' => array(
'AIToolTitleAddLine', $one)
2195 $langs->load(
'other');
2196 $suffix = (string) $route[
'suffix'];
2197 if (isset($verbs[$suffix])) {
2198 return dol_ucfirst($langs->transnoentitiesnoconv($verbs[$suffix][0], $verbs[$suffix][1]));
2203 $what = (string) preg_replace(array(
'/_list$/',
'/^get_/'),
'', $suffix);
2205 'contacts' => array(
'companies',
'Contacts'),
2206 'payments' => array(
'bills',
'Payments'),
2207 'lines' => array(
'withdrawals',
'Lines'),
2208 'categories' => array(
'main',
'Categories'),
2209 'supplier_categories' => array(
'categories',
'SuppliersCategoriesShort'),
2210 'stock' => array(
'stocks',
'Stock'),
2211 'timespent' => array(
'projects',
'TimeSpent'),
2212 'discounts' => array(
'bills',
'Discounts'),
2213 'sales_representatives' => array(
'commercial',
'SalesRepresentatives'),
2214 'shipments' => array(
'sendings',
'Shipments'),
2215 'subscriptions' => array(
'members',
'Subscriptions')
2217 if (isset($words[$what])) {
2218 $langs->load($words[$what][0]);
2219 $what =
dol_strtolower($langs->transnoentitiesnoconv($words[$what][1]));
2221 $what = str_replace(
'_',
' ', $what);
2224 return dol_ucfirst($langs->transnoentitiesnoconv(
'AIToolTitleOther', $one, $what));
2236 $text = (string) preg_replace(
'/\s*through the Dolibarr REST API \(auto-generated tool\)\.?/i',
'', (
string) $description);
2238 return trim((
string) preg_replace(
'/\s{2,}/',
' ', $text));
$id
Support class for third parties, contacts, members, users or resources.
dolibarr_set_const($db, $name, $value, $type='chaine', $visible=0, $note='', $entity=1)
Insert a parameter (key,value) into database (delete old key then insert it again).
testAIConnection(string $service, string $key, string $url)
Tests the connection to an AI service using its API key and URL by sending message "Hello".
getListOfAIFeatures()
Prepare admin pages header.
aiFindProducts($db, $user, $text, $side='sell', $limit=10)
Products of the catalogue matching what a user typed: every word must be in the ref or the label,...
aiAdminPrepareHead()
Prepare admin pages header.
getAiProviderModelList($db, $forcerefresh=false)
Return the list of model ids offered by the configured AI provider, with a 1-hour cache in the consta...
getListOfAIServices()
Get list of available ai services.
aiRestoreDocumentBlocks($text, array $blocks)
Put back, unchanged, the documents set aside by aiExtractDocumentBlocks().
aiUnitIdFromName($db, $name)
Unit id from the word a user used for it: code, short label or label, in the user's language,...
aiFindThirdpartiesInText($db, $user, $text, $nature='', $stopwords=array(), $maxwords=80)
Third parties named in a text, by the words of their name or trade name (name_alias),...
aiParseDocumentCommand($db, $text, $user=null, $side='sell')
Read a one-line document command of the chat palette, e.g.
aiThirdpartyNamesToMask($db, $user, $text, $stopwords=array(), $data=null)
Every form of the third party names found in a text or carried by a tool result, to mask with Privacy...
aiDocumentProductExists($db, $user, $typed, $side)
Whether the words of a command line name at least one product the user may put on that kind of docume...
getAiAssistantDefaultModel()
Resolve the text model used by the AI Assistant when the picker is on "Auto" (same resolution order a...
aiNameWordsEqual($a, $b)
Whether two words of a name are the same word: equal, or the same word with a different ending ("solu...
aiThirdpartyNatureHint($text, $langs)
Nature of third party a text points at, from its own words: "supplier" when it speaks of a supplier (...
getAiChatAssistantConfig()
Build the configuration array consumed by the AI Assistant chat frontend (ai/js/ai_assistant....
ai_validate_attachments(array $attachments, &$error)
Validate chat attachments before they reach any LLM provider.
aiPaletteToolTitle($langs, $name, $route)
Plain name of a tool for the palette of the chat: "Get invoice" rather than api_invoices_get.
aiTruncateForLog($text, $max=60000)
Trim a payload for the request log, keeping the beginning and the end.
getAiAssistantProviderUrl()
Resolve the API URL used by the AI Assistant for the configured provider (same resolution order as as...
aiPaletteToolDescription($description)
Description of a tool for the palette: without the sentence every generated bridge tool repeats,...
getListForAIRephraseStyle()
Get list for AI style of writing.
ai_log_request($db, $user, $query, array $response, $provider, float $time, float $confidence, $status, $error='', $rawReq='', $rawRes='', array $context=array(), &$logId=null)
Log AI Request with Raw Payloads.
aiExtractDocumentBlocks($text, $langs)
Set aside the documents a chat message carries, so what is done to the request (third parties resolve...
getAIErrorMessage($result)
Return a user-friendly error message from the error array returned by Ai\generateContent()
aiStripPersonalExtrafields($db, $payload, $elementtype)
Remove extrafields flagged as personal data from an API-shaped payload.
getAiAssistantProviderLabel()
Resolve the AI provider/service currently configured for the AI Assistant (e.g.
getListForAISummarize()
Get list for AI summarize.
aiNameWords($text)
Words of a text as the third party matcher compares them: runs of letters or digits,...
aiNameWordsInSequence($phrase, $name)
Whether the words of a phrase appear in a name one after the other, in the same order each word compa...
aiSuggestClosestModel($missing, array $models)
Suggest the closest available model id for a model that disappeared from the provider's list: same fa...
aiCheckCsrfToken($context='')
Check the anti-CSRF token of a request sent to one of the AI Assistant endpoints.
aiParseDocumentGroup($db, array $tokens, array $asProduct, $user, $side)
Lines of one group of a document command: quantity, optional unit, product, optional unit price.
getAiChatAssistantHtml($mode='page', $openconversation=0)
Build the HTML of the AI Assistant chat interface.
aiRecentProducts($db, $user, $socid, $side='sell', $limit=8)
Products of a third party's latest documents, newest first: what is most likely to be sold (or bought...
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
$context
@method int call_trigger(string $triggerName, ?User $user)
dol_now($mode='gmt')
Return date for now.
dol_ucfirst($string, $encoding="UTF-8")
Convert first character of the first word of a string to upper.
dol_strtolower($string, $encoding="UTF-8")
Convert a string to lower.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
dol_string_unaccent($str)
Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_strtoupper($string, $encoding="UTF-8")
Convert a string to upper.
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode='add', $filterorigmodule='')
Complete or removed entries into a head array (used to build tabs).
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getURLContent($url, $postorget='GET', $param='', $followlocation=1, $addheaders=array(), $allowedschemes=array('http', 'https'), $localurl=0, $ssl_verifypeer=-1, $timeoutconnect=0, $timeoutresponse=0, $otherCurlOptions=array(), $morelogsuffix='')
Function to get a content from an URL (use proxy if proxy defined).
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
checkUserAccessToObject($user, array $featuresarray, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='', $dbt_select='rowid', $parenttableforentity='')
Check that access by a given user to an object is ok.
dolDecrypt($chain, $key='', $patterntotest='')
Decode a string with a symmetric encryption.