dolibarr 21.0.0-beta
custom_prompt.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 Alice Adminson <aadminson@example.com>
4 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
5 * Coryright (C) 2024 Alexandre Spangaro <alexandre@inovea-conseil.com>
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
27// Load Dolibarr environment
28require '../../main.inc.php';
29require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php";
30require_once '../lib/ai.lib.php';
31
40$langs->loadLangs(array("admin", "website", "other"));
41
42// Parameters
43$action = GETPOST('action', 'aZ09');
44$backtopage = GETPOST('backtopage', 'alpha');
45$cancel = GETPOST('cancel');
46$modulepart = GETPOST('modulepart', 'aZ09'); // Used by actions_setmoduleoptions.inc.php
47
48$functioncode = GETPOST('functioncode', 'alpha');
49$pre_prompt = GETPOST('prePrompt');
50$post_prompt = GETPOST('postPrompt');
51$blacklists = GETPOST('blacklists');
52$test = GETPOST('test');
53
54if (empty($action)) {
55 $action = 'edit';
56}
57
58$error = 0;
59$setupnotempty = 0;
60
61// Access control
62if (!$user->admin) {
64}
65
66
67// Set this to 1 to use the factory to manage constants. Warning, the generated module will be compatible with version v15+ only
68$useFormSetup = 1;
69
70if (!class_exists('FormSetup')) {
71 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formsetup.class.php';
72}
73
74$formSetup = new FormSetup($db);
75
76// Setup conf AI_PROMPT
77$item = $formSetup->newItem('AI_CONFIGURATIONS_PROMPT');
78$item->defaultFieldValue = '';
79
80$setupnotempty += count($formSetup->items);
81
82$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
83
84// List of AI features
85$arrayofaifeatures = array(
86 'textgenerationemail' => array('label' => $langs->trans('TextGeneration').' ('.$langs->trans("EmailContent").')', 'picto'=>'', 'status'=>'development'),
87 'textgenerationwebpage' => array('label' => $langs->trans('TextGeneration').' ('.$langs->trans("WebsitePage").')', 'picto'=>'', 'status'=>'development'),
88 'textgeneration' => array('label' => $langs->trans('TextGeneration').' ('.$langs->trans("Other").')', 'picto'=>'', 'status'=>'notused'),
89 'imagegeneration' => array('label' => 'ImageGeneration', 'picto'=>'', 'status'=>'notused'),
90 'videogeneration' => array('label' => 'VideoGeneration', 'picto'=>'', 'status'=>'notused'),
91 'audiogeneration' => array('label' => 'AudioGeneration', 'picto'=>'', 'status'=>'notused'),
92 'transcription' => array('label' => 'Transcription', 'picto'=>'', 'status'=>'notused'),
93 'translation' => array('label' => 'Translation', 'picto'=>'', 'status'=>'notused')
94);
95
96
97/*
98 * Actions
99 */
100
101// get all configs in const AI
102
103$currentConfigurationsJson = getDolGlobalString('AI_CONFIGURATIONS_PROMPT');
104$currentConfigurations = json_decode($currentConfigurationsJson, true);
105
106if ($action == 'update' && $cancel) {
107 $action = 'edit';
108}
109
110if ($action == 'update' && !$cancel && !$test) {
111 $error = 0;
112 if (empty($functioncode)) {
113 $error++;
114 setEventMessages($langs->trans('ErrorInputRequired'), null, 'errors');
115 }
116 if (!is_array($currentConfigurations)) {
117 $currentConfigurations = [];
118 }
119
120 $blacklistArray = array_filter(array_map('trim', explode(',', $blacklists)));
121
122 if (empty($functioncode) || (empty($pre_prompt) && empty($post_prompt) && empty($blacklists))) {
123 if (isset($currentConfigurations[$functioncode])) {
124 unset($currentConfigurations[$functioncode]);
125 }
126 } else {
127 $currentConfigurations[$functioncode] = [
128 'prePrompt' => $pre_prompt,
129 'postPrompt' => $post_prompt,
130 'blacklists' => $blacklistArray,
131 ];
132 }
133
134 $newConfigurationsJson = json_encode($currentConfigurations, JSON_UNESCAPED_UNICODE);
135 $result = dolibarr_set_const($db, 'AI_CONFIGURATIONS_PROMPT', $newConfigurationsJson, 'chaine', 0, '', $conf->entity);
136 if (!$error) {
137 if ($result) {
138 header("Location: ".$_SERVER['PHP_SELF']);
139 setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
140 exit;
141 } else {
142 setEventMessages($langs->trans("ErrorUpdating"), null, 'errors');
143 }
144 }
145
146 $action = 'edit';
147}
148
149// Update entry
150if ($action == 'updatePrompts' && !$test) {
151 $key = GETPOST('key', 'alpha');
152
153 $blacklistArray = array_filter(array_map('trim', explode(',', $blacklists)));
154
155 $currentConfigurations[$key] = [
156 'prePrompt' => $pre_prompt,
157 'postPrompt' => $post_prompt,
158 'blacklists' => $blacklistArray,
159 ];
160
161 $newConfigurationsJson = json_encode($currentConfigurations, JSON_UNESCAPED_UNICODE);
162 $result = dolibarr_set_const($db, 'AI_CONFIGURATIONS_PROMPT', $newConfigurationsJson, 'chaine', 0, '', $conf->entity);
163 if (!$error) {
164 $action = 'edit';
165 if ($result) {
166 setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
167 } else {
168 setEventMessages($langs->trans("ErrorUpdating"), null, 'errors');
169 }
170 }
171}
172
173// Test entry
174if ($action == 'updatePrompts' && $test) {
175 $action = 'edit';
176}
177
178// Delete entry
179if ($action == 'confirm_deleteproperty' && GETPOST('confirm') == 'yes') {
180 $key = GETPOST('key', 'alpha');
181
182 if (isset($currentConfigurations[$key])) {
183 unset($currentConfigurations[$key]);
184
185 $newConfigurationsJson = json_encode($currentConfigurations, JSON_UNESCAPED_UNICODE);
186 $res = dolibarr_set_const($db, 'AI_CONFIGURATIONS_PROMPT', $newConfigurationsJson, 'chaine', 0, '', $conf->entity);
187 if ($res) {
188 header("Location: ".$_SERVER['PHP_SELF']);
189 setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs');
190 exit;
191 } else {
192 setEventMessages($langs->trans("NoRecordDeleted"), null, 'errors');
193 }
194 }
195}
196
197
198/*
199 * View
200 */
201
202$form = new Form($db);
203
204$help_url = '';
205$title = "AiSetup";
206
207llxHeader('', $langs->trans($title), $help_url, '', 0, 0, '', '', '', 'mod-ai page-admin_custom_prompt');
208
209// Subheader
210$linkback = '<a href="'.($backtopage ? $backtopage : DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1').'">'.$langs->trans("BackToModuleList").'</a>';
211
212print load_fiche_titre($langs->trans($title), $linkback, 'title_setup');
213
214// Configuration header
215$head = aiAdminPrepareHead();
216print dol_get_fiche_head($head, 'custom', $langs->trans($title), -1, "fa-microchip");
217
218//$newbutton = '<a href="'.$_SERVER["PHP_SELF"].'?action=create">'.$langs->trans("New").'</a>';
219$newbutton = '';
220
221print load_fiche_titre($langs->trans("AIPromptForFeatures"), $newbutton, '');
222
223if ($action == 'deleteproperty') {
224 $formconfirm = $form->formconfirm(
225 $_SERVER["PHP_SELF"].'?key='.urlencode(GETPOST('key', 'alpha')),
226 $langs->trans('Delete'),
227 $langs->trans('ConfirmDeleteSetup', GETPOST('key', 'alpha')),
228 'confirm_deleteproperty',
229 '',
230 0,
231 1
232 );
233 print $formconfirm;
234}
235
236if ($action == 'edit' || $action == 'deleteproperty') {
237 $out = '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
238 $out .= '<input type="hidden" name="token" value="'.newToken().'">';
239 $out .= '<input type="hidden" name="action" value="update">';
240
241
242 $out .= '<table class="noborder centpercent">';
243 $out .= '<thead>';
244 $out .= '<tr class="liste_titre">';
245 $out .= '<td>'.$langs->trans('Add').'</td>';
246 $out .= '<td></td>';
247 $out .= '</tr>';
248 $out .= '</thead>';
249
250 $out .= '<tbody>';
251 $out .= '<tr class="oddeven">';
252 $out .= '<td class="col-setup-title titlefield">';
253 $out .= '<span id="module" class="spanforparamtooltip">'.$langs->trans("Feature").'</span>';
254 $out .= '</td>';
255 $out .= '<td>';
256 // Combo list of AI features
257 $out .= '<select name="functioncode" id="functioncode" class="flat minwidth500">';
258 $out .= '<option>&nbsp;</option>';
259 foreach ($arrayofaifeatures as $key => $val) {
260 $labelhtml = $langs->trans($arrayofaifeatures[$key]['label']).($arrayofaifeatures[$key]['status'] == 'notused' ? ' <span class="opacitymedium">('.$langs->trans("NotYetAvailable").')</span>' : "");
261 $labeltext = $langs->trans($arrayofaifeatures[$key]['label']);
262 $out .= '<option value="'.$key.'" data-html="'.dol_escape_htmltag($labelhtml).'">'.dol_escape_htmltag($labeltext).'</option>';
263 }
264 /*
265 $sql = "SELECT name FROM llx_const WHERE name LIKE 'MAIN_MODULE_%' AND value = '1'";
266 $resql = $db->query($sql);
267
268 if ($resql) {
269 while ($obj = $db->fetch_object($resql)) {
270 $moduleName = str_replace('MAIN_MODULE_', '', $obj->name);
271 $out .= '<option value="' . htmlspecialchars($moduleName) . '">' . htmlspecialchars($moduleName) . '</option>';
272 }
273 } else {
274 $out.= '<option disabled>Erreur :'. $db->lasterror().'</option>';
275 }
276 */
277 $out .= '</select>';
278 $out .= ajax_combobox("functioncode");
279
280 $out .= '</td>';
281 $out .= '</tr>';
282 $out .= '<tr class="oddeven">';
283 $out .= '<td class="col-setup-title">';
284 $out .= '<span id="prePrompt" class="spanforparamtooltip">'.$langs->trans("Pre-Prompt").'</span>';
285 $out .= '</td>';
286 $out .= '<td>';
287 $out .= '<textarea class="flat minwidth500 quatrevingtpercent" id="prePromptInput" name="prePrompt" rows="3"></textarea>';
288 $out .= '</td>';
289 $out .= '</tr>';
290 $out .= '<tr class="oddeven">';
291 $out .= '<td class="col-setup-title">';
292 $out .= '<span id="postPrompt" class="spanforparamtooltip">'.$langs->trans("Post-Prompt").'</span>';
293 $out .= '</td>';
294 $out .= '<td>';
295 $out .= '<textarea class="flat minwidth500 quatrevingtpercent" id="postPromptInput" name="postPrompt" rows="3"></textarea>';
296 $out .= '</td>';
297 $out .= '</tr>';
298 $out .= '<tr class="oddeven">';
299 $out .= '<td class="col-setup-title">';
300 $out .= '<span id="blacklists" class="spanforparamtooltip">'.$langs->trans("BlackListWords").' '.img_help(1, 'Words must be separated by a coma (",")').'</span>';
301 $out .= '</td>';
302 $out .= '<td>';
303 $out .= '<textarea class="flat minwidth500 quatrevingtpercent" id="blacklistsInput" name="blacklists" rows="3"></textarea>';
304 $out .= '</td>';
305 $out .= '</tr>';
306 $out .= '</tbody>';
307 $out .= '</table>';
308
309 $out .= $form->buttonsSaveCancel("Add", "");
310 $out .= '</form>';
311 $out .= '<br><br><br>';
312
313 print $out;
314}
315
316
317if ($action == 'edit' || $action == 'create' || $action == 'deleteproperty') {
318 $out = '';
319
320 if (!empty($currentConfigurations)) {
321 foreach ($currentConfigurations as $key => $config) {
322 if (!empty($key) && !preg_match('/^[a-z]+$/i', $key)) { // Ignore empty saved setup
323 continue;
324 }
325
326 $out .= '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
327 $out .= '<input type="hidden" name="token" value="'.newToken().'">';
328 $out .= '<input type="hidden" name="key" value="'.$key.'" />';
329 $out .= '<input type="hidden" name="action" value="updatePrompts">';
330 $out .= '<input type="hidden" name="page_y" value="">';
331
332 $out .= '<table class="noborder centpercent">';
333 $out .= '<thead>';
334 $out .= '<tr class="liste_titre">';
335 $out .= '<td class="titlefield">'.$arrayofaifeatures[$key]['picto'].' '.$langs->trans($arrayofaifeatures[$key]['label']);
336 $out .= '<a class="deletefielda reposition marginleftonly right" href="'.$_SERVER["PHP_SELF"].'?action=deleteproperty&token='.newToken().'&key='.urlencode($key).'">'.img_delete().'</a>';
337 $out .= '</td>';
338 $out .= '<td></td>';
339 $out .= '</tr>';
340 $out .= '</thead>';
341 $out .= '<tbody>';
342
343 $out .= '<tr class="oddeven">';
344 $out .= '<td class="col-setup-title">';
345 $out .= '<span id="prePrompt" class="spanforparamtooltip">'.$langs->trans("Pre-Prompt").'</span>';
346 $out .= '</td>';
347 $out .= '<td>';
348 $out .= '<textarea class="flat minwidth500 quatrevingtpercent" id="prePromptInput_'.$key.'" name="prePrompt" rows="2">'.$config['prePrompt'].'</textarea>';
349 $out .= '</td>';
350 $out .= '</tr>';
351
352 $out .= '<tr class="oddeven">';
353 $out .= '<td class="col-setup-title">';
354 $out .= '<span id="postPrompt" class="spanforparamtooltip">'.$langs->trans("Post-Prompt").'</span>';
355 $out .= '</td>';
356 $out .= '<td>';
357 $out .= '<textarea class="flat minwidth500 quatrevingtpercent" id="postPromptInput_'.$key.'" name="postPrompt" rows="2">'.$config['postPrompt'].'</textarea>';
358 $out .= '</td>';
359 $out .= '</tr>';
360
361 $out .= '<tr id="fichetwothirdright-'.$key.'" class="oddeven">';
362 $out .= '<td>'.$langs->trans("BlackListWords").'</td>';
363 $out .= '<td>';
364 $out .= '<textarea class="flat minwidth500 quatrevingtpercent" id="blacklist_'.$key.'" name="blacklists" rows="3">'.(isset($config['blacklists']) ? implode(', ', (array) $config['blacklists']) : '').'</textarea>';
365 $out .= '</td>';
366 $out .= '</tr>';
367
368 $out .= '<tr>';
369 $out .= '<td></td>';
370 $out .= '<td>';
371 $out .= '<input type="submit" class="button small submitBtn reposition" name="modify" data-index="'.$key.'" value="'.dol_escape_htmltag($langs->trans("Modify")).'"/>';
372 $out .= ' &nbsp; ';
373
374 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
375 $showlinktoai = $key; // 'textgeneration', 'imagegeneration', ...
376 $showlinktoailabel = $langs->trans("ToTest");
377 $formmail = new FormMail($db);
378 $htmlname = $key;
379
380 // Fill $out
381 include DOL_DOCUMENT_ROOT.'/core/tpl/formlayoutai.tpl.php';
382
383 $out .= '<div id="'.$htmlname.'"></div>';
384
385 $out .= '</td>';
386 $out .= '</tr>';
387
388 $out .= '</tbody>';
389 $out .= '</table>';
390
391 $out .= '</form>';
392 }
393 }
394
395 print $out;
396
397 print '<br>';
398}
399
400if (empty($setupnotempty)) {
401 print '<br>'.$langs->trans("NothingToSetup");
402}
403
404
405// Page end
406print dol_get_fiche_end();
407
408llxFooter();
409$db->close();
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).
aiAdminPrepareHead()
Prepare admin pages header.
Definition ai.lib.php:31
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='')
Convert a html select field into an ajax combobox.
Definition ajax.lib.php:459
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:71
Class to manage generation of HTML components Only common components must be here.
Class permettant la generation du formulaire html d'envoi de mail unitaire Usage: $formail = new Form...
This class help you create setup render.
llxFooter()
Footer empty.
Definition document.php:107
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
Load a title with picto.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
img_help($usehelpcursor=1, $usealttitle=1)
Show help logo with cursor "?".
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0)
Show tabs of a record.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
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)
Return value of a param into GET or POST supervariable.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.