summaryrefslogtreecommitdiffstats
path: root/modules-available/permissionmanager/page.inc.php
blob: 462d3163a622c37d0c9621406b15366a71b369ac (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
<?php

class Page_PermissionManager extends Page
{

	/**
	 * Called before any page rendering happens - early hook to check parameters etc.
	 */
	protected function doPreprocess()
	{
		User::load();

		if (!User::isLoggedIn()) {
			Message::addError('main.no-permission');
			Util::redirect('?do=Main'); // does not return
		}

		$action = Request::any('action', 'show', 'string');
		if ($action === 'addRoleToUser') {
			User::assertPermission('users.edit-roles');
			$users = Request::post('users', '');
			$roles = Request::post('roles', '');
			PermissionDbUpdate::addRoleToUser($users, $roles);
		} elseif ($action === 'removeRoleFromUser') {
			User::assertPermission('users.edit-roles');
			$users = Request::post('users', '');
			$roles = Request::post('roles', '');
			PermissionDbUpdate::removeRoleFromUser($users, $roles);
		} elseif ($action === 'deleteRole') {
			User::assertPermission('roles.edit');
			$id = Request::post('deleteId', false, 'int');
			PermissionDbUpdate::deleteRole($id);
		} elseif ($action === 'saveRole') {
			User::assertPermission('roles.edit');
			$roleID = Request::post("roleid", false, 'int');
			if ($roleID === false) {
				Message::addError('main.parameter-missing', 'roleid');
				Util::redirect('?do=permissionmanager');
			}
			$roleName = Request::post("rolename", '', 'string');
			if (empty($roleName)) {
				Message::addError('main.parameter-empty', 'rolename');
				Util::redirect('?do=permissionmanager');
			}
			$roleDescription = Request::post('roledescription', '', 'string');
			$locations = self::processLocations(Request::post("locations", [], 'array'));
			$permissions = self::processPermissions(Request::post("permissions"));
			PermissionDbUpdate::saveRole($roleName, $roleDescription, $locations, $permissions, $roleID);
		}
		if (Request::isPost()) {
			Util::redirect('?do=permissionmanager&show=' . Request::get("show", "roles"));
		}
	}

	/**
	 * Menu etc. has already been generated, now it's time to generate page content.
	 */
	protected function doRender()
	{
		$show = Request::get("show", false, 'string');

		// "Public" page -- nice "permission denied" message
		if ($show === 'denied') {
			Render::addTemplate('page-permission-denied', [
				'name' => User::getName(),
				'permission' => Request::get('permission', false, 'string'),
			]);
			return;
		}

		if ($show === false) {
			foreach (['roles', 'users', 'locations'] as $show) {
				if (User::hasPermission($show . '.*'))
					break;
			}
		}

		// switch between tables, but always show menu to switch tables
		// get menu button colors
		$data = array();
		if ($show === "roleEditor") {
			$data['groupClass'] = 'btn-group-muted';
			$data['rolesButtonClass'] = 'active';
		} else {
			$data[$show . 'ButtonClass'] = 'active';
		}
		Permission::addGlobalTags($data['perms'], null, ['roles.*', 'users.*', 'locations.*']);

		Render::addtemplate('header-menu', $data);

		if ($show === "roles") {
			User::assertPermission('roles.*');
			$data = array("roles" => GetPermissionData::getRoles(GetPermissionData::WITH_USER_COUNT));
			Permission::addGlobalTags($data['perms'], null, ['roles.edit']);
			Render::addTemplate('rolestable', $data);
		} elseif ($show === "users") {
			User::assertPermission('users.*');
			$data = array("user" => GetPermissionData::getUserData());
			if (User::hasPermission('users.edit-roles')) {
				$data['allroles'] = GetPermissionData::getRoles();
			}
			Permission::addGlobalTags($data['perms'], null, ['users.edit-roles']);
			Render::addTemplate('role-filter-selectize', $data);
			Render::addTemplate('userstable', $data);
		} elseif ($show === "locations") {
			User::assertPermission('locations.*');
			$data = array("location" => GetPermissionData::getLocationData(), "allroles" => GetPermissionData::getRoles());
			Render::addTemplate('role-filter-selectize', $data);
			Render::addTemplate('locationstable', $data);
		} elseif ($show === "roleEditor") {
			User::assertPermission('roles.*');
			$data = array("cancelShow" => Request::get("cancel", "roles", 'string'));
			Permission::addGlobalTags($data['perms'], null, ['roles.edit']);

			$selectedPermissions = array();
			$selectedLocations = array();
			$roleid = Request::get("roleid", false, 'int');
			if ($roleid !== false) {
				$data += GetPermissionData::getRoleData($roleid);
				$selectedPermissions = $data["permissions"];
				$selectedLocations = $data["locations"];
			}

			$data["permissionHTML"] = self::generatePermissionHTML(PermissionUtil::getPermissions(), $selectedPermissions,
				false, '', ['perms' => $data['perms']]);
			$data["locationHTML"] = self::generateLocationHTML(Location::getTree(), $selectedLocations,
				$roleid === false, true, ['perms' => $data['perms']]);

			Render::addTemplate('roleeditor', $data);
		}
	}

	/**
	 * Recursively generate HTML code for the permission selection tree.
	 *
	 * @param array $permissions the permission tree
	 * @param array $selectedPermissions permissions that should be preselected
	 * @param bool $selectAll true if all permissions should be preselected, false if only those in $selectedPermissions
	 * @param string $permString the prefix permission string with which all permissions in the permission tree should start
	 * @return string generated html code
	 */
	private static function generatePermissionHTML($permissions, $selectedPermissions = array(), $selectAll = false, $permString = "", $tags = [])
	{
		$res = "";
		$toplevel = $permString == "";
		if ($toplevel && in_array("*", $selectedPermissions)) {
			$selectAll = true;
		}
		foreach ($permissions as $k => $v) {
			$selected = $selectAll;
			$nextPermString = $permString ? $permString . "." . $k : $k;
			if ($toplevel) {
				$displayName = Module::get($k)->getDisplayName();
			} else {
				$displayName = $k;
			}
			do {
				$leaf = isset($v['isLeaf']) && $v['isLeaf'];
				$id = $leaf ? $nextPermString : $nextPermString . ".*";
				$selected = $selected || in_array($id, $selectedPermissions);
				if ($leaf || count($v) !== 1)
					break;
				reset($v);
				$k = key($v);
				$v = $v[$k];
				$nextPermString .= '.' . $k;
				$displayName .= '.' . $k;
			} while (true);
			$data = array(
				"id" => $id,
				"name" => $displayName,
				"toplevel" => $toplevel,
				"checkboxname" => "permissions",
				"selected" => $selected,
				"HTML" => $leaf ? "" : self::generatePermissionHTML($v, $selectedPermissions, $selected, $nextPermString, $tags),
			);
			if ($leaf) {
				$data += $v;
			}
			$res .= Render::parse("treenode", $data + $tags);
		}
		if ($toplevel) {
			$res = Render::parse("treepanel",
				array("id" => "*",
					"name" => Dictionary::translateFile("template-tags", "lang_permissions"),
					"checkboxname" => "permissions",
					"selected" => $selectAll,
					"HTML" => $res) + $tags);
		}
		return $res;
	}

	/**
	 * Recursively generate HTML code for the location selection tree.
	 *
	 * @param array $locations the location tree
	 * @param array $selectedLocations locations that should be preselected
	 * @param array $selectAll true if all locations should be preselected, false if only those in $selectedLocations
	 * @param array $toplevel true if the location tree are the children of the root location, false if not
	 * @return string generated html code
	 */
	private static function generateLocationHTML($locations, $selectedLocations = array(), $selectAll = false, $toplevel = true, $tags = [])
	{
		$res = "";
		if ($toplevel && in_array(0, $selectedLocations)) {
			$selectAll = true;
		}
		foreach ($locations as $location) {
			$selected = $selectAll || in_array($location["locationid"], $selectedLocations);
			$res .= Render::parse("treenode",
				array("id" => $location["locationid"],
					"name" => $location["locationname"],
					"toplevel" => $toplevel,
					"checkboxname" => "locations",
					"selected" => $selected,
					"HTML" => array_key_exists("children", $location) ?
						self::generateLocationHTML($location["children"], $selectedLocations, $selected, false, $tags) : "")
				+ $tags);
		}
		if ($toplevel) {
			$res = Render::parse("treepanel",
				array("id" => 0,
					"name" => Dictionary::translateFile("template-tags", "lang_locations"),
					"checkboxname" => "locations",
					"selected" => $selectAll,
					"HTML" => $res) + $tags);
		}
		return $res;
	}

	/**
	 * Remove locations that are already covered by parent locations from the array.
	 *
	 * @param array $locations the locationid array
	 * @return array the locationid array without redundant locationids
	 */
	private static function processLocations($locations)
	{
		if (in_array(0, $locations))
			return array(null);
		$result = array();
		foreach ($locations as $location) {
			$rootchain = array_reverse(Location::getLocationRootChain($location));
			foreach ($rootchain as $l) {
				if (in_array($l, $result))
					break;
				if (in_array($l, $locations)) {
					$result[] = $l;
					break;
				}
			}
		}
		return $result;
	}

	/**
	 * Remove permissions that are already covered by parent permissions from the array.
	 *
	 * @param array $permissions the permissionid array
	 * @return array the permissionid array without redundant permissionids
	 */
	private static function processPermissions($permissions)
	{
		if (in_array("*", $permissions))
			return array("*");
		$result = array();
		foreach ($permissions as $permission) {
			$x =& $result;
			foreach (explode(".", $permission) as $p) {
				$x =& $x[$p];
			}
		}
		return self::extractPermissions($result);
	}

	/**
	 * Convert a multidimensional array of permissions to a flat array of permissions.
	 *
	 * @param array $permissions multidimensional array of permissionids
	 * @return array flat array of permissionids
	 */
	private static function extractPermissions($permissions)
	{
		$result = array();
		foreach ($permissions as $permission => $a) {
			if (is_array($a)) {
				if (array_key_exists("*", $a)) {
					$result[] = $permission . ".*";
				} else {
					foreach (self::extractPermissions($a) as $subPermission) {
						$result[] = $permission . "." . $subPermission;
					}
				}
			} else {
				$result[] = $permission;
			}
		}
		return $result;
	}

}