dolibarr 23.0.3
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) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
4 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2025 Quentin VIAL--GOUTEYRON <quentin.vial-gouteyron@atm-consulting.fr>
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
28// Load Dolibarr environment
29require '../../main.inc.php';
30require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php";
31require_once DOL_DOCUMENT_ROOT.'/datapolicy/lib/datapolicy.lib.php';
32require_once DOL_DOCUMENT_ROOT.'/datapolicy/class/datapolicycron.class.php';
33require_once DOL_DOCUMENT_ROOT.'/cron/class/cronjob.class.php';
34
44if (!$langs instanceof Translate) {
45 trigger_error("Langs object was not initialized correctly.", E_USER_ERROR);
46}
47
48// Translations
49$langs->loadLangs(array('admin', 'companies', 'members', 'cron', 'datapolicy', 'recruitment'));
50
51// Parameters
52$action = GETPOST('action', 'aZ09');
53$backtopage = GETPOST('backtopage', 'alpha');
54
55if (empty($action)) {
56 $action = 'edit';
57}
58
59// Get the array $arrayofparameters from _getDataPolicies
60$arrayofparameters = array();
61$dataPolicyCron = new DataPolicyCron($db);
62$arrayofelem = $dataPolicyCron->getDataPolicies();
63$arrayofparameters = array();
64foreach ($arrayofelem as $key => $val) {
65 $arrayofparameters[$val['group']][$key] = array(
66 'label_key' => $val['label_key'],
67 'picto' => $val['picto'],
68 'config_keys' => array(
69 'anonymize' => $val['const_anonymize'],
70 'delete' => $val['const_delete']
71 )
72 );
73}
74
75
76// Dropdown options for delay selection
77$valTab = array(
78 '' => $langs->trans('Never'),
79 '6' => $langs->trans('NB_MONTHS', 6),
80 '12' => $langs->trans('ONE_YEAR'),
81 '24' => $langs->trans('NB_YEARS', 2),
82 '36' => $langs->trans('NB_YEARS', 3),
83 '48' => $langs->trans('NB_YEARS', 4),
84 '60' => $langs->trans('NB_YEARS', 5),
85 '120' => $langs->trans('NB_YEARS', 10),
86 '180' => $langs->trans('NB_YEARS', 15),
87 '240' => $langs->trans('NB_YEARS', 20),
88);
89
90// Security
91if (!isModEnabled("datapolicy")) {
93}
94if (!$user->admin) {
96}
97
98/*
99 * Actions
100 */
101// Handle form submission to update constants
102if ($action == 'update') {
103 $nbdone = 0;
104 $error = 0;
105
106 // Loop through the data structure to find all possible constants to save.
107 foreach ($arrayofparameters as $tab) {
108 foreach ($tab as $logicalKey => $val) {
109 // Iterate through defined actions ('anonymize', 'delete') for the entity.
110 foreach ($val['config_keys'] as $actionType => $constKey) {
111 // Save the constant only if its value was submitted in the form.
112 if (GETPOSTISSET($constKey)) {
113 $val_const = GETPOST($constKey, 'alpha');
114 if (dolibarr_set_const($db, $constKey, $val_const, 'chaine', 0, '', $conf->entity) >= 0) {
115 $nbdone++;
116 } else {
117 $error++;
118 }
119 }
120 }
121 }
122 }
123
124 if ($nbdone > 0) {
125 setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
126 }
127 if ($error > 0) {
128 setEventMessages($langs->trans("Error"), null, 'errors');
129 }
130 $action = 'edit';
131}
132
133
134/*
135 * View
136 */
137
138$page_name = "datapolicySetup";
139llxHeader('', $langs->trans($page_name));
140
141$linkback = '<a href="'.($backtopage ? $backtopage : 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>';
142print load_fiche_titre($langs->trans($page_name), $linkback, 'generic');
143
145print dol_get_fiche_head($head, 'settings', '', -1, '');
146
147print '<span class="opacitymedium">'.$langs->trans("datapolicySetupPage").'</span>';
148print $form->textwithpicto('', $langs->trans('DATAPOLICY_Tooltip_SETUP', $langs->transnoentitiesnoconv("DATAPOLICYJob"), $langs->transnoentitiesnoconv("CronList")));
149if (!isModEnabled('cron')) {
150 print info_admin($langs->trans("ModuleMustBeEnabledFirst", $langs->transnoentitiesnoconv("CronList")), 0, 0, 'warning');
151} else {
152 $tmpjob = new Cronjob($db);
153 $tmpjob->fetch(0, '', '', 'DATAPOLICYJob');
154 if ($tmpjob->status != $tmpjob::STATUS_ENABLED) {
155 print info_admin($langs->trans("JobMustBeEnabledFirst", $langs->transnoentitiesnoconv("DATAPOLICYJob"), $langs->transnoentitiesnoconv("CronList")), 0, 0, 'warning');
156 } else {
157 // TODO Show last date/result of execution of the cron job
158 }
159}
160print '<br><br>';
161
162print '<form method="POST" action="'.dolBuildUrl($_SERVER["PHP_SELF"]).'">';
163print '<input type="hidden" name="token" value="'.newToken().'">';
164print '<input type="hidden" name="action" value="update">';
165print '<input type="hidden" name="page_y" value="">';
166
167print '<div class="div-table-responsive">';
168print '<table class="tagtable nobottomiftotal liste">';
169
170// Table Headers
171print '<tr class="liste_titre"><td class="titlefield"></td>';
172print '<td>'.$langs->trans("DelayForAnonymization").'</td>';
173print '<td>'.$langs->trans("DelayForDeletion").'</td>';
174print '</tr>';
175
176// ==============================================================================
177// == DYNAMIC VIEW RENDERING
178// ==============================================================================
179
180// Loop through each configuration group (e.g., ThirdParty, Member).
181foreach ($arrayofparameters as $title => $tab) {
182 print '<tr class="trforbreak liste_titre"><td class="titlefield trforbreak">'.$langs->trans($title).'</td>';
183 print '<td></td>';
184 print '<td></td>';
185 print '</tr>';
186
187 // Loop through each entity within the group to create a table row.
188 foreach ($tab as $logicalKey => $val) {
189 print '<tr class="oddeven"><td>';
190 print $val['picto'];
191 print $langs->trans($val['label_key']);
192 print '</td>';
193
194 // Column 1: Anonymization
195 print '<td class="nowraponall">';
196 // Display the dropdown only if a constant key is defined for the 'anonymize' action.
197 if (!empty($val['config_keys']['anonymize'])) {
198 $selectedvalue = getDolGlobalString($val['config_keys']['anonymize']);
199
200 print Form::selectarray($val['config_keys']['anonymize'], $valTab, $selectedvalue, 0, 0, 0, '', 0, 0, 0, '', 'minwidth100');
201
202 //var_dump($val);
203 $listoffieldsid = '';
204 foreach ($arrayofelem[$logicalKey]['anonymize_fields'] as $tmpkey => $tmpval) {
205 if (is_array($tmpval)) {
206 continue;
207 }
208 if ($tmpval === 'MAKEANONYMOUS') {
209 $listoffieldsid .= ($listoffieldsid ? ', ' : '').$tmpkey.' -> '.$tmpkey.'-anon-ID';
210 } elseif (strpos($tmpval, '__ID__') !== false) {
211 $listoffieldsid .= ($listoffieldsid ? ', ' : '').$tmpkey.' -> '.$tmpval;
212 }
213 }
214 $otherfields = '';
215 foreach ($arrayofelem[$logicalKey]['anonymize_fields'] as $tmpkey => $tmpval) {
216 if ($tmpval !== 'MAKEANONYMOUS' && strpos((string) $tmpval, '__ID__') === false) {
217 $otherfields .= ($otherfields ? ', ' : '').$tmpkey.' -> '.json_encode($tmpval);
218 }
219 }
220
221 $sql = $arrayofelem[$logicalKey]['sql_template'];
222 $sql = preg_replace('/__ENTITY__/', (string) (int) $conf->entity, $sql);
223 $sql = preg_replace('/__DELAY__/', (string) (int) $selectedvalue, $sql);
224 $sql = preg_replace('/__NOW__/', "'".dol_print_date(dol_now(), 'standard')."'", $sql);
225 $sql = preg_replace('/^SELECT [\w+\s+\._]+ FROM/', 'SELECT COUNT(*) as nb FROM', $sql);
226
227 $htmltooltip = $langs->transnoentitiesnoconv("TheFollowingFieldsAreReplaceWith");
228 $htmltooltip .= '<br><small class="opacitymedium">'.$listoffieldsid.'</small>';
229 $htmltooltip .= '<br><br>'.$langs->transnoentitiesnoconv("OtherFieldsAreReplaceWithStaticValues");
230 $htmltooltip .= '<br><small class="opacitymedium">'.$otherfields.'</small>';
231 $htmltooltip .= '<br><br>'.$langs->transnoentitiesnoconv("TechnicalInformation").' - SQL to select record:';
232 $htmltooltip .= '<br><small class="opacitymedium">'.$sql.'</small>';
233 print $form->textwithpicto('', $htmltooltip, 1, 'help', 'valignmidde', 1, 3, $val['config_keys']['anonymize']);
234
235 print ' &nbsp; ';
236 if ($action == 'count' && GETPOST('group') == $logicalKey) {
237 print '<span class="opacitymedium valignmiddle">'.$langs->trans("QualifiedNumber").' : </span>';
238
239 $estimatednumber = 0;
240 if ($sql) {
241 $resql = $db->query($sql);
242 if ($resql) {
243 $obj = $db->fetch_object($resql);
244 if ($obj) {
245 $estimatednumber = $obj->nb;
246 }
247 } else {
248 dol_print_error($db);
249 }
250 } else {
251 print 'Error, bad definition of the array of data policies profiles';
252 }
253
254 print '<span class="valignmiddle badge badge-info">'.$estimatednumber.'</span>';
255 } elseif ($selectedvalue) {
256 print '<span class="opacitymedium valignmiddle">'.$langs->trans("QualifiedNumber").' : </span>';
257
258 print '<a class="reposition valignmiddle" href="'.$_SERVER["PHP_SELF"].'?action=count&group='.urlencode($logicalKey).'">';
259 print $langs->trans("Calculate");
260 print '</a>';
261 }
262 }
263 print '</td>';
264
265 // Column 2: Deletion
266 print '<td>';
267 if (!empty($val['config_keys']['delete'])) {
268 $selectedvalue = getDolGlobalString($val['config_keys']['delete']);
269
270 // Display the dropdown only if a constant key is defined for the 'delete' action.
271 print Form::selectarray($val['config_keys']['delete'], $valTab, $selectedvalue, 0, 0, 0, '', 0, 0, 0, '', 'minwidth100');
272
273 $sql = $arrayofelem[$logicalKey]['sql_template_delete'];
274 $sql = preg_replace('/__ENTITY__/', (string) (int) $conf->entity, $sql);
275 $sql = preg_replace('/__DELAY__/', (string) (int) $selectedvalue, $sql);
276 $sql = preg_replace('/__NOW__/', "'".dol_print_date(dol_now(), 'standard')."'", $sql);
277 $sql = preg_replace('/^SELECT [\w+\s+\._]+ FROM/', 'SELECT COUNT(*) as nb FROM', $sql);
278
279 $htmltooltip = $langs->transnoentitiesnoconv("TechnicalInformation").' - SQL to select record:';
280 $htmltooltip .= '<br><small class="opacitymedium">'.$sql.'</small>';
281 print $form->textwithpicto('', $htmltooltip, 1, 'help', 'valignmidde', 1, 3, $val['config_keys']['delete']);
282
283 print ' &nbsp; ';
284 if ($action == 'countdelete' && GETPOST('group') == $logicalKey) {
285 print '<span class="opacitymedium valignmiddle">'.$langs->trans("QualifiedNumber").' : </span>';
286
287 $estimatednumber = 0;
288 if ($sql) {
289 $resql = $db->query($sql);
290 if ($resql) {
291 $obj = $db->fetch_object($resql);
292 if ($obj) {
293 $estimatednumber = $obj->nb;
294 }
295 } else {
296 dol_print_error($db);
297 }
298 } else {
299 print 'Error, bad definition of the array of data policies profiles';
300 }
301
302 print '<span class="valignmiddle badge badge-info">'.$estimatednumber.'</span>';
303 } elseif ($selectedvalue) {
304 print '<span class="opacitymedium valignmiddle">'.$langs->trans("QualifiedNumber").' : </span>';
305
306 print '<a class="reposition valignmiddle" href="'.$_SERVER["PHP_SELF"].'?action=countdelete&group='.urlencode($logicalKey).'">';
307 print $langs->trans("Calculate");
308 print '</a>';
309 }
310 }
311 print '</td>';
312
313 print '</tr>';
314 }
315}
316
317print '</table>';
318print '</div>';
319
320print $form->buttonsSaveCancel("Save", '', array(), false, 'reposition');
321
322print '</form>';
323print '<br>';
324
325
326print dol_get_fiche_end();
327llxFooter();
328$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).
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
Cron Job class.
Class DataPolicyCron.
static selectarray($htmlname, $array, $id='', $show_empty=0, $key_in_label=0, $value_as_key=0, $moreparam='', $translate=0, $maxlen=0, $disabled=0, $sort='', $morecss='minwidth75', $addjscombo=1, $moreparamonempty='', $disablebademail=0, $nohtmlescape=0)
Return a HTML select string, built from an array of key+value.
Class to manage translations.
datapolicyAdminPrepareHead()
Prepare admin pages header.
dol_now($mode='gmt')
Return date for now.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
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.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='')
Show information in HTML for admin users or standard users.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.