dolibarr 25.0.0-alpha
modAi.class.php
1<?php
2/* Copyright (C) 2004-2018 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2018-2019 Nicolas ZABOURI <info@inovea-conseil.com>
4 * Copyright (C) 2019-2024 Frédéric France <frederic.france@free.fr>
5 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
6 * Copyright (C) 2026 Jose Martinez <jose.martinez@pichinov.com>
7 * Copyright (C) 2026 Nick Fragoulis
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
31include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php';
32
37{
43 public function __construct($db)
44 {
45 global $conf;
46
47 $this->db = $db;
48
49 // Id for module (must be unique).
50 // Use here a free id (See in Home -> System information -> Dolibarr for list of used modules id).
51 $this->numero = 4560;
52
53 // Key text used to identify module (for permissions, menus, etc...)
54 $this->rights_class = 'ai';
55
56 // Family can be 'base' (core modules),'crm','financial','hr','projects','products','ecm','technic' (transverse modules),'interface' (link with external tools),'other','...'
57 // It is used to group modules by family in module setup page
58 $this->family = "technic";
59
60 // Module position in the family on 2 digits ('01', '10', '20', ...)
61 $this->module_position = '50';
62
63 // Gives the possibility for the module, to provide his own family info and position of this family (Overwrite $this->family and $this->module_position. Avoid this)
64 //$this->familyinfo = array('myownfamily' => array('position' => '01', 'label' => $langs->trans("MyOwnFamily")));
65 // Module label (no space allowed), used if translation string 'ModuleAiName' not found (Ai is name of module).
66 $this->name = preg_replace('/^mod/i', '', get_class($this));
67
68 // Module description, used if translation string 'ModuleAiDesc' not found (Ai is name of module).
69 $this->description = "AiDescription";
70 // Used only if file README.md and README-LL.md not found.
71 $this->descriptionlong = "AiDescriptionLong";
72
73 // Possible values for version are: 'development', 'experimental', 'dolibarr', 'dolibarr_deprecated' or a version string like 'x.y.z'
74 $this->version = 'dolibarr';
75
76 // Key used in llx_const table to save module status enabled/disabled (where BOOKCAL is value of property name of module in uppercase)
77 $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name);
78
79 // Name of image file used for this module.
80 // If file is in theme/yourtheme/img directory under name object_pictovalue.png, use this->picto='pictovalue'
81 // If file is in module/img directory under name object_pictovalue.png, use this->picto='pictovalue@module'
82 // To use a supported fa-xxx css style of font awesome, use this->picto='xxx'
83 $this->picto = 'fa-magic';
84
85 // Define some features supported by module (triggers, login, substitutions, menus, css, etc...)
86 $this->module_parts = array(
87 // Set this to 1 if module has its own trigger directory (core/triggers)
88 'triggers' => 0,
89 // Set this to 1 if module has its own login method file (core/login)
90 'login' => 0,
91 // Set this to 1 if module has its own substitution function file (core/substitutions)
92 'substitutions' => 0,
93 // Set this to 1 if module has its own menus handler directory (core/menus)
94 'menus' => 0,
95 // Set this to 1 if module overwrite template dir (core/tpl)
96 'tpl' => 0,
97 // Set this to 1 if module has its own barcode directory (core/modules/barcode)
98 'barcode' => 0,
99 // Set this to 1 if module has its own models directory (core/modules/xxx)
100 'models' => 0,
101 // Set this to 1 if module has its own printing directory (core/modules/printing)
102 'printing' => 0,
103 // Set this to 1 if module has its own theme directory (theme)
104 'theme' => 0,
105 // Set this to relative path of css file if module has its own css file
106 'css' => array(
107 // '/ai/css/ai.css.php',
108 ),
109 // Set this to relative path of js file if module must load a js on all pages
110 'js' => array(
111 // '/ai/js/ai.js.php',
112 ),
113 // Set here all hooks context managed by module. To find available hook context, make a "grep -r '>initHooks(' *" on source code. You can also set hook context to 'all'
114 'hooks' => array('all'),
115 // Set this to 1 if features of module are opened to external users
116 'moduleforexternal' => 0,
117 );
118
119 // Data directories to create when module is enabled.
120 // Example: this->dirs = array("/ai/temp","/ai/subdir");
121 $this->dirs = array("/ai/temp");
122
123 // Config pages. Put here list of php page, stored into ai/admin directory, to use to setup module.
124 $this->config_page_url = array("setup.php@ai");
125
126 // Dependencies
127 // A condition to hide module
128 $this->hidden = false;
129 // List of module class names as string that must be enabled if this module is enabled. Example: array('always'=>array('modModuleToEnable1','modModuleToEnable2'), 'FR'=>array('modModuleToEnableFR'...))
130 $this->depends = array();
131 $this->requiredby = array(); // List of module class names as string to disable if this one is disabled. Example: array('modModuleToDisable1', ...)
132 $this->conflictwith = array(); // List of module class names as string this module is in conflict with. Example: array('modModuleToDisable1', ...)
133
134 // The language file dedicated to your module
135 $this->langfiles = array("ai");
136
137 // Prerequisites
138 $this->phpmin = array(7, 0); // Minimum version of PHP required by module
139
140 // Messages at activation
141 $this->warnings_activation = array();
142 $this->warnings_activation_ext = array();
143 //$this->automatic_activation = array('FR'=>'AiWasAutomaticallyActivatedBecauseOfYourCountryChoice');
144
145 // Constants
146 // List of particular constants to add when module is enabled (key, 'chaine', value, desc, visible, 'current' or 'allentities', deleteonunactive)
147 // Example: $this->const=array(1 => array('BOOKCAL_MYNEWCONST1', 'chaine', 'myvalue', 'This is a constant to add', 1),
148 // 2 => array('BOOKCAL_MYNEWCONST2', 'chaine', 'myvalue', 'This is another constant to add', 0, 'current', 1)
149 // );
150 $this->const = array(
151 1 => array('AI_EMAILCLEANER_ENABLED', 'yesno', '0', 'Enable AI cleaner hook for EmailCollector (no business decision)', 0, 'current'),
152 2 => array('AI_EMAILCLEANER_MAX_INPUT', 'integer', '16000', 'Max input size for EmailCleaner prompt', 0, 'current'),
153 3 => array('AI_EMAILCLEANER_MIN_CONFIDENCE', 'chaine', '0.60', 'Minimum confidence to trust AI cleaned text', 0, 'current'),
154 4 => array('AI_EMAILCLEANER_EXPOSE_OPERATION', 'yesno', '0', 'Expose AI Email Cleaner operation in EmailCollector card', 0, 'current'),
155 5 => array('AI_EMAILCLEANER_ISOLATED_MODE', 'yesno', '1', 'Force isolated cleaner runtime (no business decision / no cross-module side effects)', 0, 'current'),
156 );
157
158 // Some keys to add into the overwriting translation tables
159 /*$this->overwrite_translation = array(
160 'en_US:ParentCompany'=>'Parent company or reseller',
161 'fr_FR:ParentCompany'=>'Maison mère ou revendeur'
162 )*/
163
164 if (!isset($conf->ai) || !isset($conf->ai->enabled)) {
165 $conf->ai = new stdClass();
166 $conf->ai->enabled = 0;
167 }
168
169 // Array to add new pages in new tabs
170 $this->tabs = array();
171 // Example:
172 // $this->tabs[] = array('data'=>'objecttype:+tabname1:Title1:mylangfile@ai:$user->hasRight('ai','read'):/ai/mynewtab1.php?id=__ID__'); // To add a new tab identified by code tabname1
173 // $this->tabs[] = array('data'=>'objecttype:+tabname2:SUBSTITUTION_Title2:mylangfile@ai:$user->hasRight('othermodule','read'):/ai/mynewtab2.php?id=__ID__', // To add another new tab identified by code tabname2. Label will be result of calling all substitution functions on 'Title2' key.
174 // $this->tabs[] = array('data'=>'objecttype:-tabname:NU:conditiontoremove'); // To remove an existing tab identified by code tabname
175 //
176 // Where objecttype can be
177 // 'categories_x' to add a tab in category view (replace 'x' by type of category (0=product, 1=supplier, 2=customer, 3=member)
178 // 'contact' to add a tab in contact view
179 // 'contract' to add a tab in contract view
180 // 'group' to add a tab in group view
181 // 'intervention' to add a tab in intervention view
182 // 'invoice' to add a tab in customer invoice view
183 // 'invoice_supplier' to add a tab in supplier invoice view
184 // 'member' to add a tab in foundation member view
185 // 'opensurveypoll' to add a tab in opensurvey poll view
186 // 'order' to add a tab in customer order view
187 // 'order_supplier' to add a tab in supplier order view
188 // 'payment' to add a tab in payment view
189 // 'payment_supplier' to add a tab in supplier payment view
190 // 'product' to add a tab in product view
191 // 'propal' to add a tab in propal view
192 // 'project' to add a tab in project view
193 // 'stock' to add a tab in stock view
194 // 'thirdparty' to add a tab in third party view
195 // 'user' to add a tab in user view
196
197 // Dictionaries
198 $this->dictionaries = array();
199 /* Example:
200 $this->dictionaries=array(
201 'langs'=>'ai@ai',
202 // List of tables we want to see into dictionary editor
203 'tabname'=>array("table1", "table2", "table3"),
204 // Label of tables
205 'tablib'=>array("Table1", "Table2", "Table3"),
206 // Request to select fields
207 'tabsql'=>array('SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table1 as f', 'SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table2 as f', 'SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table3 as f'),
208 // Sort order
209 'tabsqlsort'=>array("label ASC", "label ASC", "label ASC"),
210 // List of fields (result of select to show dictionary)
211 'tabfield'=>array("code,label", "code,label", "code,label"),
212 // List of fields (list of fields to edit a record)
213 'tabfieldvalue'=>array("code,label", "code,label", "code,label"),
214 // List of fields (list of fields for insert)
215 'tabfieldinsert'=>array("code,label", "code,label", "code,label"),
216 // Name of columns with primary key (try to always name it 'rowid')
217 'tabrowid'=>array("rowid", "rowid", "rowid"),
218 // Condition to show each dictionary
219 'tabcond'=>array($conf->ai->enabled, $conf->ai->enabled, $conf->ai->enabled)
220 // Help tooltip for each fields of the dictionary
221 'tabhelp'=>array(array('code'=>$langs->trans('CodeTooltipHelp')))
222 );
223 */
224
225 // Boxes/Widgets
226 // Add here list of php file(s) stored in ai/core/boxes that contains a class to show a widget.
227 $this->boxes = array(
228 // 0 => array(
229 // 'file' => 'aiwidget1.php@ai',
230 // 'note' => 'Widget provided by Ai',
231 // 'enabledbydefaulton' => 'Home',
232 // ),
233 // ...
234 );
235
236 // Cronjobs (List of cron jobs entries to add when module is enabled)
237 // unit_frequency must be 60 for minute, 3600 for hour, 86400 for day, 604800 for week
238 $this->cronjobs = array(
239 // 0 => array(
240 // 'label' => 'MyJob label',
241 // 'jobtype' => 'method',
242 // 'class' => '/ai/class/availabilities.class.php',
243 // 'objectname' => 'Availabilities',
244 // 'method' => 'doScheduledJob',
245 // 'parameters' => '',
246 // 'comment' => 'Comment',
247 // 'frequency' => 2,
248 // 'unitfrequency' => 3600,
249 // 'status' => 0,
250 // 'test' => 'isModEnabled('ai')',
251 // 'priority' => 50,
252 // ),
253 );
254 // Example: $this->cronjobs=array(
255 // 0=>array('label'=>'My label', 'jobtype'=>'method', 'class'=>'/dir/class/file.class.php', 'objectname'=>'MyClass', 'method'=>'myMethod', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>2, 'unitfrequency'=>3600, 'status'=>0, 'test'=>'$conf->ai->enabled', 'priority'=>50),
256 // 1=>array('label'=>'My label', 'jobtype'=>'command', 'command'=>'', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>1, 'unitfrequency'=>3600*24, 'status'=>0, 'test'=>'$conf->ai->enabled', 'priority'=>50)
257 // );
258
259 // Permissions provided by this module
260 $this->rights = array();
261 $r = 0;
262 // Add here entries to declare new permissions
263 /* BEGIN MODULEBUILDER PERMISSIONS */
264 // Right to use the AI Assistant chat (read-level access to the AI workflow).
265 //
266 // NOT granted by default: per the GDPR / EU AI Act discussion on
267 // issue #38331 (and feedback by @sonikf and @eldy on this PR),
268 // AI Assistant usage must be attributed explicitly by an admin to
269 // the users/groups who are authorized to send organisational data
270 // to the configured LLM provider. The admin is typically the GDPR
271 // DPO officer who is also the de-facto DPA for the AI module, and
272 // owns the per-user authorization decision.
273 //
274 // Setup access intentionally remains a hard $user->admin check
275 // (technical setup, no dedicated right declared) so that the
276 // API-key configuration of the AI module stays in admin scope,
277 // in line with how every other Dolibarr module is configured.
278 $this->rights[$r][0] = $this->numero + 1;
279 $this->rights[$r][1] = 'Use the AI Assistant';
280 $this->rights[$r][3] = 0; // default: NOT granted
281 $this->rights[$r][4] = 'assistant';
282 $this->rights[$r][5] = 'use';
283 $r++;
284 /* END MODULEBUILDER PERMISSIONS */
285
286 // Main menu entries to add
287 $this->menu = array();
288 $r = 0;
289 // Add here entries to declare new menus
290 /* BEGIN MODULEBUILDER TOPMENU */
291 /* END MODULEBUILDER TOPMENU */
292
293 /* BEGIN MODULEBUILDER LEFTMENU AI */
294 // The full-page assistant (ai/assistant/index.php) was reachable only by
295 // typing its URL: the topbar popover opens the quick chat, but nothing in
296 // the menus leads to the page with the welcome screen and its ready-made
297 // prompts. One entry under Tools, hideable with AI_MENU_HIDE_TOOLSMENU
298 // and gated by the same ai->assistant->use right as the page itself.
299 $this->menu[$r++] = array(
300 'fk_menu' => 'fk_mainmenu=tools',
301 'type' => 'left',
302 'titre' => 'AIAssistant',
303 'prefix' => img_picto('', 'fa-robot', 'class="paddingright pictofixedwidth"'),
304 'mainmenu' => 'tools',
305 'leftmenu' => 'ai',
306 'url' => '/ai/assistant/index.php?mainmenu=tools&leftmenu=ai',
307 'langs' => 'other',
308 'position' => 200,
309 'enabled' => 'isModEnabled("ai") && getDolGlobalString("AI_ASSISTANT_ENABLED") && getDolGlobalString("AI_MENU_SHOW_TOOLSMENU")',
310 'perms' => '$user->hasRight("ai", "assistant", "use")',
311 'target' => '',
312 'user' => 2,
313 );
314 /* END MODULEBUILDER LEFTMENU AI */
315
316 /* BEGIN MODULEBUILDER LEFTMENU AVAILABILITIES
317 /* END MODULEBUILDER LEFTMENU AVAILABILITIES */
318
319 // Exports profiles provided by this module
320 $r = 1;
321 /* BEGIN MODULEBUILDER EXPORT AVAILABILITIES */
322 /*
323 $langs->load("agenda");
324 $this->export_code[$r]=$this->rights_class.'_'.$r;
325 $this->export_label[$r]='AvailabilitiesLines'; // Translation key (used only if key ExportDataset_xxx_z not found)
326 $this->export_icon[$r]='availabilities@ai';
327 // Define $this->export_fields_array, $this->export_TypeFields_array and $this->export_entities_array
328 $keyforclass = 'Availabilities'; $keyforclassfile='/ai/class/availabilities.class.php'; $keyforelement='availabilities@ai';
329 include DOL_DOCUMENT_ROOT.'/core/commonfieldsinexport.inc.php';
330 //$this->export_fields_array[$r]['t.fieldtoadd']='FieldToAdd'; $this->export_TypeFields_array[$r]['t.fieldtoadd']='Text';
331 //unset($this->export_fields_array[$r]['t.fieldtoremove']);
332 //$keyforclass = 'AvailabilitiesLine'; $keyforclassfile='/ai/class/availabilities.class.php'; $keyforelement='availabilitiesline@ai'; $keyforalias='tl';
333 //include DOL_DOCUMENT_ROOT.'/core/commonfieldsinexport.inc.php';
334 $keyforselect='availabilities'; $keyforaliasextra='extra'; $keyforelement='availabilities@ai';
335 include DOL_DOCUMENT_ROOT.'/core/extrafieldsinexport.inc.php';
336 //$keyforselect='availabilitiesline'; $keyforaliasextra='extraline'; $keyforelement='availabilitiesline@ai';
337 //include DOL_DOCUMENT_ROOT.'/core/extrafieldsinexport.inc.php';
338 //$this->export_dependencies_array[$r] = array('availabilitiesline'=>array('tl.rowid','tl.ref')); // To force to activate one or several fields if we select some fields that need same (like to select a unique key if we ask a field of a child to avoid the DISTINCT to discard them, or for computed field than need several other fields)
339 //$this->export_special_array[$r] = array('t.field'=>'...');
340 //$this->export_examplevalues_array[$r] = array('t.field'=>'Example');
341 //$this->export_help_array[$r] = array('t.field'=>'FieldDescHelp');
342 $this->export_sql_start[$r]='SELECT DISTINCT ';
343 $this->export_sql_end[$r] =' FROM '.MAIN_DB_PREFIX.'availabilities as t';
344 //$this->export_sql_end[$r] =' LEFT JOIN '.MAIN_DB_PREFIX.'availabilities_line as tl ON tl.fk_availabilities = t.rowid';
345 $this->export_sql_end[$r] .=' WHERE 1 = 1';
346 $this->export_sql_end[$r] .=' AND t.entity IN ('.getEntity('availabilities').')';
347 $r++; */
348 /* END MODULEBUILDER EXPORT AVAILABILITIES */
349
350 // Imports profiles provided by this module
351 $r = 1;
352 /* BEGIN MODULEBUILDER IMPORT AVAILABILITIES */
353 /*
354 $langs->load("agenda");
355 $this->import_code[$r]=$this->rights_class.'_'.$r;
356 $this->import_label[$r]='AvailabilitiesLines'; // Translation key (used only if key ExportDataset_xxx_z not found)
357 $this->import_icon[$r]='availabilities@ai';
358 $this->import_tables_array[$r] = array('t' => MAIN_DB_PREFIX.'ai_availabilities', 'extra' => MAIN_DB_PREFIX.'ai_availabilities_extrafields');
359 $this->import_tables_creator_array[$r] = array('t' => 'fk_user_author'); // Fields to store import user id
360 $import_sample = array();
361 $keyforclass = 'Availabilities'; $keyforclassfile='/ai/class/availabilities.class.php'; $keyforelement='availabilities@ai';
362 include DOL_DOCUMENT_ROOT.'/core/commonfieldsinimport.inc.php';
363 $import_extrafield_sample = array();
364 $keyforselect='availabilities'; $keyforaliasextra='extra'; $keyforelement='availabilities@ai';
365 include DOL_DOCUMENT_ROOT.'/core/extrafieldsinimport.inc.php';
366 $this->import_fieldshidden_array[$r] = array('extra.fk_object' => 'lastrowid-'.MAIN_DB_PREFIX.'ai_availabilities');
367 $this->import_regex_array[$r] = array();
368 $this->import_examplevalues_array[$r] = array_merge($import_sample, $import_extrafield_sample);
369 $this->import_updatekeys_array[$r] = array('t.ref' => 'Ref');
370 $this->import_convertvalue_array[$r] = array(
371 't.ref' => array(
372 'rule'=>'getrefifauto',
373 'class'=>(empty($conf->global->BOOKCAL_AVAILABILITIES_ADDON) ? 'mod_availabilities_standard' : $conf->global->BOOKCAL_AVAILABILITIES_ADDON),
374 'path'=>"/core/modules/commande/".(empty($conf->global->BOOKCAL_AVAILABILITIES_ADDON) ? 'mod_availabilities_standard' : $conf->global->BOOKCAL_AVAILABILITIES_ADDON).'.php'
375 'classobject'=>'Availabilities',
376 'pathobject'=>'/ai/class/availabilities.class.php',
377 ),
378 't.fk_soc' => array('rule' => 'fetchidfromref', 'file' => '/societe/class/societe.class.php', 'class' => 'Societe', 'method' => 'fetch', 'element' => 'ThirdParty'),
379 't.fk_user_valid' => array('rule' => 'fetchidfromref', 'file' => '/user/class/user.class.php', 'class' => 'User', 'method' => 'fetch', 'element' => 'user'),
380 't.fk_mode_reglement' => array('rule' => 'fetchidfromcodeorlabel', 'file' => '/compta/paiement/class/cpaiement.class.php', 'class' => 'Cpaiement', 'method' => 'fetch', 'element' => 'cpayment'),
381 );
382 $r++; */
383 /* END MODULEBUILDER IMPORT AVAILABILITIES */
384 }
385
394 public function init($options = '')
395 {
396 //global $conf, $langs;
397
398 $result = $this->_load_tables('/install/mysql/', 'ai');
399 if ($result < 0) {
400 return -1; // Do not activate module if error 'not allowed' returned when loading module SQL queries (the _load_table run sql with run_sql with the error allowed parameter set to 'default')
401 }
402
403 // Permissions
404 $this->remove($options);
405
406 $sql = array();
407
408 return $this->_init($sql, $options);
409 }
410
419 public function remove($options = '')
420 {
421 $sql = array();
422 return $this->_remove($sql, $options);
423 }
424}
Class DolibarrModules.
_init($array_sql, $options='')
Enables a module.
_remove($array_sql, $options='')
Disable function.
_load_tables($reldir, $onlywithsuffix='')
Create tables and keys required by module:
Description and activation class for module Ai.
__construct($db)
Constructor.
init($options='')
Function called when module is enabled.
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
$conf browser version
Definition main.inc.php:229
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:140