1<?php
2/* Copyright (C) 2017-2020	Laurent Destailleur	<eldy@users.sourceforge.net>
3 * Copyright (C) 2017-2018	Regis Houssin		<regis.houssin@inodbox.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
19/**
20 *       \file      htdocs/admin/defaultvalues.php
21 *       \brief     Page to set default values used used in a create form
22 *       			Default values are stored into $user->default_values[url]['createform']['querystring'|'_noquery_'][paramkey]=paramvalue
23 *       			Default filters are stored into $user->default_values[url]['filters']['querystring'|'_noquery_'][paramkey]=paramvalue
24 *       			Default sort order are stored into $user->default_values[url]['sortorder']['querystring'|'_noquery_'][paramkey]=paramvalue
25 *       			Default focus are stored into $user->default_values[url]['focus']['querystring'|'_noquery_'][paramkey]=paramvalue
26 *       			Mandatory fields are stored into $user->default_values[url]['mandatory']['querystring'|'_noquery_'][paramkey]=paramvalue
27 */
28
29require '../main.inc.php';
30require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
31require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
32require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
33
34// Load translation files required by the page
35$langs->loadLangs(array('companies', 'products', 'admin', 'sms', 'other', 'errors'));
36
37if (!$user->admin) accessforbidden();
38
39$id = GETPOST('rowid', 'int');
40$action = GETPOST('action', 'aZ09');
41$optioncss = GETPOST('optionscss', 'alphanohtml');
42
43$mode = GETPOST('mode', 'aZ09') ?GETPOST('mode', 'aZ09') : 'createform'; // 'createform', 'filters', 'sortorder', 'focus'
44
45$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
46$sortfield = GETPOST("sortfield", 'alpha');
47$sortorder = GETPOST("sortorder", 'alpha');
48$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
49if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
50$offset = $limit * $page;
51$pageprev = $page - 1;
52$pagenext = $page + 1;
53if (!$sortfield) $sortfield = 'page,param';
54if (!$sortorder) $sortorder = 'ASC';
55
56$defaulturl = GETPOST('defaulturl', 'alphanohtml');
57$defaultkey = GETPOST('defaultkey', 'alphanohtml');
58$defaultvalue = GETPOST('defaultvalue', 'none');
59
60$defaulturl = preg_replace('/^\//', '', $defaulturl);
61
62$urlpage = GETPOST('urlpage', 'alphanohtml');
63$key = GETPOST('key', 'alphanohtml');
64$value = GETPOST('value', 'restricthtml');
65
66// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
67$hookmanager->initHooks(array('admindefaultvalues', 'globaladmin'));
68
69
70/*
71 * Actions
72 */
73
74if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
75if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; }
76
77$parameters = array('socid'=>$socid);
78$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
79if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
80
81include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
82
83// Purge search criteria
84if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
85{
86	$defaulturl = '';
87	$defaultkey = '';
88	$defaultvalue = '';
89	$toselect = '';
90	$search_array_options = array();
91}
92
93if ($action == 'setMAIN_ENABLE_DEFAULT_VALUES')
94{
95	if (GETPOST('value')) dolibarr_set_const($db, 'MAIN_ENABLE_DEFAULT_VALUES', 1, 'chaine', 0, '', $conf->entity);
96	else dolibarr_set_const($db, 'MAIN_ENABLE_DEFAULT_VALUES', 0, 'chaine', 0, '', $conf->entity);
97}
98
99if (($action == 'add' || (GETPOST('add') && $action != 'update')) || GETPOST('actionmodify'))
100{
101	$error = 0;
102
103	if (($action == 'add' || (GETPOST('add') && $action != 'update')))
104	{
105		if (empty($defaulturl))
106		{
107			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Url")), null, 'errors');
108			$error++;
109		}
110		if (empty($defaultkey))
111		{
112			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Field")), null, 'errors');
113			$error++;
114		}
115	}
116	if (GETPOST('actionmodify'))
117	{
118		if (empty($urlpage))
119		{
120			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Url")), null, 'errors');
121			$error++;
122		}
123		if (empty($key))
124		{
125			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Field")), null, 'errors');
126			$error++;
127		}
128	}
129
130	if (!$error)
131	{
132		$db->begin();
133
134		if ($action == 'add' || (GETPOST('add') && $action != 'update'))
135		{
136			$sql = "INSERT INTO ".MAIN_DB_PREFIX."default_values(type, user_id, page, param, value, entity) VALUES ('".$db->escape($mode)."', 0, '".$db->escape($defaulturl)."','".$db->escape($defaultkey)."','".$db->escape($defaultvalue)."', ".$db->escape($conf->entity).")";
137		}
138		if (GETPOST('actionmodify'))
139		{
140			$sql = "UPDATE ".MAIN_DB_PREFIX."default_values SET page = '".$db->escape($urlpage)."', param = '".$db->escape($key)."', value = '".$db->escape($value)."'";
141			$sql .= " WHERE rowid = ".$id;
142		}
143
144		$result = $db->query($sql);
145		if ($result > 0)
146		{
147			$db->commit();
148			setEventMessages($langs->trans("RecordSaved"), null, 'mesgs');
149			$action = "";
150			$defaulturl = '';
151			$defaultkey = '';
152			$defaultvalue = '';
153		} else {
154			$db->rollback();
155			setEventMessages($db->lasterror(), null, 'errors');
156			$action = '';
157		}
158	}
159}
160
161// Delete line from delete picto
162if ($action == 'delete')
163{
164	$sql = "DELETE FROM ".MAIN_DB_PREFIX."default_values WHERE rowid = ".$db->escape($id);
165	// Delete const
166	$result = $db->query($sql);
167	if ($result >= 0)
168	{
169		setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs');
170	} else {
171		dol_print_error($db);
172	}
173}
174
175
176
177/*
178 * View
179 */
180
181$form = new Form($db);
182$formadmin = new FormAdmin($db);
183
184$wikihelp = 'EN:First_setup|FR:Premiers_paramétrages|ES:Primeras_configuraciones';
185llxHeader('', $langs->trans("Setup"), $wikihelp);
186
187$param = '&mode='.$mode;
188
189$enabledisablehtml .= $langs->trans("EnableDefaultValues").' ';
190if (empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES))
191{
192	// Button off, click to enable
193	$enabledisablehtml .= '<a class="reposition valignmiddle" href="'.$_SERVER["PHP_SELF"].'?action=setMAIN_ENABLE_DEFAULT_VALUES&amp;token='.newToken().'&amp;value=1'.$param.'">';
194	$enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off');
195	$enabledisablehtml .= '</a>';
196} else {
197	// Button on, click to disable
198	$enabledisablehtml .= '<a class="reposition valignmiddle" href="'.$_SERVER["PHP_SELF"].'?action=setMAIN_ENABLE_DEFAULT_VALUES&amp;token='.newToken().'&amp;value=0'.$param.'">';
199	$enabledisablehtml .= img_picto($langs->trans("Activated"), 'switch_on');
200	$enabledisablehtml .= '</a>';
201}
202
203print load_fiche_titre($langs->trans("DefaultValues"), $enabledisablehtml, 'title_setup');
204
205print '<span class="opacitymedium">'.$langs->trans("DefaultValuesDesc")."</span><br>\n";
206print "<br>\n";
207
208if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
209if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
210if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss);
211if ($defaulturl)      $param .= '&defaulturl='.urlencode($defaulturl);
212if ($defaultkey)      $param .= '&defaultkey='.urlencode($defaultkey);
213if ($defaultvalue)    $param .= '&defaultvalue='.urlencode($defaultvalue);
214
215
216print '<form action="'.$_SERVER["PHP_SELF"].((empty($user->entity) && $debug) ? '?debug=1' : '').'" method="POST">';
217if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
218print '<input type="hidden" name="token" value="'.newToken().'">';
219print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
220print '<input type="hidden" name="action" value="list">';
221print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
222print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
223print '<input type="hidden" name="page" value="'.$page.'">';
224
225$head = defaultvalues_prepare_head();
226
227print dol_get_fiche_head($head, $mode, '', -1, '');
228
229if ($mode == 'sortorder')
230{
231	print info_admin($langs->trans("WarningSettingSortOrder")).'<br>';
232}
233if ($mode == 'mandatory')
234{
235	print info_admin($langs->trans("FeatureSupportedOnTextFieldsOnly")).'<br>';
236}
237
238print '<input type="hidden" name="token" value="'.newToken().'">';
239print '<input type="hidden" id="action" name="action" value="">';
240print '<input type="hidden" id="mode" name="mode" value="'.dol_escape_htmltag($mode).'">';
241
242print '<div class="div-table-responsive-no-min">';
243print '<table class="noborder centpercent">';
244print '<tr class="liste_titre">';
245// Page
246$texthelp = $langs->trans("PageUrlForDefaultValues");
247if ($mode == 'createform') $texthelp .= $langs->trans("PageUrlForDefaultValuesCreate", 'societe/card.php', 'societe/card.php?abc=val1&def=val2');
248else $texthelp .= $langs->trans("PageUrlForDefaultValuesList", 'societe/list.php', 'societe/list.php?abc=val1&def=val2');
249$texthelp .= '<br><br>'.$langs->trans("AlsoDefaultValuesAreEffectiveForActionCreate");
250$texturl = $form->textwithpicto($langs->trans("RelativeURL"), $texthelp);
251print_liste_field_titre($texturl, $_SERVER["PHP_SELF"], 'page,param', '', $param, '', $sortfield, $sortorder);
252// Field
253$texthelp = $langs->trans("TheKeyIsTheNameOfHtmlField");
254if ($mode != 'sortorder')
255{
256	$textkey = $form->textwithpicto($langs->trans("Field"), $texthelp);
257} else {
258	$texthelp = 'field or alias.field';
259	$textkey = $form->textwithpicto($langs->trans("Field"), $texthelp);
260}
261print_liste_field_titre($textkey, $_SERVER["PHP_SELF"], 'param', '', $param, '', $sortfield, $sortorder);
262// Value
263if ($mode != 'focus' && $mode != 'mandatory')
264{
265	if ($mode != 'sortorder')
266	{
267		$substitutionarray = getCommonSubstitutionArray($langs, 2, array('object', 'objectamount')); // Must match list into GETPOST
268		unset($substitutionarray['__USER_SIGNATURE__']);
269		$texthelp = $langs->trans("FollowingConstantsWillBeSubstituted").'<br>';
270		foreach ($substitutionarray as $key => $val)
271		{
272			$texthelp .= $key.' -> '.$val.'<br>';
273		}
274		$textvalue = $form->textwithpicto($langs->trans("Value"), $texthelp, 1, 'help', '', 0, 2, 'subsitutiontooltip');
275	} else {
276		$texthelp = 'ASC or DESC';
277		$textvalue = $form->textwithpicto($langs->trans("SortOrder"), $texthelp);
278	}
279	print_liste_field_titre($textvalue, $_SERVER["PHP_SELF"], 'value', '', $param, '', $sortfield, $sortorder);
280}
281// Entity
282if (!empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,page', '', $param, '', $sortfield, $sortorder);
283else print_liste_field_titre("", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder);
284// Actions
285print_liste_field_titre("", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder);
286print "</tr>\n";
287
288
289// Line to add new record
290print "\n";
291
292print '<tr class="oddeven">';
293// Page
294print '<td>';
295print '<input type="text" class="flat minwidth200 maxwidthonsmartphone" name="defaulturl" value="'.dol_escape_htmltag(GETPOST('defaulturl', 'alphanohtml')).'">';
296print '</td>'."\n";
297// Field
298print '<td>';
299print '<input type="text" class="flat maxwidth100onsmartphone" name="defaultkey" value="'.dol_escape_htmltag(GETPOST('defaultkey', 'alphanohtml')).'">';
300print '</td>';
301// Value
302if ($mode != 'focus' && $mode != 'mandatory')
303{
304	print '<td>';
305	print '<input type="text" class="flat maxwidth100onsmartphone" name="defaultvalue" value="">';
306	print '</td>';
307}
308// Limit to superadmin
309if (!empty($conf->multicompany->enabled) && !$user->entity)
310{
311	print '<td>';
312	print '<input type="text" class="flat" size="1" disabled name="entity" value="'.$conf->entity.'">'; // We see environment, but to change it we must switch on other entity
313	print '</td>';
314} else {
315	print '<td class="center">';
316	print '<input type="hidden" name="entity" value="'.$conf->entity.'">';
317	print '</td>';
318}
319print '<td class="center">';
320$disabled = '';
321if (empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) $disabled = ' disabled="disabled"';
322print '<input type="submit" class="button"'.$disabled.' value="'.$langs->trans("Add").'" name="add">';
323print "</td>\n";
324print '</tr>';
325
326
327// Show constants
328$sql = "SELECT rowid, entity, type, page, param, value";
329$sql .= " FROM ".MAIN_DB_PREFIX."default_values";
330$sql .= " WHERE type = '".$db->escape($mode)."'";
331$sql .= " AND entity IN (".$user->entity.",".$conf->entity.")";
332$sql .= $db->order($sortfield, $sortorder);
333
334dol_syslog("translation::select from table", LOG_DEBUG);
335$result = $db->query($sql);
336if ($result)
337{
338	$num = $db->num_rows($result);
339	$i = 0;
340
341	while ($i < $num)
342	{
343		$obj = $db->fetch_object($result);
344
345		print "\n";
346
347		print '<tr class="oddeven">';
348
349		// Page
350		print '<td>';
351		if ($action != 'edit' || GETPOST('rowid', 'int') != $obj->rowid) print $obj->page;
352		else print '<input type="text" name="urlpage" value="'.dol_escape_htmltag($obj->page).'">';
353		print '</td>'."\n";
354
355		// Field
356		print '<td>';
357		if ($action != 'edit' || GETPOST('rowid') != $obj->rowid) print $obj->param;
358		else print '<input type="text" name="key" value="'.dol_escape_htmltag($obj->param).'">';
359		print '</td>'."\n";
360
361		// Value
362		if ($mode != 'focus' && $mode != 'mandatory')
363		{
364			print '<td>';
365			/*print '<input type="hidden" name="const['.$i.'][rowid]" value="'.$obj->rowid.'">';
366    		print '<input type="hidden" name="const['.$i.'][lang]" value="'.$obj->lang.'">';
367    		print '<input type="hidden" name="const['.$i.'][name]" value="'.$obj->transkey.'">';
368    		print '<input type="text" id="value_'.$i.'" class="flat inputforupdate" size="30" name="const['.$i.'][value]" value="'.dol_escape_htmltag($obj->transvalue).'">';
369    		*/
370			if ($action != 'edit' || GETPOST('rowid') != $obj->rowid) print dol_escape_htmltag($obj->value);
371			else print '<input type="text" name="value" value="'.dol_escape_htmltag($obj->value).'">';
372			print '</td>';
373		}
374
375		print '<td></td>';
376
377		// Actions
378		print '<td class="center">';
379		if ($action != 'edit' || GETPOST('rowid') != $obj->rowid)
380		{
381			print '<a class="editfielda marginleftonly marginrightonly" href="'.$_SERVER['PHP_SELF'].'?rowid='.$obj->rowid.'&entity='.$obj->entity.'&mode='.$mode.'&action=edit&token='.newToken().((empty($user->entity) && $debug) ? '&debug=1' : '').'">'.img_edit().'</a>';
382			print '<a class="marginleftonly marginrightonly" href="'.$_SERVER['PHP_SELF'].'?rowid='.$obj->rowid.'&entity='.$obj->entity.'&mode='.$mode.'&action=delete&token='.newToken().((empty($user->entity) && $debug) ? '&debug=1' : '').'">'.img_delete().'</a>';
383		} else {
384			print '<input type="hidden" name="page" value="'.$page.'">';
385			print '<input type="hidden" name="rowid" value="'.$id.'">';
386			print '<div name="'.(!empty($obj->rowid) ? $obj->rowid : 'none').'"></div>';
387			print '<input type="submit" class="button" name="actionmodify" value="'.$langs->trans("Modify").'">';
388			print '<input type="submit" class="button button-cancel" name="actioncancel" value="'.$langs->trans("Cancel").'">';
389		}
390		print '</td>';
391
392		print "</tr>\n";
393		print "\n";
394		$i++;
395	}
396} else {
397	dol_print_error($db);
398}
399
400print '</table>';
401print '</div>';
402
403print dol_get_fiche_end();
404
405print "</form>\n";
406
407// End of page
408llxFooter();
409$db->close();
410