dolibarr 21.0.0-alpha
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
32$langs->loadLangs(array("admin", "website", "other"));
33
34// Parameters
35$action = GETPOST('action', 'aZ09');
36$backtopage = GETPOST('backtopage', 'alpha');
37$cancel = GETPOST('cancel');
38$modulepart = GETPOST('modulepart', 'aZ09'); // Used by actions_setmoduleoptions.inc.php
39
40$functioncode = GETPOST('functioncode', 'alpha');
41$pre_prompt = GETPOST('prePrompt');
42$post_prompt = GETPOST('postPrompt');
43$blacklists = GETPOST('blacklists');
44$test = GETPOST('test');
45
46if (empty($action)) {
47 $action = 'edit';
48}
49
50$error = 0;
51$setupnotempty = 0;
52
53// Access control
54if (!$user->admin) {
56}
57
58
59// Set this to 1 to use the factory to manage constants. Warning, the generated module will be compatible with version v15+ only
60$useFormSetup = 1;
61
62if (!class_exists('FormSetup')) {
63 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formsetup.class.php';
64}
65
66$formSetup = new FormSetup($db);
67
68// Setup conf AI_PROMPT
69$item = $formSetup->newItem('AI_CONFIGURATIONS_PROMPT');
70$item->defaultFieldValue = '';
71
72$setupnotempty += count($formSetup->items);
73
74$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
75
76// List of AI features
77$arrayofaifeatures = array(
78 'textgenerationemail' => array('label' => $langs->trans('TextGeneration').' ('.$langs->trans("EmailContent").')', 'picto'=>'', 'status'=>'development'),
79 'textgenerationwebpage' => array('label' => $langs->trans('TextGeneration').' ('.$langs->trans("WebsitePage").')', 'picto'=>'', 'status'=>'development'),
80 'textgeneration' => array('label' => $langs->trans('TextGeneration').' ('.$langs->trans("Other").')', 'picto'=>'', 'status'=>'notused'),
81 'imagegeneration' => array('label' => 'ImageGeneration', 'picto'=>'', 'status'=>'notused'),
82 'videogeneration' => array('label' => 'VideoGeneration', 'picto'=>'', 'status'=>'notused'),
83 'audiogeneration' => array('label' => 'AudioGeneration', 'picto'=>'', 'status'=>'notused'),
84 'transcription' => array('label' => 'Transcription', 'picto'=>'', 'status'=>'notused'),
85 'translation' => array('label' => 'Translation', 'picto'=>'', 'status'=>'notused')
86);
87
88
89/*
90 * Actions
91 */
92
93// get all configs in const AI
94
95$currentConfigurationsJson = getDolGlobalString('AI_CONFIGURATIONS_PROMPT');
96$currentConfigurations = json_decode($currentConfigurationsJson, true);
97
98if ($action == 'update' && $cancel) {
99 $action = 'edit';
100}
101
102if ($action == 'update' && !$cancel && !$test) {
103 $error = 0;
104 if (empty($functioncode)) {
105 $error++;
106 setEventMessages($langs->trans('ErrorInputRequired'), null, 'errors');
107 }
108 if (!is_array($currentConfigurations)) {
109 $currentConfigurations = [];
110 }
111
112 $blacklistArray = array_filter(array_map('trim', explode(',', $blacklists)));
113
114 if (empty($functioncode) || (empty($pre_prompt) && empty($post_prompt) && empty($blacklists))) {
115 if (isset($currentConfigurations[$functioncode])) {
116 unset($currentConfigurations[$functioncode]);
117 }
118 } else {
119 $currentConfigurations[$functioncode] = [
120 'prePrompt' => $pre_prompt,
121 'postPrompt' => $post_prompt,
122 'blacklists' => $blacklistArray,
123 ];
124 }
125
126 $newConfigurationsJson = json_encode($currentConfigurations, JSON_UNESCAPED_UNICODE);
127 $result = dolibarr_set_const($db, 'AI_CONFIGURATIONS_PROMPT', $newConfigurationsJson, 'chaine', 0, '', $conf->entity);
128 if (!$error) {
129 if ($result) {
130 header("Location: ".$_SERVER['PHP_SELF']);
131 setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
132 exit;
133 } else {
134 setEventMessages($langs->trans("ErrorUpdating"), null, 'errors');
135 }
136 }
137
138 $action = 'edit';
139}
140
141// Update entry
142if ($action == 'updatePrompts' && !$test) {
143 $key = GETPOST('key', 'alpha');
144
145 $blacklistArray = array_filter(array_map('trim', explode(',', $blacklists)));
146
147 $currentConfigurations[$key] = [
148 'prePrompt' => $pre_prompt,
149 'postPrompt' => $post_prompt,
150 'blacklists' => $blacklistArray,
151 ];
152
153 $newConfigurationsJson = json_encode($currentConfigurations, JSON_UNESCAPED_UNICODE);
154 $result = dolibarr_set_const($db, 'AI_CONFIGURATIONS_PROMPT', $newConfigurationsJson, 'chaine', 0, '', $conf->entity);
155 if (!$error) {
156 $action = 'edit';
157 if ($result) {
158 setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
159 } else {
160 setEventMessages($langs->trans("ErrorUpdating"), null, 'errors');
161 }
162 }
163}
164
165// Test entry
166if ($action == 'updatePrompts' && $test) {
167 $action = 'edit';
168}
169
170// Delete entry
171if ($action == 'confirm_deleteproperty' && GETPOST('confirm') == 'yes') {
172 $key = GETPOST('key', 'alpha');
173
174 if (isset($currentConfigurations[$key])) {
175 unset($currentConfigurations[$key]);
176
177 $newConfigurationsJson = json_encode($currentConfigurations, JSON_UNESCAPED_UNICODE);
178 $res = dolibarr_set_const($db, 'AI_CONFIGURATIONS_PROMPT', $newConfigurationsJson, 'chaine', 0, '', $conf->entity);
179 if ($res) {
180 header("Location: ".$_SERVER['PHP_SELF']);
181 setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs');
182 exit;
183 } else {
184 setEventMessages($langs->trans("NoRecordDeleted"), null, 'errors');
185 }
186 }
187}
188
189
190/*
191 * View
192 */
193
194$form = new Form($db);
195
196$help_url = '';
197$title = "AiSetup";
198
199llxHeader('', $langs->trans($title), $help_url, '', 0, 0, '', '', '', 'mod-ai page-admin_custom_prompt');
200
201// Subheader
202$linkback = '<a href="'.($backtopage ? $backtopage : DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1').'">'.$langs->trans("BackToModuleList").'</a>';
203
204print load_fiche_titre($langs->trans($title), $linkback, 'title_setup');
205
206// Configuration header
207$head = aiAdminPrepareHead();
208print dol_get_fiche_head($head, 'custom', $langs->trans($title), -1, "fa-microchip");
209
210//$newbutton = '<a href="'.$_SERVER["PHP_SELF"].'?action=create">'.$langs->trans("New").'</a>';
211$newbutton = '';
212
213print load_fiche_titre($langs->trans("AIPromptForFeatures"), $newbutton, '');
214
215if ($action == 'deleteproperty') {
216 $formconfirm = $form->formconfirm(
217 $_SERVER["PHP_SELF"].'?key='.urlencode(GETPOST('key', 'alpha')),
218 $langs->trans('Delete'),
219 $langs->trans('ConfirmDeleteSetup', GETPOST('key', 'alpha')),
220 'confirm_deleteproperty',
221 '',
222 0,
223 1
224 );
225 print $formconfirm;
226}
227
228if ($action == 'edit' || $action == 'deleteproperty') {
229 $out = '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
230 $out .= '<input type="hidden" name="token" value="'.newToken().'">';
231 $out .= '<input type="hidden" name="action" value="update">';
232
233
234 $out .= '<table class="noborder centpercent">';
235 $out .= '<thead>';
236 $out .= '<tr class="liste_titre">';
237 $out .= '<td>'.$langs->trans('Add').'</td>';
238 $out .= '<td></td>';
239 $out .= '</tr>';
240 $out .= '</thead>';
241
242 $out .= '<tbody>';
243 $out .= '<tr class="oddeven">';
244 $out .= '<td class="col-setup-title titlefield">';
245 $out .= '<span id="module" class="spanforparamtooltip">'.$langs->trans("Feature").'</span>';
246 $out .= '</td>';
247 $out .= '<td>';
248 // Combo list of AI features
249 $out .= '<select name="functioncode" id="functioncode" class="flat minwidth500">';
250 $out .= '<option>&nbsp;</option>';
251 foreach ($arrayofaifeatures as $key => $val) {
252 $labelhtml = $langs->trans($arrayofaifeatures[$key]['label']).($arrayofaifeatures[$key]['status'] == 'notused' ? ' <span class="opacitymedium">('.$langs->trans("NotYetAvailable").')</span>' : "");
253 $labeltext = $langs->trans($arrayofaifeatures[$key]['label']);
254 $out .= '<option value="'.$key.'" data-html="'.dol_escape_htmltag($labelhtml).'">'.dol_escape_htmltag($labeltext).'</option>';
255 }
256 /*
257 $sql = "SELECT name FROM llx_const WHERE name LIKE 'MAIN_MODULE_%' AND value = '1'";
258 $resql = $db->query($sql);
259
260 if ($resql) {
261 while ($obj = $db->fetch_object($resql)) {
262 $moduleName = str_replace('MAIN_MODULE_', '', $obj->name);
263 $out .= '<option value="' . htmlspecialchars($moduleName) . '">' . htmlspecialchars($moduleName) . '</option>';
264 }
265 } else {
266 $out.= '<option disabled>Erreur :'. $db->lasterror().'</option>';
267 }
268 */
269 $out .= '</select>';
270 $out .= ajax_combobox("functioncode");
271
272 $out .= '</td>';
273 $out .= '</tr>';
274 $out .= '<tr class="oddeven">';
275 $out .= '<td class="col-setup-title">';
276 $out .= '<span id="prePrompt" class="spanforparamtooltip">'.$langs->trans("Pre-Prompt").'</span>';
277 $out .= '</td>';
278 $out .= '<td>';
279 $out .= '<textarea class="flat minwidth500 quatrevingtpercent" id="prePromptInput" name="prePrompt" rows="3"></textarea>';
280 $out .= '</td>';
281 $out .= '</tr>';
282 $out .= '<tr class="oddeven">';
283 $out .= '<td class="col-setup-title">';
284 $out .= '<span id="postPrompt" class="spanforparamtooltip">'.$langs->trans("Post-Prompt").'</span>';
285 $out .= '</td>';
286 $out .= '<td>';
287 $out .= '<textarea class="flat minwidth500 quatrevingtpercent" id="postPromptInput" name="postPrompt" 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="blacklists" class="spanforparamtooltip">'.$langs->trans("BlackListWords").' '.img_help(1, 'Words must be separated by a coma (",")').'</span>';
293 $out .= '</td>';
294 $out .= '<td>';
295 $out .= '<textarea class="flat minwidth500 quatrevingtpercent" id="blacklistsInput" name="blacklists" rows="3"></textarea>';
296 $out .= '</td>';
297 $out .= '</tr>';
298 $out .= '</tbody>';
299 $out .= '</table>';
300
301 $out .= $form->buttonsSaveCancel("Add", "");
302 $out .= '</form>';
303 $out .= '<br><br><br>';
304
305 print $out;
306}
307
308
309if ($action == 'edit' || $action == 'create' || $action == 'deleteproperty') {
310 $out = '';
311
312 if (!empty($currentConfigurations)) {
313 foreach ($currentConfigurations as $key => $config) {
314 if (!empty($key) && !preg_match('/^[a-z]+$/i', $key)) { // Ignore empty saved setup
315 continue;
316 }
317
318 $out .= '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
319 $out .= '<input type="hidden" name="token" value="'.newToken().'">';
320 $out .= '<input type="hidden" name="key" value="'.$key.'" />';
321 $out .= '<input type="hidden" name="action" value="updatePrompts">';
322 $out .= '<input type="hidden" name="page_y" value="">';
323
324 $out .= '<table class="noborder centpercent">';
325 $out .= '<thead>';
326 $out .= '<tr class="liste_titre">';
327 $out .= '<td class="titlefield">'.$arrayofaifeatures[$key]['picto'].' '.$langs->trans($arrayofaifeatures[$key]['label']);
328 $out .= '<a class="deletefielda reposition marginleftonly right" href="'.$_SERVER["PHP_SELF"].'?action=deleteproperty&token='.newToken().'&key='.urlencode($key).'">'.img_delete().'</a>';
329 $out .= '</td>';
330 $out .= '<td></td>';
331 $out .= '</tr>';
332 $out .= '</thead>';
333 $out .= '<tbody>';
334
335 $out .= '<tr class="oddeven">';
336 $out .= '<td class="col-setup-title">';
337 $out .= '<span id="prePrompt" class="spanforparamtooltip">'.$langs->trans("Pre-Prompt").'</span>';
338 $out .= '</td>';
339 $out .= '<td>';
340 $out .= '<textarea class="flat minwidth500 quatrevingtpercent" id="prePromptInput_'.$key.'" name="prePrompt" rows="2">'.$config['prePrompt'].'</textarea>';
341 $out .= '</td>';
342 $out .= '</tr>';
343
344 $out .= '<tr class="oddeven">';
345 $out .= '<td class="col-setup-title">';
346 $out .= '<span id="postPrompt" class="spanforparamtooltip">'.$langs->trans("Post-Prompt").'</span>';
347 $out .= '</td>';
348 $out .= '<td>';
349 $out .= '<textarea class="flat minwidth500 quatrevingtpercent" id="postPromptInput_'.$key.'" name="postPrompt" rows="2">'.$config['postPrompt'].'</textarea>';
350 $out .= '</td>';
351 $out .= '</tr>';
352
353 $out .= '<tr id="fichetwothirdright-'.$key.'" class="oddeven">';
354 $out .= '<td>'.$langs->trans("BlackListWords").'</td>';
355 $out .= '<td>';
356 $out .= '<textarea class="flat minwidth500 quatrevingtpercent" id="blacklist_'.$key.'" name="blacklists" rows="3">'.(isset($config['blacklists']) ? implode(', ', (array) $config['blacklists']) : '').'</textarea>';
357 $out .= '</td>';
358 $out .= '</tr>';
359
360 $out .= '<tr>';
361 $out .= '<td></td>';
362 $out .= '<td>';
363 $out .= '<input type="submit" class="button small submitBtn reposition" name="modify" data-index="'.$key.'" value="'.dol_escape_htmltag($langs->trans("Modify")).'"/>';
364 $out .= ' &nbsp; ';
365
366 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
367 $showlinktoai = $key; // 'textgeneration', 'imagegeneration', ...
368 $showlinktoailabel = $langs->trans("ToTest");
369 $formmail = new FormMail($db);
370 $htmlname = $key;
371
372 // Fill $out
373 include DOL_DOCUMENT_ROOT.'/core/tpl/formlayoutai.tpl.php';
374
375 $out .= '<div id="'.$htmlname.'"></div>';
376
377 $out .= '</td>';
378 $out .= '</tr>';
379
380 $out .= '</tbody>';
381 $out .= '</table>';
382
383 $out .= '</form>';
384 }
385 }
386
387 print $out;
388
389 print '<br>';
390}
391
392if (empty($setupnotempty)) {
393 print '<br>'.$langs->trans("NothingToSetup");
394}
395
396
397// Page end
398print dol_get_fiche_end();
399
400llxFooter();
401$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:457
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:70
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...
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.