1<?php
2/* Copyright (C) 2002-2005	Rodolphe Quiedeville	<rodolphe@quiedeville.org>
3 * Copyright (C) 2002-2003	Jean-Louis Bergamo		<jlb@j1b.org>
4 * Copyright (C) 2004-2020	Laurent Destailleur		<eldy@users.sourceforge.net>
5 * Copyright (C) 2004		Eric Seigne				<eric.seigne@ryxeo.com>
6 * Copyright (C) 2005-2017	Regis Houssin			<regis.houssin@inodbox.com>
7 * Copyright (C) 2012		Juanjo Menent			<jmenent@2byte.es>
8 * Copyright (C) 2020		Tobias Sekan			<tobias.sekan@startmail.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
24/**
25 *		\file		htdocs/user/perms.php
26 *		\brief		Page to set permission of a user record
27 */
28
29if (!defined('CSRFCHECK_WITH_TOKEN')) {
30	define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET
31}
32
33require '../main.inc.php';
34require_once DOL_DOCUMENT_ROOT.'/core/lib/usergroups.lib.php';
35require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
36require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
37
38// Load translation files required by page
39$langs->loadLangs(array('users', 'admin'));
40
41$id = GETPOST('id', 'int');
42$action = GETPOST('action', 'aZ09');
43$confirm = GETPOST('confirm', 'alpha');
44$module = GETPOST('module', 'alpha');
45$rights = GETPOST('rights', 'int');
46$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'userperms'; // To manage different context of search
47
48if (!isset($id) || empty($id)) {
49	accessforbidden();
50}
51
52// Define if user can read permissions
53$canreaduser = ($user->admin || $user->rights->user->user->lire);
54// Define if user can modify other users and permissions
55$caneditperms = ($user->admin || $user->rights->user->user->creer);
56// Advanced permissions
57if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) {
58	$canreaduser = ($user->admin || ($user->rights->user->user->lire && $user->rights->user->user_advance->readperms));
59	$caneditselfperms = ($user->id == $id && $user->rights->user->self_advance->writeperms);
60	$caneditperms = (($caneditperms || $caneditselfperms) ? 1 : 0);
61}
62
63// Security check
64$socid = 0;
65if (isset($user->socid) && $user->socid > 0) {
66	$socid = $user->socid;
67}
68$feature2 = (($socid && $user->rights->user->self->creer) ? '' : 'user');
69// A user can always read its own card if not advanced perms enabled, or if he has advanced perms, except for admin
70if ($user->id == $id && (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->user->self_advance->readperms) && empty($user->admin))) {
71	accessforbidden();
72}
73
74$result = restrictedArea($user, 'user', $id, 'user&user', $feature2);
75if ($user->id <> $id && !$canreaduser) {
76	accessforbidden();
77}
78
79$object = new User($db);
80$object->fetch($id, '', '', 1);
81$object->getrights();
82
83$entity = $conf->entity;
84
85// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
86$hookmanager->initHooks(array('usercard', 'userperms', 'globalcard'));
87
88
89/*
90 * Actions
91 */
92
93$parameters = array('socid'=>$socid);
94$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
95if ($reshook < 0) {
96	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
97}
98
99if (empty($reshook)) {
100	if ($action == 'addrights' && $caneditperms && $confirm == 'yes') {
101		$edituser = new User($db);
102		$edituser->fetch($object->id);
103		$result = $edituser->addrights($rights, $module, '', $entity);
104		if ($result < 0) {
105			setEventMessages($edituser->error, $edituser->errors, 'errors');
106		}
107
108		// If we are changing our own permissions, we reload permissions and menu
109		if ($object->id == $user->id) {
110			$user->clearrights();
111			$user->getrights();
112			$menumanager->loadMenu();
113		}
114
115		$object->clearrights();
116		$object->getrights();
117	}
118
119	if ($action == 'delrights' && $caneditperms && $confirm == 'yes') {
120		$edituser = new User($db);
121		$edituser->fetch($object->id);
122		$result = $edituser->delrights($rights, $module, '', $entity);
123		if ($result < 0) {
124			setEventMessages($edituser->error, $edituser->errors, 'errors');
125		}
126
127		// If we are changing our own permissions, we reload permissions and menu
128		if ($object->id == $user->id) {
129			$user->clearrights();
130			$user->getrights();
131			$menumanager->loadMenu();
132		}
133
134		$object->clearrights();
135		$object->getrights();
136	}
137}
138
139
140/*
141 *	View
142 */
143
144$form = new Form($db);
145
146llxHeader('', $langs->trans("Permissions"));
147
148$head = user_prepare_head($object);
149
150$title = $langs->trans("User");
151print dol_get_fiche_head($head, 'rights', $title, -1, 'user');
152
153
154$db->begin();
155
156// Search all modules with permission and reload permissions def.
157$modules = array();
158$modulesdir = dolGetModulesDirs();
159
160foreach ($modulesdir as $dir) {
161	$handle = @opendir(dol_osencode($dir));
162	if (is_resource($handle)) {
163		while (($file = readdir($handle)) !== false) {
164			if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') {
165				$modName = substr($file, 0, dol_strlen($file) - 10);
166
167				if ($modName) {
168					include_once $dir.$file;
169					$objMod = new $modName($db);
170
171					// Load all lang files of module
172					if (isset($objMod->langfiles) && is_array($objMod->langfiles)) {
173						foreach ($objMod->langfiles as $domain) {
174							$langs->load($domain);
175						}
176					}
177					// Load all permissions
178					if ($objMod->rights_class) {
179						$ret = $objMod->insert_permissions(0, $entity);
180						$modules[$objMod->rights_class] = $objMod;
181						//print "modules[".$objMod->rights_class."]=$objMod;";
182					}
183				}
184			}
185		}
186	}
187}
188
189$db->commit();
190
191// Read permissions of user
192$permsuser = array();
193
194$sql = "SELECT DISTINCT ur.fk_id";
195$sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur";
196$sql .= " WHERE ur.entity = ".((int) $entity);
197$sql .= " AND ur.fk_user = ".((int) $object->id);
198
199dol_syslog("get user perms", LOG_DEBUG);
200$result = $db->query($sql);
201if ($result) {
202	$num = $db->num_rows($result);
203	$i = 0;
204	while ($i < $num) {
205		$obj = $db->fetch_object($result);
206		array_push($permsuser, $obj->fk_id);
207		$i++;
208	}
209	$db->free($result);
210} else {
211	dol_print_error($db);
212}
213
214// Lecture des droits groupes
215$permsgroupbyentity = array();
216
217$sql = "SELECT DISTINCT gr.fk_id, gu.entity";
218$sql .= " FROM ".MAIN_DB_PREFIX."usergroup_rights as gr,";
219$sql .= " ".MAIN_DB_PREFIX."usergroup_user as gu";
220$sql .= " WHERE gr.entity = ".((int) $entity);
221$sql .= " AND gr.fk_usergroup = gu.fk_usergroup";
222$sql .= " AND gu.fk_user = ".((int) $object->id);
223
224dol_syslog("get user perms", LOG_DEBUG);
225$result = $db->query($sql);
226if ($result) {
227	$num = $db->num_rows($result);
228	$i = 0;
229	while ($i < $num) {
230		$obj = $db->fetch_object($result);
231		if (!isset($permsgroupbyentity[$obj->entity])) {
232			$permsgroupbyentity[$obj->entity] = array();
233		}
234		array_push($permsgroupbyentity[$obj->entity], $obj->fk_id);
235		$i++;
236	}
237	$db->free($result);
238} else {
239	dol_print_error($db);
240}
241
242
243/*
244 * Part to add/remove permissions
245 */
246
247$linkback = '';
248
249if ($user->rights->user->user->lire || $user->admin) {
250	$linkback = '<a href="'.DOL_URL_ROOT.'/user/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
251}
252
253dol_banner_tab($object, 'id', $linkback, $user->rights->user->user->lire || $user->admin);
254
255
256print '<div class="underbanner clearboth"></div>';
257
258if ($user->admin) {
259	print info_admin($langs->trans("WarningOnlyPermissionOfActivatedModules"));
260}
261// If edited user is an extern user, we show warning for external users
262if (! empty($object->socid)) {
263	print info_admin(showModulesExludedForExternal($modules))."\n";
264}
265
266$parameters = array('permsgroupbyentity'=>$permsgroupbyentity);
267$reshook = $hookmanager->executeHooks('insertExtraHeader', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
268if ($reshook < 0) {
269	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
270}
271
272
273print "\n";
274print '<div class="div-table-responsive-no-min">';
275print '<table class="noborder centpercent">';
276
277print '<tr class="liste_titre">';
278print '<td>'.$langs->trans("Module").'</td>';
279if (($caneditperms && empty($objMod->rights_admin_allowed)) || empty($object->admin)) {
280	if ($caneditperms) {
281		print '<td class="center nowrap">';
282		print '<a class="reposition commonlink" title="'.dol_escape_htmltag($langs->trans("All")).'" alt="'.dol_escape_htmltag($langs->trans("All")).'" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=addrights&amp;entity='.$entity.'&amp;module=allmodules&amp;confirm=yes&amp;token='.newToken().'">'.$langs->trans("All")."</a>";
283		print ' / ';
284		print '<a class="reposition commonlink" title="'.dol_escape_htmltag($langs->trans("None")).'" alt="'.dol_escape_htmltag($langs->trans("None")).'" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delrights&amp;entity='.$entity.'&amp;module=allmodules&amp;confirm=yes&amp;token='.newToken().'">'.$langs->trans("None")."</a>";
285		print '</td>';
286	}
287	print '<td class="center" width="24">&nbsp;</td>';
288}
289print '<td>'.$langs->trans("Permissions").'</td>';
290if ($user->admin) {
291	print '<td class="right"></td>';
292}
293print '</tr>'."\n";
294
295//print "xx".$conf->global->MAIN_USE_ADVANCED_PERMS;
296$sql = "SELECT r.id, r.libelle as label, r.module, r.perms, r.subperms, r.module_position, r.bydefault";
297$sql .= " FROM ".MAIN_DB_PREFIX."rights_def as r";
298$sql .= " WHERE r.libelle NOT LIKE 'tou%'"; // On ignore droits "tous"
299$sql .= " AND r.entity = ".((int) $entity);
300if (empty($conf->global->MAIN_USE_ADVANCED_PERMS)) {
301	$sql .= " AND r.perms NOT LIKE '%_advance'"; // Hide advanced perms if option is not enabled
302}
303$sql .= " ORDER BY r.family_position, r.module_position, r.module, r.id";
304
305$result = $db->query($sql);
306if ($result) {
307	$num = $db->num_rows($result);
308	$i = 0;
309	$oldmod = '';
310
311	while ($i < $num) {
312		$obj = $db->fetch_object($result);
313
314		// If line is for a module that does not exist anymore (absent of includes/module), we ignore it
315		if (empty($modules[$obj->module])) {
316			$i++;
317			continue;
318		}
319
320		$objMod = $modules[$obj->module];
321
322		// Save field module_position in database if value is wrong
323		if (empty($obj->module_position) || (is_object($objMod) && $objMod->isCoreOrExternalModule() == 'external' && $obj->module_position < 100000)) {
324			if (is_object($modules[$obj->module]) && ($modules[$obj->module]->module_position > 0)) {
325				// TODO Define familyposition
326				//$familyposition = $modules[$obj->module]->family_position;
327				$familyposition = 0;
328
329				$newmoduleposition = $modules[$obj->module]->module_position;
330
331				// Correct $newmoduleposition position for external modules
332				$objMod = $modules[$obj->module];
333				if (is_object($objMod) && $objMod->isCoreOrExternalModule() == 'external' && $newmoduleposition < 100000) {
334					$newmoduleposition += 100000;
335				}
336
337				$sqlupdate = 'UPDATE '.MAIN_DB_PREFIX."rights_def SET module_position = ".((int) $newmoduleposition).",";
338				$sqlupdate .= " family_position = ".((int) $familyposition);
339				$sqlupdate .= " WHERE module_position = ".((int) $obj->module_position)." AND module = '".$db->escape($obj->module)."'";
340
341				$db->query($sqlupdate);
342			}
343		}
344
345		// Break found, it's a new module to catch
346		if (isset($obj->module) && ($oldmod <> $obj->module)) {
347			$oldmod = $obj->module;
348
349			// Break detected, we get objMod
350			$objMod = $modules[$obj->module];
351			$picto = ($objMod->picto ? $objMod->picto : 'generic');
352
353			// Show break line
354			print '<tr class="oddeven trforbreak">';
355			print '<td class="maxwidthonsmartphone tdoverflowonsmartphone">';
356			print img_object('', $picto, 'class="pictoobjectwidth paddingright"').' '.$objMod->getName();
357			print '<a name="'.$objMod->getName().'"></a>';
358			print '</td>';
359			if (($caneditperms && empty($objMod->rights_admin_allowed)) || empty($object->admin)) {
360				if ($caneditperms) {
361					print '<td class="center nowrap">';
362					print '<a class="reposition" title="'.dol_escape_htmltag($langs->trans("All")).'" alt="'.dol_escape_htmltag($langs->trans("All")).'" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=addrights&amp;entity='.$entity.'&amp;module='.$obj->module.'&amp;confirm=yes&amp;token='.newToken().'">'.$langs->trans("All")."</a>";
363					print ' / ';
364					print '<a class="reposition" title="'.dol_escape_htmltag($langs->trans("None")).'" alt="'.dol_escape_htmltag($langs->trans("None")).'" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delrights&amp;entity='.$entity.'&amp;module='.$obj->module.'&amp;confirm=yes&amp;token='.newToken().'">'.$langs->trans("None")."</a>";
365					print '</td>';
366				}
367				print '<td>&nbsp;</td>';
368			} else {
369				if ($caneditperms) {
370					print '<td>&nbsp;</td>';
371				}
372				print '<td>&nbsp;</td>';
373			}
374			print '<td>&nbsp;</td>';
375
376			// Permission id
377			if ($user->admin) {
378				print '<td class="right"></td>';
379			}
380
381			print '</tr>'."\n";
382		}
383
384		print '<!-- '.$obj->module.'->'.$obj->perms.($obj->subperms ? '->'.$obj->subperms : '').' -->'."\n";
385		print '<tr class="oddeven">';
386
387		// Picto and label of module
388		print '<td class="maxwidthonsmartphone tdoverflowonsmartphone">';
389		//print img_object('', $picto, 'class="inline-block pictoobjectwidth"').' '.$objMod->getName();
390		print '</td>';
391
392		// Permission and tick
393		if (!empty($object->admin) && !empty($objMod->rights_admin_allowed)) {    // Permission granted because admin
394			if ($caneditperms) {
395				print '<td class="center">'.img_picto($langs->trans("Administrator"), 'star').'</td>';
396			}
397			print '<td class="center nowrap">';
398			print img_picto($langs->trans("Active"), 'tick');
399			print '</td>';
400		} elseif (in_array($obj->id, $permsuser)) {					// Permission granted by user
401			if ($caneditperms) {
402				print '<td class="center"><a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delrights&amp;entity='.$entity.'&amp;rights='.$obj->id.'&amp;confirm=yes&amp;token='.newToken().'">';
403				//print img_edit_remove($langs->trans("Remove"));
404				print img_picto($langs->trans("Remove"), 'switch_on');
405				print '</a></td>';
406			}
407			print '<td class="center nowrap">';
408			print img_picto($langs->trans("Active"), 'tick');
409			print '</td>';
410		} elseif (isset($permsgroupbyentity[$entity]) && is_array($permsgroupbyentity[$entity])) {
411			if (in_array($obj->id, $permsgroupbyentity[$entity])) {	// Permission granted by group
412				if ($caneditperms) {
413					print '<td class="center">';
414					print $form->textwithtooltip($langs->trans("Inherited"), $langs->trans("PermissionInheritedFromAGroup"));
415					print '</td>';
416				}
417				print '<td class="center nowrap">';
418				print img_picto($langs->trans("Active"), 'tick');
419				print '</td>';
420			} else {
421				// Do not own permission
422				if ($caneditperms) {
423					print '<td class="center"><a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=addrights&amp;entity='.$entity.'&amp;rights='.$obj->id.'&amp;confirm=yes&amp;token='.newToken().'">';
424					//print img_edit_add($langs->trans("Add"));
425					print img_picto($langs->trans("Add"), 'switch_off');
426					print '</a></td>';
427				}
428				print '<td>&nbsp;</td>';
429			}
430		} else {
431			// Do not own permission
432			if ($caneditperms) {
433				print '<td class="center"><a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=addrights&amp;entity='.$entity.'&amp;rights='.$obj->id.'&amp;confirm=yes&amp;token='.newToken().'">';
434				//print img_edit_add($langs->trans("Add"));
435				print img_picto($langs->trans("Add"), 'switch_off');
436				print '</a></td>';
437			}
438			print '<td>&nbsp;</td>';
439		}
440
441		// Description of permission
442		$permlabel = (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ($langs->trans("PermissionAdvanced".$obj->id) != ("PermissionAdvanced".$obj->id)) ? $langs->trans("PermissionAdvanced".$obj->id) : (($langs->trans("Permission".$obj->id) != ("Permission".$obj->id)) ? $langs->trans("Permission".$obj->id) : $langs->trans($obj->label)));
443		print '<td>';
444		print $permlabel;
445		if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS)) {
446			if (preg_match('/_advance$/', $obj->perms)) {
447				print ' <span class="opacitymedium">('.$langs->trans("AdvancedModeOnly").')</span>';
448			}
449		}
450		print '</td>';
451
452		// Permission id
453		if ($user->admin) {
454			print '<td class="right">';
455			$htmltext = $langs->trans("ID").': '.$obj->id;
456			$htmltext .= '<br>'.$langs->trans("Permission").': user->rights->'.$obj->module.'->'.$obj->perms.($obj->subperms ? '->'.$obj->subperms : '');
457			print $form->textwithpicto('', $htmltext);
458			//print '<span class="opacitymedium">'.$obj->id.'</span>';
459			print '</td>';
460		}
461
462		print '</tr>'."\n";
463
464		$i++;
465	}
466} else {
467	dol_print_error($db);
468}
469print '</table>';
470print '</div>';
471
472$parameters = array();
473$reshook = $hookmanager->executeHooks('insertExtraFooter', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
474if ($reshook < 0) {
475	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
476}
477
478
479print dol_get_fiche_end();
480
481// End of page
482llxFooter();
483$db->close();
484