dolibarr 25.0.0-alpha
setup.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2004-2017 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2022 Lamrani Abdel
4 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
6 * Coryright (C) 2024 Alexandre Spangaro <alexandre@inovea-conseil.com>
7 * Copyright (C) 2026 Nick Fragoulis
8 * Copyright (C) 2026 Jose Martinez <jose.martinez@pichinov.com>
9 *
10 * This program is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation, either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY, without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 */
23
30// Load Dolibarr environment
31require '../../main.inc.php';
39require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php";
40require_once DOL_DOCUMENT_ROOT."/core/class/doleditor.class.php";
41require_once DOL_DOCUMENT_ROOT."/ai/lib/ai.lib.php";
42
43$langs->loadLangs(array("admin", "website", "other"));
44
45
46// Parameters
47$action = GETPOST('action', 'aZ09');
48$backtopage = GETPOST('backtopage', 'alpha');
49$modulepart = GETPOST('modulepart', 'aZ09'); // Used by actions_setmoduleoptions.inc.php
50
51if (empty($action)) {
52 $action = 'edit';
53}
54
55$content = GETPOST('content');
56
57$error = 0;
58$setupnotempty = 0;
59
60
61// Set this to 1 to use the factory to manage constants. Warning, the generated module will be compatible with version v15+ only
62$useFormSetup = 1;
63
64if (!class_exists('FormSetup')) {
65 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formsetup.class.php';
66}
67
68$formSetup = new FormSetup($db);
69
70// List all available AI
71$arrayofai = getListOfAIServices();
72
73// List all available features
74$arrayofaifeatures = getListOfAIFeatures();
75
76// Main Service Selection
77$item = $formSetup->newItem('AI_API_SERVICE'); // Name of constant must end with _KEY so it is encrypted when saved into database.
78$item->setAsSelect($arrayofai);
79$item->cssClass = 'minwidth150';
80
81// Loop for Provider Configs
82foreach ($arrayofai as $ia => $iarecord) {
83 if ($ia == '-1') {
84 continue;
85 }
86 $ialabel = $iarecord['label'];
87 // Setup conf AI_PUBLIC_INTERFACE_TOPIC
88 /*$item = $formSetup->newItem('AI_API_'.strtoupper($ia).'_ENDPOINT'); // Name of constant must end with _KEY so it is encrypted when saved into database.
89 $item->defaultFieldValue = '';
90 $item->cssClass = 'minwidth500';*/
91
92 // API Key
93 $item = $formSetup->newItem('AI_API_'.strtoupper($ia).'_KEY')->setAsSecureKey(); // Name of constant must end with _KEY so it is encrypted when saved into database.
94 $item->nameText = $langs->trans("AI_API_KEY").' ('.$ialabel.')';
95 $item->defaultFieldValue = '';
96 $item->fieldParams['hideGenerateButton'] = 1;
97 $item->fieldParams['showEyeButton'] = 1;
98 $item->fieldParams['trClass'] = 'iaservice '.$ia;
99 $item->cssClass = 'minwidth500 text-security input'.$ia;
100 $item->helpText = '<span class="helptoshow">HelpToShow</span>';
101
102 // API URL
103 $item = $formSetup->newItem('AI_API_'.strtoupper($ia).'_URL'); // Name of constant must end with _KEY so it is encrypted when saved into database.
104 $item->nameText = $langs->trans("AI_API_URL").' ('.$ialabel.')';
105 $item->defaultFieldValue = $iarecord['url'];
106 $item->fieldParams['trClass'] = 'iaservice iaurl '.$ia;
107 $item->cssClass = 'minwidth500 input'.$ia;
108 if ($ia == 'custom') {
109 $item->fieldAttr['placeholder'] = 'https://domainofapi.com/v1/';
110 }
111}
112
113$setupnotempty = + count($formSetup->items);
114
115
116$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
117
118// Access control
119// Setup intentionally stays admin-only: per @sonikf and @eldy feedback,
120// the AI module's technical setup (API keys, provider configuration) is
121// a task done by the admin user, just like for every other Dolibarr module.
122// Per-user/group AI usage is gated separately by 'ai/assistant/use'.
123if (!$user->admin) {
125}
126if (!isModEnabled('ai')) {
127 accessforbidden('Module AI not activated.');
128}
129
130
131/*
132 * Actions
133 */
134
135include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php';
136
137$action = 'edit';
138
139
140/*
141 * View
142 */
143
144$help_url = '';
145$title = "AiSetup";
146
147llxHeader('', $langs->trans($title), $help_url, '', 0, 0, '', '', '', 'mod-ai page-admin');
148
149// Subheader
150$linkback = '<a href="'.($backtopage ? $backtopage : dolBuildUrl(DOL_URL_ROOT.'/admin/modules.php', ['restore_lastsearch_values' => 1])).'">'.img_picto($langs->trans("BackToModuleList"), 'back', 'class="pictofixedwidth"').'<span class="hideonsmartphone">'.$langs->trans("BackToModuleList").'</span></a>';
151
152print load_fiche_titre($langs->trans($title), $linkback, 'title_setup');
153
154// Configuration header
155$head = aiAdminPrepareHead();
156print dol_get_fiche_head($head, 'settings', $langs->trans($title), -1, "ai");
157
158print '<br>';
159
160if ($action == 'edit') {
161 print $formSetup->generateOutput(true);
162} elseif (!empty($formSetup->items)) {
163 print $formSetup->generateOutput();
164 print '<div class="tabsAction">';
165 print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&token='.newToken().'">'.$langs->trans("Modify").'</a>';
166 print '</div>';
167} else {
168 print $langs->trans("NothingToSetup");
169}
170
171
172if (empty($setupnotempty)) {
173 print '<br>'.$langs->trans("NothingToSetup");
174}
175
176print '<script type="text/javascript">
177 jQuery(document).ready(function() {
178 function showHideAIService(aiservice) {
179 console.log("showHideAIService: We select the AI service "+aiservice);
180 jQuery(".iaservice").hide();
181
182 if (aiservice != "-1") {
183 jQuery(".iaservice."+aiservice).show();
184 const arrayofia = {';
185$i = 0;
186foreach ($arrayofai as $key => $airecord) {
187 if ($key == -1) {
188 continue;
189 }
190 if ($i) {
191 print ', ';
192 }
193 $i++;
194 print dol_sanitizeKeyCode($key).': \''.dol_escape_js($airecord['url']).'\'';
195}
196print '};
197 const arrayofextlink = {';
198$i = 0;
199foreach ($arrayofai as $key => $airecord) {
200 if ($key == -1) {
201 continue;
202 }
203 if ($i) {
204 print ', ';
205 }
206 $i++;
207 print dol_sanitizeKeyCode($key).': \''.dol_escape_js($airecord['setup']).'\'';
208}
209print '};
210 console.log("Check URL for .iaurl."+aiservice+" .input"+aiservice);
211 if (jQuery(".iaurl."+aiservice+" .input"+aiservice).val() == \'\') {
212 console.log("URL is empty, we fill with default value of IA selected");
213 jQuery(".iaurl."+aiservice+" .input"+aiservice).val(arrayofia[aiservice]);
214 }
215 jQuery(".helptoshow").text(arrayofextlink[aiservice]);
216 }
217 }
218
219 jQuery("#AI_API_SERVICE").change(function() {
220 var aiservice = $(this).val();
221
222 showHideAIService(aiservice);
223
224 jQuery(".sectiontest").hide(); /* Hide test section, will appear after the save */
225 });
226
227 showHideAIService("'.getDolGlobalString("AI_API_SERVICE").'");
228 });
229</script>';
230
231// Page end
232print dol_get_fiche_end();
233
234
235// The section for test
236
237if (getDolGlobalString("AI_API_SERVICE")) {
238 print '<br><div class="sectiontest">';
239
240 // Section to test
241 print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
242 print '<input type="hidden" name="token" value="'.newToken().'">';
243 print '<input type="hidden" name="action" value="add">';
244 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
245
246
247 $key = 'textgenerationother'; // The HTML ID of field to fill
248
249 //if (GETPOST('functioncode') == 'textgenerationemail') {
250
251 print '<br>';
252 //print '<hr>';
253
254 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
255 include_once DOL_DOCUMENT_ROOT."/core/class/html.formai.class.php";
256 $formai = new FormAI($db);
257 $formmail = new FormMail($db);
258
259 $showlinktoai = $key; // 'textgeneration', 'imagegeneration', ...
260 $showlinktoailabel = $langs->trans("AITestText");
261 $showlinktolayout = 0;
262 $htmlname = $key;
263 $formmail->withaiprompt = '';
264
265 // Fill $out
266
267 $out = $langs->trans("Test").': &nbsp; ';
268 include DOL_DOCUMENT_ROOT.'/core/tpl/formlayoutai.tpl.php';
269 print $out;
270
271 print ' &nbsp; ';
272 if (getDolGlobalString("AI_DEBUG")) {
273 print ' <span class="small opacitymedium">'.$langs->trans("DebugOnInFile", 'dolibarr_ai.log').'</span>';
274 } else {
275 print ' <span class="small opacitymedium">'.$langs->trans("DebugOff", 'dolibarr_ai.log').'</span>';
276 }
277
278 print '<br><textarea id="'.$htmlname.'" placeholder="Click on picto to enter a prompt or enter a message and click picto to make text transformation..." class="quatrevingtpercent" rows="4"></textarea>'; // The div
279
280 print '<br><br>';
281
282
283 $showlinktoai .= 'html';
284 $htmlname .= 'html';
285 $formmail->withaiprompt = 'html';
286
287 // Fill $out
288 $out = $langs->trans("Test").': &nbsp; ';
289 include DOL_DOCUMENT_ROOT.'/core/tpl/formlayoutai.tpl.php';
290 print $out;
291
292 print ' &nbsp; ';
293 if (getDolGlobalString("AI_DEBUG")) {
294 print ' <span class="small opacitymedium">'.$langs->trans("DebugOnInFile", 'dolibarr_ai.log').'</span>';
295 } else {
296 print ' <span class="small opacitymedium">'.$langs->trans("DebugOff", 'dolibarr_ai.log').'</span>';
297 }
298
299 print '<br>';
300 $doleditor = new DolEditor($htmlname, '', '', 150, 'dolibarr_details');
301 print $doleditor->Create(1);
302
303 print '</form>';
304
305 print '</div>';
306}
307
308llxFooter();
309$db->close();
getListOfAIFeatures()
Prepare admin pages header.
Definition ai.lib.php:37
aiAdminPrepareHead()
Prepare admin pages header.
Definition ai.lib.php:548
getListOfAIServices()
Get list of available ai services.
Definition ai.lib.php:69
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage a WYSIWYG editor.
Class to generate HTML forms for single email Usage: $formai = new FormAI($db) $formai->proprietes=1 ...
Class to manage a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
This class help you create setup render.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into JavaScript code.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_sanitizeKeyCode($str)
Clean a string to use it as a key or code.
isModEnabled($module)
Is Dolibarr module enabled.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
Definition html.lib.php:542
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition html.lib.php:740
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.