dolibarr 24.0.0-beta
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['trClass'] = 'iaservice '.$ia;
98 $item->cssClass = 'minwidth500 text-security input'.$ia;
99 $item->helpText = '<span class="helptoshow">HelpToShow</span>';
100
101 // API URL
102 $item = $formSetup->newItem('AI_API_'.strtoupper($ia).'_URL'); // Name of constant must end with _KEY so it is encrypted when saved into database.
103 $item->nameText = $langs->trans("AI_API_URL").' ('.$ialabel.')';
104 $item->defaultFieldValue = $iarecord['url'];
105 $item->fieldParams['trClass'] = 'iaservice iaurl '.$ia;
106 $item->cssClass = 'minwidth500 input'.$ia;
107 if ($ia == 'custom') {
108 $item->fieldAttr['placeholder'] = 'https://domainofapi.com/v1/';
109 }
110}
111
112$setupnotempty = + count($formSetup->items);
113
114
115$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
116
117// Access control
118// Setup intentionally stays admin-only: per @sonikf and @eldy feedback,
119// the AI module's technical setup (API keys, provider configuration) is
120// a task done by the admin user, just like for every other Dolibarr module.
121// Per-user/group AI usage is gated separately by 'ai/assistant/use'.
122if (!$user->admin) {
124}
125if (!isModEnabled('ai')) {
126 accessforbidden('Module AI not activated.');
127}
128
129
130/*
131 * Actions
132 */
133
134include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php';
135
136$action = 'edit';
137
138
139/*
140 * View
141 */
142
143$help_url = '';
144$title = "AiSetup";
145
146llxHeader('', $langs->trans($title), $help_url, '', 0, 0, '', '', '', 'mod-ai page-admin');
147
148// Subheader
149$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>';
150
151print load_fiche_titre($langs->trans($title), $linkback, 'title_setup');
152
153// Configuration header
154$head = aiAdminPrepareHead();
155print dol_get_fiche_head($head, 'settings', $langs->trans($title), -1, "ai");
156
157
158if ($action == 'edit') {
159 print $formSetup->generateOutput(true);
160} elseif (!empty($formSetup->items)) {
161 print $formSetup->generateOutput();
162 print '<div class="tabsAction">';
163 print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&token='.newToken().'">'.$langs->trans("Modify").'</a>';
164 print '</div>';
165} else {
166 print '<br>'.$langs->trans("NothingToSetup");
167}
168
169
170if (empty($setupnotempty)) {
171 print '<br>'.$langs->trans("NothingToSetup");
172}
173
174print '<script type="text/javascript">
175 jQuery(document).ready(function() {
176 function showHideAIService(aiservice) {
177 console.log("showHideAIService: We select the AI service "+aiservice);
178 jQuery(".iaservice").hide();
179
180 if (aiservice != "-1") {
181 jQuery(".iaservice."+aiservice).show();
182 const arrayofia = {';
183$i = 0;
184foreach ($arrayofai as $key => $airecord) {
185 if ($key == -1) {
186 continue;
187 }
188 if ($i) {
189 print ', ';
190 }
191 $i++;
192 print dol_escape_js($key).': \''.dol_escape_js($airecord['url']).'\'';
193}
194print '};
195 const arrayofextlink = {';
196$i = 0;
197foreach ($arrayofai as $key => $airecord) {
198 if ($key == -1) {
199 continue;
200 }
201 if ($i) {
202 print ', ';
203 }
204 $i++;
205 print dol_escape_js($key).': \''.dol_escape_js($airecord['setup']).'\'';
206}
207print '};
208 console.log("Check URL for .iaurl."+aiservice+" .input"+aiservice);
209 if (jQuery(".iaurl."+aiservice+" .input"+aiservice).val() == \'\') {
210 console.log("URL is empty, we fill with default value of IA selected");
211 jQuery(".iaurl."+aiservice+" .input"+aiservice).val(arrayofia[aiservice]);
212 }
213 jQuery(".helptoshow").text(arrayofextlink[aiservice]);
214 }
215 }
216
217 jQuery("#AI_API_SERVICE").change(function() {
218 var aiservice = $(this).val();
219
220 showHideAIService(aiservice);
221
222 jQuery(".sectiontest").hide(); /* Hide test section, will appear after the save */
223 });
224
225 showHideAIService("'.getDolGlobalString("AI_API_SERVICE").'");
226 });
227</script>';
228
229// Page end
230print dol_get_fiche_end();
231
232
233// The section for test
234
235if (getDolGlobalString("AI_API_SERVICE")) {
236 print '<br><div class="sectiontest">';
237
238 // Section to test
239 print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
240 print '<input type="hidden" name="token" value="'.newToken().'">';
241 print '<input type="hidden" name="action" value="add">';
242 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
243
244
245 $key = 'textgenerationother'; // The HTML ID of field to fill
246
247 //if (GETPOST('functioncode') == 'textgenerationemail') {
248
249 print '<br>';
250 //print '<hr>';
251
252 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
253 include_once DOL_DOCUMENT_ROOT."/core/class/html.formai.class.php";
254 $formai = new FormAI($db);
255 $formmail = new FormMail($db);
256
257 $showlinktoai = $key; // 'textgeneration', 'imagegeneration', ...
258 $showlinktoailabel = $langs->trans("AITestText");
259 $showlinktolayout = 0;
260 $htmlname = $key;
261 $formmail->withaiprompt = '';
262
263 // Fill $out
264
265 $out = $langs->trans("Test").': &nbsp; ';
266 include DOL_DOCUMENT_ROOT.'/core/tpl/formlayoutai.tpl.php';
267 print $out;
268
269 print ' &nbsp; ';
270 if (getDolGlobalString("AI_DEBUG")) {
271 print ' <span class="small opacitymedium">'.$langs->trans("DebugOnInFile", 'dolibarr_ai.log').'</span>';
272 } else {
273 print ' <span class="small opacitymedium">'.$langs->trans("DebugOff", 'dolibarr_ai.log').'</span>';
274 }
275
276 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
277
278 print '<br><br>';
279
280
281 $showlinktoai .= 'html';
282 $htmlname .= 'html';
283 $formmail->withaiprompt = 'html';
284
285 // Fill $out
286 $out = $langs->trans("Test").': &nbsp; ';
287 include DOL_DOCUMENT_ROOT.'/core/tpl/formlayoutai.tpl.php';
288 print $out;
289
290 print ' &nbsp; ';
291 if (getDolGlobalString("AI_DEBUG")) {
292 print ' <span class="small opacitymedium">'.$langs->trans("DebugOnInFile", 'dolibarr_ai.log').'</span>';
293 } else {
294 print ' <span class="small opacitymedium">'.$langs->trans("DebugOff", 'dolibarr_ai.log').'</span>';
295 }
296
297 print '<br>';
298 $doleditor = new DolEditor($htmlname, '', '', 150, 'dolibarr_details');
299 print $doleditor->Create(1);
300
301 print '</form>';
302
303 print '</div>';
304}
305
306llxFooter();
307$db->close();
getListOfAIFeatures()
Prepare admin pages header.
Definition ai.lib.php:36
aiAdminPrepareHead()
Prepare admin pages header.
Definition ai.lib.php:407
getListOfAIServices()
Get list of available ai services.
Definition ai.lib.php:68
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
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.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
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.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into JavaScript code.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.