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 // Set this to relative path of js file if module must load a js on all pages
108 'js' => array(),
109 // 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'
110 'hooks' => array('all'),
111 // Set this to 1 if features of module are opened to external users
112 'moduleforexternal' => 0,
113 );
114
115 // Data directories to create when module is enabled.
116 // Example: this->dirs = array("/ai/temp","/ai/subdir");
117 $this->dirs = array("/ai/temp");
118
119 // Config pages. Put here list of php page, stored into ai/admin directory, to use to setup module.
120 $this->config_page_url = array("setup.php@ai");
121
122 // Dependencies
123 // A condition to hide module
124 $this->hidden = false;
125 // 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'...))
126 $this->depends = array();
127 $this->requiredby = array(); // List of module class names as string to disable if this one is disabled. Example: array('modModuleToDisable1', ...)
128 $this->conflictwith = array(); // List of module class names as string this module is in conflict with. Example: array('modModuleToDisable1', ...)
129
130 // The language file dedicated to your module
131 $this->langfiles = array("ai");
132
133 // Prerequisites
134 $this->phpmin = array(7, 0); // Minimum version of PHP required by module
135
136 // Messages at activation
137 $this->warnings_activation = array();
138 $this->warnings_activation_ext = array();
139 //$this->automatic_activation = array('FR'=>'AiWasAutomaticallyActivatedBecauseOfYourCountryChoice');
140
141 // Constants
142 // List of particular constants to add when module is enabled (key, 'chaine', value, desc, visible, 'current' or 'allentities', deleteonunactive)
143 // Example: $this->const=array(1 => array('BOOKCAL_MYNEWCONST1', 'chaine', 'myvalue', 'This is a constant to add', 1),
144 // 2 => array('BOOKCAL_MYNEWCONST2', 'chaine', 'myvalue', 'This is another constant to add', 0, 'current', 1)
145 // );
146 $this->const = array(
147 1 => array('AI_EMAILCLEANER_ENABLED', 'yesno', '0', 'Enable AI cleaner hook for EmailCollector (no business decision)', 0, 'current'),
148 2 => array('AI_EMAILCLEANER_MAX_INPUT', 'integer', '16000', 'Max input size for EmailCleaner prompt', 0, 'current'),
149 3 => array('AI_EMAILCLEANER_MIN_CONFIDENCE', 'chaine', '0.60', 'Minimum confidence to trust AI cleaned text', 0, 'current'),
150 4 => array('AI_EMAILCLEANER_EXPOSE_OPERATION', 'yesno', '0', 'Expose AI Email Cleaner operation in EmailCollector card', 0, 'current'),
151 5 => array('AI_EMAILCLEANER_ISOLATED_MODE', 'yesno', '1', 'Force isolated cleaner runtime (no business decision / no cross-module side effects)', 0, 'current'),
152 6 => array('AI_CHAT_CONTEXT_AUTO_EXCHANGES', 'integer', '2', 'Number of recent exchanges of the AI chat sent back as context by default', 0, 'current'),
153 );
154
155 // Some keys to add into the overwriting translation tables
156 /*$this->overwrite_translation = array(
157 'en_US:ParentCompany'=>'Parent company or reseller',
158 'fr_FR:ParentCompany'=>'Maison mère ou revendeur'
159 )*/
160
161 if (!isset($conf->ai) || !isset($conf->ai->enabled)) {
162 $conf->ai = new stdClass();
163 $conf->ai->enabled = 0;
164 }
165
166 // Array to add new pages in new tabs
167 $this->tabs = array();
168 // Example:
169 // $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
170 // $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.
171 // $this->tabs[] = array('data'=>'objecttype:-tabname:NU:conditiontoremove'); // To remove an existing tab identified by code tabname
172 //
173 // Where objecttype can be
174 // 'categories_x' to add a tab in category view (replace 'x' by type of category (0=product, 1=supplier, 2=customer, 3=member)
175 // 'contact' to add a tab in contact view
176 // 'contract' to add a tab in contract view
177 // 'group' to add a tab in group view
178 // 'intervention' to add a tab in intervention view
179 // 'invoice' to add a tab in customer invoice view
180 // 'invoice_supplier' to add a tab in supplier invoice view
181 // 'member' to add a tab in foundation member view
182 // 'opensurveypoll' to add a tab in opensurvey poll view
183 // 'order' to add a tab in customer order view
184 // 'order_supplier' to add a tab in supplier order view
185 // 'payment' to add a tab in payment view
186 // 'payment_supplier' to add a tab in supplier payment view
187 // 'product' to add a tab in product view
188 // 'propal' to add a tab in propal view
189 // 'project' to add a tab in project view
190 // 'stock' to add a tab in stock view
191 // 'thirdparty' to add a tab in third party view
192 // 'user' to add a tab in user view
193
194 // Dictionaries
195 $this->dictionaries = array();
196 /* Example:
197 $this->dictionaries=array(
198 'langs'=>'ai@ai',
199 // List of tables we want to see into dictionary editor
200 'tabname'=>array("table1", "table2", "table3"),
201 // Label of tables
202 'tablib'=>array("Table1", "Table2", "Table3"),
203 // Request to select fields
204 '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'),
205 // Sort order
206 'tabsqlsort'=>array("label ASC", "label ASC", "label ASC"),
207 // List of fields (result of select to show dictionary)
208 'tabfield'=>array("code,label", "code,label", "code,label"),
209 // List of fields (list of fields to edit a record)
210 'tabfieldvalue'=>array("code,label", "code,label", "code,label"),
211 // List of fields (list of fields for insert)
212 'tabfieldinsert'=>array("code,label", "code,label", "code,label"),
213 // Name of columns with primary key (try to always name it 'rowid')
214 'tabrowid'=>array("rowid", "rowid", "rowid"),
215 // Condition to show each dictionary
216 'tabcond'=>array($conf->ai->enabled, $conf->ai->enabled, $conf->ai->enabled)
217 // Help tooltip for each fields of the dictionary
218 'tabhelp'=>array(array('code'=>$langs->trans('CodeTooltipHelp')))
219 );
220 */
221
222 // Boxes/Widgets
223 // Add here list of php file(s) stored in ai/core/boxes that contains a class to show a widget.
224 $this->boxes = array(
225 // 0 => array(
226 // 'file' => 'aiwidget1.php@ai',
227 // 'note' => 'Widget provided by Ai',
228 // 'enabledbydefaulton' => 'Home',
229 // ),
230 // ...
231 );
232
233 // Cronjobs (List of cron jobs entries to add when module is enabled)
234 // unit_frequency must be 60 for minute, 3600 for hour, 86400 for day, 604800 for week
235 $this->cronjobs = array(
236 // 0 => array(
237 // 'label' => 'MyJob label',
238 // 'jobtype' => 'method',
239 // 'class' => '/ai/class/availabilities.class.php',
240 // 'objectname' => 'Availabilities',
241 // 'method' => 'doScheduledJob',
242 // 'parameters' => '',
243 // 'comment' => 'Comment',
244 // 'frequency' => 2,
245 // 'unitfrequency' => 3600,
246 // 'status' => 0,
247 // 'test' => 'isModEnabled('ai')',
248 // 'priority' => 50,
249 // ),
250 );
251 // Example: $this->cronjobs=array(
252 // 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),
253 // 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)
254 // );
255
256 // Permissions provided by this module
257 $this->rights = array();
258 $r = 0;
259 // Add here entries to declare new permissions
260 /* BEGIN MODULEBUILDER PERMISSIONS */
261 // Right to use the AI Assistant chat (read-level access to the AI workflow).
262 //
263 // NOT granted by default: per the GDPR / EU AI Act discussion on
264 // issue #38331 (and feedback by @sonikf and @eldy on this PR),
265 // AI Assistant usage must be attributed explicitly by an admin to
266 // the users/groups who are authorized to send organisational data
267 // to the configured LLM provider. The admin is typically the GDPR
268 // DPO officer who is also the de-facto DPA for the AI module, and
269 // owns the per-user authorization decision.
270 //
271 // Setup access intentionally remains a hard $user->admin check
272 // (technical setup, no dedicated right declared) so that the
273 // API-key configuration of the AI module stays in admin scope,
274 // in line with how every other Dolibarr module is configured.
275 $this->rights[$r][0] = $this->numero + 1;
276 $this->rights[$r][1] = 'Use the AI Assistant';
277 $this->rights[$r][3] = 0; // default: NOT granted
278 $this->rights[$r][4] = 'assistant';
279 $this->rights[$r][5] = 'use';
280 $r++;
281 /* END MODULEBUILDER PERMISSIONS */
282
283 // Main menu entries to add
284 $this->menu = array();
285 $r = 0;
286 // Add here entries to declare new menus
287 /* BEGIN MODULEBUILDER TOPMENU */
288 /* END MODULEBUILDER TOPMENU */
289
290 /* BEGIN MODULEBUILDER LEFTMENU AI */
291 // The full-page assistant (ai/assistant/index.php) was reachable only by
292 // typing its URL: the topbar popover opens the quick chat, but nothing in
293 // the menus leads to the page with the welcome screen and its ready-made
294 // prompts. One entry under Tools, hideable with AI_MENU_HIDE_TOOLSMENU
295 // and gated by the same ai->assistant->use right as the page itself.
296 $this->menu[$r++] = array(
297 'fk_menu' => 'fk_mainmenu=tools',
298 'type' => 'left',
299 'titre' => 'AIAssistant',
300 'prefix' => img_picto('', 'fa-robot', 'class="paddingright pictofixedwidth"'),
301 'mainmenu' => 'tools',
302 'leftmenu' => 'ai',
303 'url' => '/ai/assistant/index.php?mainmenu=tools&leftmenu=ai',
304 'langs' => 'other',
305 'position' => 200,
306 'enabled' => 'isModEnabled("ai") && getDolGlobalString("AI_ASSISTANT_ENABLED") && getDolGlobalString("AI_MENU_SHOW_TOOLSMENU")',
307 'perms' => '$user->hasRight("ai", "assistant", "use")',
308 'target' => '',
309 'user' => 2,
310 );
311 /* END MODULEBUILDER LEFTMENU AI */
312
313 /* BEGIN MODULEBUILDER LEFTMENU AVAILABILITIES
314 /* END MODULEBUILDER LEFTMENU AVAILABILITIES */
315
316 // Exports profiles provided by this module
317 $r = 1;
318 /* BEGIN MODULEBUILDER EXPORT AVAILABILITIES */
319 /*
320 $langs->load("agenda");
321 $this->export_code[$r]=$this->rights_class.'_'.$r;
322 $this->export_label[$r]='AvailabilitiesLines'; // Translation key (used only if key ExportDataset_xxx_z not found)
323 $this->export_icon[$r]='availabilities@ai';
324 // Define $this->export_fields_array, $this->export_TypeFields_array and $this->export_entities_array
325 $keyforclass = 'Availabilities'; $keyforclassfile='/ai/class/availabilities.class.php'; $keyforelement='availabilities@ai';
326 include DOL_DOCUMENT_ROOT.'/core/commonfieldsinexport.inc.php';
327 //$this->export_fields_array[$r]['t.fieldtoadd']='FieldToAdd'; $this->export_TypeFields_array[$r]['t.fieldtoadd']='Text';
328 //unset($this->export_fields_array[$r]['t.fieldtoremove']);
329 //$keyforclass = 'AvailabilitiesLine'; $keyforclassfile='/ai/class/availabilities.class.php'; $keyforelement='availabilitiesline@ai'; $keyforalias='tl';
330 //include DOL_DOCUMENT_ROOT.'/core/commonfieldsinexport.inc.php';
331 $keyforselect='availabilities'; $keyforaliasextra='extra'; $keyforelement='availabilities@ai';
332 include DOL_DOCUMENT_ROOT.'/core/extrafieldsinexport.inc.php';
333 //$keyforselect='availabilitiesline'; $keyforaliasextra='extraline'; $keyforelement='availabilitiesline@ai';
334 //include DOL_DOCUMENT_ROOT.'/core/extrafieldsinexport.inc.php';
335 //$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)
336 //$this->export_special_array[$r] = array('t.field'=>'...');
337 //$this->export_examplevalues_array[$r] = array('t.field'=>'Example');
338 //$this->export_help_array[$r] = array('t.field'=>'FieldDescHelp');
339 $this->export_sql_start[$r]='SELECT DISTINCT ';
340 $this->export_sql_end[$r] =' FROM '.MAIN_DB_PREFIX.'availabilities as t';
341 //$this->export_sql_end[$r] =' LEFT JOIN '.MAIN_DB_PREFIX.'availabilities_line as tl ON tl.fk_availabilities = t.rowid';
342 $this->export_sql_end[$r] .=' WHERE 1 = 1';
343 $this->export_sql_end[$r] .=' AND t.entity IN ('.getEntity('availabilities').')';
344 $r++; */
345 /* END MODULEBUILDER EXPORT AVAILABILITIES */
346
347 // Imports profiles provided by this module
348 $r = 1;
349 /* BEGIN MODULEBUILDER IMPORT AVAILABILITIES */
350 /*
351 $langs->load("agenda");
352 $this->import_code[$r]=$this->rights_class.'_'.$r;
353 $this->import_label[$r]='AvailabilitiesLines'; // Translation key (used only if key ExportDataset_xxx_z not found)
354 $this->import_icon[$r]='availabilities@ai';
355 $this->import_tables_array[$r] = array('t' => MAIN_DB_PREFIX.'ai_availabilities', 'extra' => MAIN_DB_PREFIX.'ai_availabilities_extrafields');
356 $this->import_tables_creator_array[$r] = array('t' => 'fk_user_author'); // Fields to store import user id
357 $import_sample = array();
358 $keyforclass = 'Availabilities'; $keyforclassfile='/ai/class/availabilities.class.php'; $keyforelement='availabilities@ai';
359 include DOL_DOCUMENT_ROOT.'/core/commonfieldsinimport.inc.php';
360 $import_extrafield_sample = array();
361 $keyforselect='availabilities'; $keyforaliasextra='extra'; $keyforelement='availabilities@ai';
362 include DOL_DOCUMENT_ROOT.'/core/extrafieldsinimport.inc.php';
363 $this->import_fieldshidden_array[$r] = array('extra.fk_object' => 'lastrowid-'.MAIN_DB_PREFIX.'ai_availabilities');
364 $this->import_regex_array[$r] = array();
365 $this->import_examplevalues_array[$r] = array_merge($import_sample, $import_extrafield_sample);
366 $this->import_updatekeys_array[$r] = array('t.ref' => 'Ref');
367 $this->import_convertvalue_array[$r] = array(
368 't.ref' => array(
369 'rule'=>'getrefifauto',
370 'class'=>(empty($conf->global->BOOKCAL_AVAILABILITIES_ADDON) ? 'mod_availabilities_standard' : $conf->global->BOOKCAL_AVAILABILITIES_ADDON),
371 'path'=>"/core/modules/commande/".(empty($conf->global->BOOKCAL_AVAILABILITIES_ADDON) ? 'mod_availabilities_standard' : $conf->global->BOOKCAL_AVAILABILITIES_ADDON).'.php'
372 'classobject'=>'Availabilities',
373 'pathobject'=>'/ai/class/availabilities.class.php',
374 ),
375 't.fk_soc' => array('rule' => 'fetchidfromref', 'file' => '/societe/class/societe.class.php', 'class' => 'Societe', 'method' => 'fetch', 'element' => 'ThirdParty'),
376 't.fk_user_valid' => array('rule' => 'fetchidfromref', 'file' => '/user/class/user.class.php', 'class' => 'User', 'method' => 'fetch', 'element' => 'user'),
377 't.fk_mode_reglement' => array('rule' => 'fetchidfromcodeorlabel', 'file' => '/compta/paiement/class/cpaiement.class.php', 'class' => 'Cpaiement', 'method' => 'fetch', 'element' => 'cpayment'),
378 );
379 $r++; */
380 /* END MODULEBUILDER IMPORT AVAILABILITIES */
381 }
382
391 public function init($options = '')
392 {
393 //global $conf, $langs;
394
395 $result = $this->_load_tables('/install/mysql/', 'ai');
396 if ($result < 0) {
397 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')
398 }
399
400 // Permissions
401 $this->remove($options);
402
403 $sql = array();
404
405 return $this->_init($sql, $options);
406 }
407
416 public function remove($options = '')
417 {
418 $sql = array();
419 return $this->_remove($sql, $options);
420 }
421}
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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.
$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:165