ModifyMembergroup()   F
last analyzed

Complexity

Conditions 38
Paths > 20000

Size

Total Lines 155
Code Lines 77

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 38
eloc 77
c 0
b 0
f 0
nop 0
dl 0
loc 155
rs 0
nc 1302528

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * ManagePermissions handles all possible permission stuff.
5
 *
6
 * Simple Machines Forum (SMF)
7
 *
8
 * @package SMF
9
 * @author Simple Machines https://www.simplemachines.org
10
 * @copyright 2022 Simple Machines and individual contributors
11
 * @license https://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1.2
14
 */
15
16
if (!defined('SMF'))
17
	die('No direct access...');
18
19
/**
20
 * Dispatches to the right function based on the given subaction.
21
 * Checks the permissions, based on the sub-action.
22
 * Called by ?action=managepermissions.
23
 *
24
 * Uses ManagePermissions language file.
25
 */
26
27
function ModifyPermissions()
28
{
29
	global $txt, $context;
30
31
	loadLanguage('ManagePermissions+ManageMembers');
32
	loadTemplate('ManagePermissions');
33
34
	// Format: 'sub-action' => array('function_to_call', 'permission_needed'),
35
	$subActions = array(
36
		'board' => array('PermissionByBoard', 'manage_permissions'),
37
		'index' => array('PermissionIndex', 'manage_permissions'),
38
		'modify' => array('ModifyMembergroup', 'manage_permissions'),
39
		'modify2' => array('ModifyMembergroup2', 'manage_permissions'),
40
		'quick' => array('SetQuickGroups', 'manage_permissions'),
41
		'quickboard' => array('SetQuickBoards', 'manage_permissions'),
42
		'postmod' => array('ModifyPostModeration', 'manage_permissions'),
43
		'profiles' => array('EditPermissionProfiles', 'manage_permissions'),
44
		'settings' => array('GeneralPermissionSettings', 'admin_forum'),
45
	);
46
47
	$_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) && empty($subActions[$_REQUEST['sa']]['disabled']) ? $_REQUEST['sa'] : (allowedTo('manage_permissions') ? 'index' : 'settings');
48
	isAllowedTo($subActions[$_REQUEST['sa']][1]);
49
50
	// Create the tabs for the template.
51
	$context[$context['admin_menu_name']]['tab_data'] = array(
52
		'title' => $txt['permissions_title'],
53
		'help' => 'permissions',
54
		'description' => '',
55
		'tabs' => array(
56
			'index' => array(
57
				'description' => $txt['permissions_groups'],
58
			),
59
			'board' => array(
60
				'description' => $txt['permission_by_board_desc'],
61
			),
62
			'profiles' => array(
63
				'description' => $txt['permissions_profiles_desc'],
64
			),
65
			'postmod' => array(
66
				'description' => $txt['permissions_post_moderation_desc'],
67
			),
68
			'settings' => array(
69
				'description' => $txt['permission_settings_desc'],
70
			),
71
		),
72
	);
73
74
	call_integration_hook('integrate_manage_permissions', array(&$subActions));
75
76
	call_helper($subActions[$_REQUEST['sa']][0]);
77
}
78
79
/**
80
 * Sets up the permissions by membergroup index page.
81
 * Called by ?action=managepermissions
82
 * Creates an array of all the groups with the number of members and permissions.
83
 *
84
 * Uses ManagePermissions language file.
85
 * Uses ManagePermissions template file.
86
 * @uses template_permission_index()
87
 */
88
function PermissionIndex()
89
{
90
	global $txt, $scripturl, $context, $settings, $modSettings, $smcFunc;
91
92
	$context['page_title'] = $txt['permissions_title'];
93
94
	// Load all the permissions. We'll need them in the template.
95
	loadAllPermissions();
96
97
	// Also load profiles, we may want to reset.
98
	loadPermissionProfiles();
99
100
	// Are we going to show the advanced options?
101
	$context['show_advanced_options'] = empty($context['admin_preferences']['app']);
102
103
	// Determine the number of ungrouped members.
104
	$request = $smcFunc['db_query']('', '
105
		SELECT COUNT(*)
106
		FROM {db_prefix}members
107
		WHERE id_group = {int:regular_group}',
108
		array(
109
			'regular_group' => 0,
110
		)
111
	);
112
	list ($num_members) = $smcFunc['db_fetch_row']($request);
113
	$smcFunc['db_free_result']($request);
114
115
	// Fill the context variable with 'Guests' and 'Regular Members'.
116
	$context['groups'] = array(
117
		-1 => array(
118
			'id' => -1,
119
			'name' => $txt['membergroups_guests'],
120
			'num_members' => $txt['membergroups_guests_na'],
121
			'allow_delete' => false,
122
			'allow_modify' => true,
123
			'can_search' => false,
124
			'href' => '',
125
			'link' => '',
126
			'help' => 'membergroup_guests',
127
			'is_post_group' => false,
128
			'color' => '',
129
			'icons' => '',
130
			'children' => array(),
131
			'num_permissions' => array(
132
				'allowed' => 0,
133
				// Can't deny guest permissions!
134
				'denied' => '(' . $txt['permissions_none'] . ')'
135
			),
136
			'access' => false
137
		),
138
		0 => array(
139
			'id' => 0,
140
			'name' => $txt['membergroups_members'],
141
			'num_members' => $num_members,
142
			'allow_delete' => false,
143
			'allow_modify' => true,
144
			'can_search' => false,
145
			'href' => $scripturl . '?action=moderate;area=viewgroups;sa=members;group=0',
146
			'help' => 'membergroup_regular_members',
147
			'is_post_group' => false,
148
			'color' => '',
149
			'icons' => '',
150
			'children' => array(),
151
			'num_permissions' => array(
152
				'allowed' => 0,
153
				'denied' => 0
154
			),
155
			'access' => false
156
		),
157
	);
158
159
	$postGroups = array();
160
	$normalGroups = array();
161
162
	// Query the database defined membergroups.
163
	$query = $smcFunc['db_query']('', '
164
		SELECT id_group, id_parent, group_name, min_posts, online_color, icons
165
		FROM {db_prefix}membergroups' . (empty($modSettings['permission_enable_postgroups']) ? '
166
		WHERE min_posts = {int:min_posts}' : '') . '
167
		ORDER BY id_parent = {int:not_inherited} DESC, min_posts, CASE WHEN id_group < {int:newbie_group} THEN id_group ELSE 4 END, group_name',
168
		array(
169
			'min_posts' => -1,
170
			'not_inherited' => -2,
171
			'newbie_group' => 4,
172
		)
173
	);
174
	while ($row = $smcFunc['db_fetch_assoc']($query))
175
	{
176
		// If it's inherited, just add it as a child.
177
		if ($row['id_parent'] != -2)
178
		{
179
			if (isset($context['groups'][$row['id_parent']]))
180
				$context['groups'][$row['id_parent']]['children'][$row['id_group']] = $row['group_name'];
181
			continue;
182
		}
183
184
		$row['icons'] = explode('#', $row['icons']);
185
		$context['groups'][$row['id_group']] = array(
186
			'id' => $row['id_group'],
187
			'name' => $row['group_name'],
188
			'num_members' => $row['id_group'] != 3 ? 0 : $txt['membergroups_guests_na'],
189
			'allow_delete' => $row['id_group'] > 4,
190
			'allow_modify' => $row['id_group'] > 1,
191
			'can_search' => $row['id_group'] != 3,
192
			'href' => $scripturl . '?action=moderate;area=viewgroups;sa=members;group=' . $row['id_group'],
193
			'help' => $row['id_group'] == 1 ? 'membergroup_administrator' : ($row['id_group'] == 3 ? 'membergroup_moderator' : ''),
194
			'is_post_group' => $row['min_posts'] != -1,
195
			'color' => empty($row['online_color']) ? '' : $row['online_color'],
196
			'icons' => !empty($row['icons'][0]) && !empty($row['icons'][1]) ? str_repeat('<img src="' . $settings['images_url'] . '/' . $row['icons'][1] . '" alt="*">', $row['icons'][0]) : '',
197
			'children' => array(),
198
			'num_permissions' => array(
199
				'allowed' => $row['id_group'] == 1 ? '(' . $txt['permissions_all'] . ')' : 0,
200
				'denied' => $row['id_group'] == 1 ? '(' . $txt['permissions_none'] . ')' : 0
201
			),
202
			'access' => false,
203
		);
204
205
		if ($row['min_posts'] == -1)
206
			$normalGroups[$row['id_group']] = $row['id_group'];
207
		else
208
			$postGroups[$row['id_group']] = $row['id_group'];
209
	}
210
	$smcFunc['db_free_result']($query);
211
212
	// Get the number of members in this post group.
213
	if (!empty($postGroups))
214
	{
215
		$query = $smcFunc['db_query']('', '
216
			SELECT id_post_group AS id_group, COUNT(*) AS num_members
217
			FROM {db_prefix}members
218
			WHERE id_post_group IN ({array_int:post_group_list})
219
			GROUP BY id_post_group',
220
			array(
221
				'post_group_list' => $postGroups,
222
			)
223
		);
224
		while ($row = $smcFunc['db_fetch_assoc']($query))
225
			$context['groups'][$row['id_group']]['num_members'] += $row['num_members'];
226
		$smcFunc['db_free_result']($query);
227
	}
228
229
	if (!empty($normalGroups))
230
	{
231
		// First, the easy one!
232
		$query = $smcFunc['db_query']('', '
233
			SELECT id_group, COUNT(*) AS num_members
234
			FROM {db_prefix}members
235
			WHERE id_group IN ({array_int:normal_group_list})
236
			GROUP BY id_group',
237
			array(
238
				'normal_group_list' => $normalGroups,
239
			)
240
		);
241
		while ($row = $smcFunc['db_fetch_assoc']($query))
242
			$context['groups'][$row['id_group']]['num_members'] += $row['num_members'];
243
		$smcFunc['db_free_result']($query);
244
245
		// This one is slower, but it's okay... careful not to count twice!
246
		$query = $smcFunc['db_query']('', '
247
			SELECT mg.id_group, COUNT(*) AS num_members
248
			FROM {db_prefix}membergroups AS mg
249
				INNER JOIN {db_prefix}members AS mem ON (mem.additional_groups != {string:blank_string}
250
					AND mem.id_group != mg.id_group
251
					AND FIND_IN_SET(mg.id_group, mem.additional_groups) != 0)
252
			WHERE mg.id_group IN ({array_int:normal_group_list})
253
			GROUP BY mg.id_group',
254
			array(
255
				'normal_group_list' => $normalGroups,
256
				'blank_string' => '',
257
			)
258
		);
259
		while ($row = $smcFunc['db_fetch_assoc']($query))
260
			$context['groups'][$row['id_group']]['num_members'] += $row['num_members'];
261
		$smcFunc['db_free_result']($query);
262
	}
263
264
	foreach ($context['groups'] as $id => $data)
265
	{
266
		if ($data['href'] != '')
267
			$context['groups'][$id]['link'] = '<a href="' . $data['href'] . '">' . $data['num_members'] . '</a>';
268
	}
269
270
	if (empty($_REQUEST['pid']))
271
	{
272
		$request = $smcFunc['db_query']('', '
273
			SELECT id_group, COUNT(*) AS num_permissions, add_deny
274
			FROM {db_prefix}permissions
275
			' . (empty($context['hidden_permissions']) ? '' : ' WHERE permission NOT IN ({array_string:hidden_permissions})') . '
276
			GROUP BY id_group, add_deny',
277
			array(
278
				'hidden_permissions' => !empty($context['hidden_permissions']) ? $context['hidden_permissions'] : array(),
279
			)
280
		);
281
		while ($row = $smcFunc['db_fetch_assoc']($request))
282
			if (isset($context['groups'][(int) $row['id_group']]) && (!empty($row['add_deny']) || $row['id_group'] != -1))
283
				$context['groups'][(int) $row['id_group']]['num_permissions'][empty($row['add_deny']) ? 'denied' : 'allowed'] = $row['num_permissions'];
284
		$smcFunc['db_free_result']($request);
285
286
		// Get the "default" profile permissions too.
287
		$request = $smcFunc['db_query']('', '
288
			SELECT id_profile, id_group, COUNT(*) AS num_permissions, add_deny
289
			FROM {db_prefix}board_permissions
290
			WHERE id_profile = {int:default_profile}
291
			' . (empty($context['hidden_permissions']) ? '' : ' AND permission NOT IN ({array_string:hidden_permissions})') . '
292
			GROUP BY id_profile, id_group, add_deny',
293
			array(
294
				'default_profile' => 1,
295
				'hidden_permissions' => !empty($context['hidden_permissions']) ? $context['hidden_permissions'] : array(),
296
			)
297
		);
298
		while ($row = $smcFunc['db_fetch_assoc']($request))
299
		{
300
			if (isset($context['groups'][(int) $row['id_group']]) && (!empty($row['add_deny']) || $row['id_group'] != -1))
301
				$context['groups'][(int) $row['id_group']]['num_permissions'][empty($row['add_deny']) ? 'denied' : 'allowed'] += $row['num_permissions'];
302
		}
303
		$smcFunc['db_free_result']($request);
304
	}
305
	else
306
	{
307
		$_REQUEST['pid'] = (int) $_REQUEST['pid'];
308
309
		if (!isset($context['profiles'][$_REQUEST['pid']]))
310
			fatal_lang_error('no_access', false);
311
312
		// Change the selected tab to better reflect that this really is a board profile.
313
		$context[$context['admin_menu_name']]['current_subsection'] = 'profiles';
314
315
		$request = $smcFunc['db_query']('', '
316
			SELECT id_profile, id_group, COUNT(*) AS num_permissions, add_deny
317
			FROM {db_prefix}board_permissions
318
			WHERE id_profile = {int:current_profile}
319
			GROUP BY id_profile, id_group, add_deny',
320
			array(
321
				'current_profile' => $_REQUEST['pid'],
322
			)
323
		);
324
		while ($row = $smcFunc['db_fetch_assoc']($request))
325
		{
326
			if (isset($context['groups'][(int) $row['id_group']]) && (!empty($row['add_deny']) || $row['id_group'] != -1))
327
				$context['groups'][(int) $row['id_group']]['num_permissions'][empty($row['add_deny']) ? 'denied' : 'allowed'] += $row['num_permissions'];
328
		}
329
		$smcFunc['db_free_result']($request);
330
331
		$context['profile'] = array(
332
			'id' => $_REQUEST['pid'],
333
			'name' => $context['profiles'][$_REQUEST['pid']]['name'],
334
		);
335
	}
336
337
	// We can modify any permission set apart from the read only, reply only and no polls ones as they are redefined.
338
	$context['can_modify'] = empty($_REQUEST['pid']) || $_REQUEST['pid'] == 1 || $_REQUEST['pid'] > 4;
339
340
	// Load the proper template.
341
	$context['sub_template'] = 'permission_index';
342
	createToken('admin-mpq');
343
}
344
345
/**
346
 * Handle permissions by board... more or less. :P
347
 */
348
function PermissionByBoard()
349
{
350
	global $context, $txt, $smcFunc, $sourcedir, $cat_tree, $boardList, $boards;
351
352
	$context['page_title'] = $txt['permissions_boards'];
353
	$context['edit_all'] = isset($_GET['edit']);
354
355
	// Saving?
356
	if (!empty($_POST['save_changes']) && !empty($_POST['boardprofile']))
357
	{
358
		checkSession('request');
359
		validateToken('admin-mpb');
360
361
		$changes = array();
362
		foreach ($_POST['boardprofile'] as $pBoard => $profile)
363
		{
364
			$changes[(int) $profile][] = (int) $pBoard;
365
		}
366
367
		if (!empty($changes))
368
		{
369
			foreach ($changes as $profile => $boards)
370
				$smcFunc['db_query']('', '
371
					UPDATE {db_prefix}boards
372
					SET id_profile = {int:current_profile}
373
					WHERE id_board IN ({array_int:board_list})',
374
					array(
375
						'board_list' => $boards,
376
						'current_profile' => $profile,
377
					)
378
				);
379
		}
380
381
		$context['edit_all'] = false;
382
	}
383
384
	// Load all permission profiles.
385
	loadPermissionProfiles();
386
387
	// Get the board tree.
388
	require_once($sourcedir . '/Subs-Boards.php');
389
390
	getBoardTree();
391
392
	// Build the list of the boards.
393
	$context['categories'] = array();
394
	foreach ($cat_tree as $catid => $tree)
395
	{
396
		$context['categories'][$catid] = array(
397
			'name' => &$tree['node']['name'],
398
			'id' => &$tree['node']['id'],
399
			'boards' => array()
400
		);
401
		foreach ($boardList[$catid] as $boardid)
402
		{
403
			if (!isset($context['profiles'][$boards[$boardid]['profile']]))
404
				$boards[$boardid]['profile'] = 1;
405
406
			$context['categories'][$catid]['boards'][$boardid] = array(
407
				'id' => &$boards[$boardid]['id'],
408
				'name' => &$boards[$boardid]['name'],
409
				'description' => &$boards[$boardid]['description'],
410
				'child_level' => &$boards[$boardid]['level'],
411
				'profile' => &$boards[$boardid]['profile'],
412
				'profile_name' => $context['profiles'][$boards[$boardid]['profile']]['name'],
413
			);
414
		}
415
	}
416
417
	$context['sub_template'] = 'by_board';
418
	createToken('admin-mpb');
419
}
420
421
/**
422
 * Handles permission modification actions from the upper part of the
423
 * permission manager index.
424
 */
425
function SetQuickGroups()
426
{
427
	global $context, $smcFunc;
428
429
	checkSession();
430
	validateToken('admin-mpq', 'quick');
431
432
	loadIllegalPermissions();
433
	loadIllegalGuestPermissions();
434
	loadIllegalBBCHtmlGroups();
435
436
	// Make sure only one of the quick options was selected.
437
	if ((!empty($_POST['predefined']) && ((isset($_POST['copy_from']) && $_POST['copy_from'] != 'empty') || !empty($_POST['permissions']))) || (!empty($_POST['copy_from']) && $_POST['copy_from'] != 'empty' && !empty($_POST['permissions'])))
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (! empty($_POST['predefi...($_POST['permissions']), Probably Intended Meaning: ! empty($_POST['predefin...$_POST['permissions']))
Loading history...
438
		fatal_lang_error('permissions_only_one_option', false);
439
440
	if (empty($_POST['group']) || !is_array($_POST['group']))
441
		$_POST['group'] = array();
442
443
	// Only accept numeric values for selected membergroups.
444
	foreach ($_POST['group'] as $id => $group_id)
445
		$_POST['group'][$id] = (int) $group_id;
446
	$_POST['group'] = array_unique($_POST['group']);
447
448
	if (empty($_REQUEST['pid']))
449
		$_REQUEST['pid'] = 0;
450
	else
451
		$_REQUEST['pid'] = (int) $_REQUEST['pid'];
452
453
	// Fix up the old global to the new default!
454
	$bid = max(1, $_REQUEST['pid']);
455
456
	// No modifying the predefined profiles.
457
	if ($_REQUEST['pid'] > 1 && $_REQUEST['pid'] < 5)
458
		fatal_lang_error('no_access', false);
459
460
	// Clear out any cached authority.
461
	updateSettings(array('settings_updated' => time()));
462
463
	// No groups were selected.
464
	if (empty($_POST['group']))
465
		redirectexit('action=admin;area=permissions;pid=' . $_REQUEST['pid']);
466
467
	// Set a predefined permission profile.
468
	if (!empty($_POST['predefined']))
469
	{
470
		// Make sure it's a predefined permission set we expect.
471
		if (!in_array($_POST['predefined'], array('restrict', 'standard', 'moderator', 'maintenance')))
472
			redirectexit('action=admin;area=permissions;pid=' . $_REQUEST['pid']);
473
474
		foreach ($_POST['group'] as $group_id)
475
		{
476
			if (!empty($_REQUEST['pid']))
477
				setPermissionLevel($_POST['predefined'], $group_id, $_REQUEST['pid']);
478
			else
479
				setPermissionLevel($_POST['predefined'], $group_id);
480
		}
481
	}
482
	// Set a permission profile based on the permissions of a selected group.
483
	elseif ($_POST['copy_from'] != 'empty')
484
	{
485
		// Just checking the input.
486
		if (!is_numeric($_POST['copy_from']))
487
			redirectexit('action=admin;area=permissions;pid=' . $_REQUEST['pid']);
488
489
		// Make sure the group we're copying to is never included.
490
		$_POST['group'] = array_diff($_POST['group'], array($_POST['copy_from']));
491
492
		// No groups left? Too bad.
493
		if (empty($_POST['group']))
494
			redirectexit('action=admin;area=permissions;pid=' . $_REQUEST['pid']);
495
496
		if (empty($_REQUEST['pid']))
497
		{
498
			// Retrieve current permissions of group.
499
			$request = $smcFunc['db_query']('', '
500
				SELECT permission, add_deny
501
				FROM {db_prefix}permissions
502
				WHERE id_group = {int:copy_from}',
503
				array(
504
					'copy_from' => $_POST['copy_from'],
505
				)
506
			);
507
			$target_perm = array();
508
			while ($row = $smcFunc['db_fetch_assoc']($request))
509
				$target_perm[$row['permission']] = $row['add_deny'];
510
			$smcFunc['db_free_result']($request);
511
512
			$inserts = array();
513
			foreach ($_POST['group'] as $group_id)
514
				foreach ($target_perm as $perm => $add_deny)
515
				{
516
					// No dodgy permissions please!
517
					if (!empty($context['illegal_permissions']) && in_array($perm, $context['illegal_permissions']))
518
						continue;
519
					if (isset($context['permissions_excluded'][$perm]) && in_array($group_id, $context['permissions_excluded'][$perm]))
520
						continue;
521
522
					if ($group_id != 1 && $group_id != 3)
523
						$inserts[] = array($perm, $group_id, $add_deny);
524
				}
525
526
			// Delete the previous permissions...
527
			$smcFunc['db_query']('', '
528
				DELETE FROM {db_prefix}permissions
529
				WHERE id_group IN ({array_int:group_list})
530
					' . (empty($context['illegal_permissions']) ? '' : ' AND permission NOT IN ({array_string:illegal_permissions})'),
531
				array(
532
					'group_list' => $_POST['group'],
533
					'illegal_permissions' => !empty($context['illegal_permissions']) ? $context['illegal_permissions'] : array(),
534
				)
535
			);
536
537
			if (!empty($inserts))
538
			{
539
				// ..and insert the new ones.
540
				$smcFunc['db_insert']('',
541
					'{db_prefix}permissions',
542
					array(
543
						'permission' => 'string', 'id_group' => 'int', 'add_deny' => 'int',
544
					),
545
					$inserts,
546
					array('permission', 'id_group')
547
				);
548
			}
549
		}
550
551
		// Now do the same for the board permissions.
552
		$request = $smcFunc['db_query']('', '
553
			SELECT permission, add_deny
554
			FROM {db_prefix}board_permissions
555
			WHERE id_group = {int:copy_from}
556
				AND id_profile = {int:current_profile}',
557
			array(
558
				'copy_from' => $_POST['copy_from'],
559
				'current_profile' => $bid,
560
			)
561
		);
562
		$target_perm = array();
563
		while ($row = $smcFunc['db_fetch_assoc']($request))
564
			$target_perm[$row['permission']] = $row['add_deny'];
565
		$smcFunc['db_free_result']($request);
566
567
		$inserts = array();
568
		foreach ($_POST['group'] as $group_id)
569
			foreach ($target_perm as $perm => $add_deny)
570
			{
571
				// Are these for guests?
572
				if ($group_id == -1 && in_array($perm, $context['non_guest_permissions']))
573
					continue;
574
575
				$inserts[] = array($perm, $group_id, $bid, $add_deny);
576
			}
577
578
		// Delete the previous global board permissions...
579
		$smcFunc['db_query']('', '
580
			DELETE FROM {db_prefix}board_permissions
581
			WHERE id_group IN ({array_int:current_group_list})
582
				AND id_profile = {int:current_profile}',
583
			array(
584
				'current_group_list' => $_POST['group'],
585
				'current_profile' => $bid,
586
			)
587
		);
588
589
		// And insert the copied permissions.
590
		if (!empty($inserts))
591
		{
592
			// ..and insert the new ones.
593
			$smcFunc['db_insert']('',
594
				'{db_prefix}board_permissions',
595
				array('permission' => 'string', 'id_group' => 'int', 'id_profile' => 'int', 'add_deny' => 'int'),
596
				$inserts,
597
				array('permission', 'id_group', 'id_profile')
598
			);
599
		}
600
601
		// Update any children out there!
602
		updateChildPermissions($_POST['group'], $_REQUEST['pid']);
603
	}
604
	// Set or unset a certain permission for the selected groups.
605
	elseif (!empty($_POST['permissions']))
606
	{
607
		// Unpack two variables that were transported.
608
		list ($permissionType, $permission) = explode('/', $_POST['permissions']);
609
610
		// Check whether our input is within expected range.
611
		if (!in_array($_POST['add_remove'], array('add', 'clear', 'deny')) || !in_array($permissionType, array('membergroup', 'board')))
612
			redirectexit('action=admin;area=permissions;pid=' . $_REQUEST['pid']);
613
614
		if ($_POST['add_remove'] == 'clear')
615
		{
616
			if ($permissionType == 'membergroup')
617
			{
618
				$smcFunc['db_query']('', '
619
					DELETE FROM {db_prefix}permissions
620
					WHERE id_group IN ({array_int:current_group_list})
621
						AND permission = {string:current_permission}
622
						' . (empty($context['illegal_permissions']) ? '' : ' AND permission NOT IN ({array_string:illegal_permissions})'),
623
					array(
624
						'current_group_list' => $_POST['group'],
625
						'current_permission' => $permission,
626
						'illegal_permissions' => !empty($context['illegal_permissions']) ? $context['illegal_permissions'] : array(),
627
					)
628
				);
629
630
				// Did these changes make anyone lose eligibility for the bbc_html permission?
631
				$bbc_html_groups = array_diff($_POST['group'], $context['permissions_excluded']['bbc_html']);
632
				if (!empty($bbc_html_groups))
633
					removeIllegalBBCHtmlPermission(true);
634
			}
635
			else
636
				$smcFunc['db_query']('', '
637
					DELETE FROM {db_prefix}board_permissions
638
					WHERE id_group IN ({array_int:current_group_list})
639
						AND id_profile = {int:current_profile}
640
						AND permission = {string:current_permission}',
641
					array(
642
						'current_group_list' => $_POST['group'],
643
						'current_profile' => $bid,
644
						'current_permission' => $permission,
645
					)
646
				);
647
		}
648
		// Add a permission (either 'set' or 'deny').
649
		else
650
		{
651
			$add_deny = $_POST['add_remove'] == 'add' ? '1' : '0';
652
			$permChange = array();
653
			foreach ($_POST['group'] as $groupID)
654
			{
655
				if (isset($context['permissions_excluded'][$permission]) && in_array($groupID, $context['permissions_excluded'][$permission]))
656
					continue;
657
658
				if ($permissionType == 'membergroup' && $groupID != 1 && $groupID != 3 && (empty($context['illegal_permissions']) || !in_array($permission, $context['illegal_permissions'])))
659
					$permChange[] = array($permission, $groupID, $add_deny);
660
				elseif ($permissionType != 'membergroup')
661
					$permChange[] = array($permission, $groupID, $bid, $add_deny);
662
			}
663
664
			if (!empty($permChange))
665
			{
666
				if ($permissionType == 'membergroup')
667
					$smcFunc['db_insert']('replace',
668
						'{db_prefix}permissions',
669
						array('permission' => 'string', 'id_group' => 'int', 'add_deny' => 'int'),
670
						$permChange,
671
						array('permission', 'id_group')
672
					);
673
				// Board permissions go into the other table.
674
				else
675
					$smcFunc['db_insert']('replace',
676
						'{db_prefix}board_permissions',
677
						array('permission' => 'string', 'id_group' => 'int', 'id_profile' => 'int', 'add_deny' => 'int'),
678
						$permChange,
679
						array('permission', 'id_group', 'id_profile')
680
					);
681
			}
682
		}
683
684
		// Another child update!
685
		updateChildPermissions($_POST['group'], $_REQUEST['pid']);
686
	}
687
688
	updateBoardManagers();
689
690
	redirectexit('action=admin;area=permissions;pid=' . $_REQUEST['pid']);
691
}
692
693
/**
694
 * Initializes the necessary to modify a membergroup's permissions.
695
 */
696
function ModifyMembergroup()
697
{
698
	global $context, $txt, $smcFunc, $modSettings;
699
700
	if (!isset($_GET['group']))
701
		fatal_lang_error('no_access', false);
702
703
	$context['group']['id'] = (int) $_GET['group'];
704
705
	// It's not likely you'd end up here with this setting disabled.
706
	if ($_GET['group'] == 1)
707
		redirectexit('action=admin;area=permissions');
708
709
	loadAllPermissions();
710
	loadPermissionProfiles();
711
	$context['hidden_perms'] = array();
712
713
	if ($context['group']['id'] > 0)
714
	{
715
		$result = $smcFunc['db_query']('', '
716
			SELECT group_name, id_parent
717
			FROM {db_prefix}membergroups
718
			WHERE id_group = {int:current_group}
719
			LIMIT 1',
720
			array(
721
				'current_group' => $context['group']['id'],
722
			)
723
		);
724
		list ($context['group']['name'], $parent) = $smcFunc['db_fetch_row']($result);
725
		$smcFunc['db_free_result']($result);
726
727
		// Cannot edit an inherited group!
728
		if ($parent != -2)
729
			fatal_lang_error('cannot_edit_permissions_inherited');
730
	}
731
	elseif ($context['group']['id'] == -1)
732
		$context['group']['name'] = $txt['membergroups_guests'];
733
	else
734
		$context['group']['name'] = $txt['membergroups_members'];
735
736
	$context['profile']['id'] = empty($_GET['pid']) ? 0 : (int) $_GET['pid'];
737
738
	// If this is a moderator and they are editing "no profile" then we only do boards.
739
	if ($context['group']['id'] == 3 && empty($context['profile']['id']))
740
	{
741
		// For sanity just check they have no general permissions.
742
		$smcFunc['db_query']('', '
743
			DELETE FROM {db_prefix}permissions
744
			WHERE id_group = {int:moderator_group}',
745
			array(
746
				'moderator_group' => 3,
747
			)
748
		);
749
750
		$context['profile']['id'] = 1;
751
	}
752
753
	$context['permission_type'] = empty($context['profile']['id']) ? 'membergroup' : 'board';
754
	$context['profile']['can_modify'] = !$context['profile']['id'] || $context['profiles'][$context['profile']['id']]['can_modify'];
755
756
	// Set up things a little nicer for board related stuff...
757
	if ($context['permission_type'] == 'board')
758
	{
759
		$context['profile']['name'] = $context['profiles'][$context['profile']['id']]['name'];
760
		$context[$context['admin_menu_name']]['current_subsection'] = 'profiles';
761
	}
762
763
	// Fetch the current permissions.
764
	$permissions = array(
765
		'membergroup' => array('allowed' => array(), 'denied' => array()),
766
		'board' => array('allowed' => array(), 'denied' => array())
767
	);
768
769
	// General permissions?
770
	if ($context['permission_type'] == 'membergroup')
771
	{
772
		$result = $smcFunc['db_query']('', '
773
			SELECT permission, add_deny
774
			FROM {db_prefix}permissions
775
			WHERE id_group = {int:current_group}',
776
			array(
777
				'current_group' => $_GET['group'],
778
			)
779
		);
780
		while ($row = $smcFunc['db_fetch_assoc']($result))
781
			$permissions['membergroup'][empty($row['add_deny']) ? 'denied' : 'allowed'][] = $row['permission'];
782
		$smcFunc['db_free_result']($result);
783
	}
784
785
	// Fetch current board permissions...
786
	$result = $smcFunc['db_query']('', '
787
		SELECT permission, add_deny
788
		FROM {db_prefix}board_permissions
789
		WHERE id_group = {int:current_group}
790
			AND id_profile = {int:current_profile}',
791
		array(
792
			'current_group' => $context['group']['id'],
793
			'current_profile' => $context['permission_type'] == 'membergroup' ? 1 : $context['profile']['id'],
794
		)
795
	);
796
	while ($row = $smcFunc['db_fetch_assoc']($result))
797
		$permissions['board'][empty($row['add_deny']) ? 'denied' : 'allowed'][] = $row['permission'];
798
	$smcFunc['db_free_result']($result);
799
800
	// Loop through each permission and set whether it's checked.
801
	foreach ($context['permissions'] as $permissionType => $tmp)
802
	{
803
		foreach ($tmp['columns'] as $position => $permissionGroups)
804
		{
805
			foreach ($permissionGroups as $permissionGroup => $permissionArray)
806
			{
807
				foreach ($permissionArray['permissions'] as $perm)
808
				{
809
					// Create a shortcut for the current permission.
810
					$curPerm = &$context['permissions'][$permissionType]['columns'][$position][$permissionGroup]['permissions'][$perm['id']];
811
812
					if ($perm['has_own_any'])
813
					{
814
						$curPerm['any']['select'] = in_array($perm['id'] . '_any', $permissions[$permissionType]['allowed']) ? 'on' : (in_array($perm['id'] . '_any', $permissions[$permissionType]['denied']) ? 'deny' : 'off');
815
						$curPerm['own']['select'] = in_array($perm['id'] . '_own', $permissions[$permissionType]['allowed']) ? 'on' : (in_array($perm['id'] . '_own', $permissions[$permissionType]['denied']) ? 'deny' : 'off');
816
					}
817
					else
818
						$curPerm['select'] = in_array($perm['id'], $permissions[$permissionType]['denied']) ? 'deny' : (in_array($perm['id'], $permissions[$permissionType]['allowed']) ? 'on' : 'off');
819
820
					// Keep the last value if it's hidden.
821
					if ($perm['hidden'] || $permissionArray['hidden'])
822
					{
823
						if ($perm['has_own_any'])
824
						{
825
							$context['hidden_perms'][] = array(
826
								$permissionType,
827
								$perm['own']['id'],
828
								$curPerm['own']['select'] == 'deny' && !empty($modSettings['permission_enable_deny']) ? 'deny' : $curPerm['own']['select'],
829
							);
830
							$context['hidden_perms'][] = array(
831
								$permissionType,
832
								$perm['any']['id'],
833
								$curPerm['any']['select'] == 'deny' && !empty($modSettings['permission_enable_deny']) ? 'deny' : $curPerm['any']['select'],
834
							);
835
						}
836
						else
837
							$context['hidden_perms'][] = array(
838
								$permissionType,
839
								$perm['id'],
840
								$curPerm['select'] == 'deny' && !empty($modSettings['permission_enable_deny']) ? 'deny' : $curPerm['select'],
841
							);
842
					}
843
				}
844
			}
845
		}
846
	}
847
	$context['sub_template'] = 'modify_group';
848
	$context['page_title'] = $txt['permissions_modify_group'];
849
850
	createToken('admin-mp');
851
}
852
853
/**
854
 * This function actually saves modifications to a membergroup's board permissions.
855
 */
856
function ModifyMembergroup2()
857
{
858
	global $smcFunc, $context;
859
860
	checkSession();
861
	validateToken('admin-mp');
862
863
	loadIllegalPermissions();
864
865
	$_GET['group'] = (int) $_GET['group'];
866
	$_GET['pid'] = (int) $_GET['pid'];
867
868
	// Cannot modify predefined profiles.
869
	if ($_GET['pid'] > 1 && $_GET['pid'] < 5)
870
		fatal_lang_error('no_access', false);
871
872
	// Verify this isn't inherited.
873
	if ($_GET['group'] == -1 || $_GET['group'] == 0)
874
		$parent = -2;
875
	else
876
	{
877
		$result = $smcFunc['db_query']('', '
878
			SELECT id_parent
879
			FROM {db_prefix}membergroups
880
			WHERE id_group = {int:current_group}
881
			LIMIT 1',
882
			array(
883
				'current_group' => $_GET['group'],
884
			)
885
		);
886
		list ($parent) = $smcFunc['db_fetch_row']($result);
887
		$smcFunc['db_free_result']($result);
888
	}
889
890
	if ($parent != -2)
891
		fatal_lang_error('cannot_edit_permissions_inherited');
892
893
	$givePerms = array('membergroup' => array(), 'board' => array());
894
895
	// Guest group, we need illegal, guest permissions.
896
	if ($_GET['group'] == -1)
897
	{
898
		loadIllegalGuestPermissions();
899
		$context['illegal_permissions'] = array_merge($context['illegal_permissions'], $context['non_guest_permissions']);
900
	}
901
902
	// Prepare all permissions that were set or denied for addition to the DB.
903
	if (isset($_POST['perm']) && is_array($_POST['perm']))
904
	{
905
		foreach ($_POST['perm'] as $perm_type => $perm_array)
906
		{
907
			if (is_array($perm_array))
908
			{
909
				foreach ($perm_array as $permission => $value)
910
					if ($value == 'on' || $value == 'deny')
911
					{
912
						// Don't allow people to escalate themselves!
913
						if (!empty($context['illegal_permissions']) && in_array($permission, $context['illegal_permissions']))
914
							continue;
915
916
						$givePerms[$perm_type][] = array($_GET['group'], $permission, $value == 'deny' ? 0 : 1);
917
					}
918
			}
919
		}
920
	}
921
922
	// Insert the general permissions.
923
	if ($_GET['group'] != 3 && empty($_GET['pid']))
924
	{
925
		$smcFunc['db_query']('', '
926
			DELETE FROM {db_prefix}permissions
927
			WHERE id_group = {int:current_group}
928
			' . (empty($context['illegal_permissions']) ? '' : ' AND permission NOT IN ({array_string:illegal_permissions})'),
929
			array(
930
				'current_group' => $_GET['group'],
931
				'illegal_permissions' => !empty($context['illegal_permissions']) ? $context['illegal_permissions'] : array(),
932
			)
933
		);
934
935
		if (!empty($givePerms['membergroup']))
936
		{
937
			$smcFunc['db_insert']('replace',
938
				'{db_prefix}permissions',
939
				array('id_group' => 'int', 'permission' => 'string', 'add_deny' => 'int'),
940
				$givePerms['membergroup'],
941
				array('id_group', 'permission')
942
			);
943
		}
944
	}
945
946
	// Insert the boardpermissions.
947
	$profileid = max(1, $_GET['pid']);
948
	$smcFunc['db_query']('', '
949
		DELETE FROM {db_prefix}board_permissions
950
		WHERE id_group = {int:current_group}
951
			AND id_profile = {int:current_profile}',
952
		array(
953
			'current_group' => $_GET['group'],
954
			'current_profile' => $profileid,
955
		)
956
	);
957
	if (!empty($givePerms['board']))
958
	{
959
		foreach ($givePerms['board'] as $k => $v)
960
			$givePerms['board'][$k][] = $profileid;
961
962
		$smcFunc['db_insert']('replace',
963
			'{db_prefix}board_permissions',
964
			array('id_group' => 'int', 'permission' => 'string', 'add_deny' => 'int', 'id_profile' => 'int'),
965
			$givePerms['board'],
966
			array('id_group', 'permission', 'id_profile')
967
		);
968
	}
969
970
	// Update any inherited permissions as required.
971
	updateChildPermissions($_GET['group'], $_GET['pid']);
972
973
	removeIllegalBBCHtmlPermission();
974
975
	// Make sure $modSettings['board_manager_groups'] is up to date.
976
	if (!in_array('manage_boards', $context['illegal_permissions']))
977
		updateBoardManagers();
978
979
	// Clear cached privs.
980
	updateSettings(array('settings_updated' => time()));
981
982
	redirectexit('action=admin;area=permissions;pid=' . $_GET['pid']);
983
}
984
985
/**
986
 * A screen to set some general settings for permissions.
987
 *
988
 * @param bool $return_config Whether to return the $config_vars array (used for admin search)
989
 * @return void|array Returns nothing or returns the config_vars array if $return_config is true
990
 */
991
function GeneralPermissionSettings($return_config = false)
992
{
993
	global $context, $modSettings, $sourcedir, $txt, $scripturl, $smcFunc;
994
995
	// All the setting variables
996
	$config_vars = array(
997
		array('title', 'settings'),
998
		// Inline permissions.
999
		array('permissions', 'manage_permissions'),
1000
		'',
1001
1002
		// A few useful settings
1003
		array('check', 'permission_enable_deny', 0, $txt['permission_settings_enable_deny'], 'help' => 'permissions_deny'),
1004
		array('check', 'permission_enable_postgroups', 0, $txt['permission_settings_enable_postgroups'], 'help' => 'permissions_postgroups'),
1005
	);
1006
1007
	call_integration_hook('integrate_modify_permission_settings', array(&$config_vars));
1008
1009
	if ($return_config)
1010
		return $config_vars;
1011
1012
	$context['page_title'] = $txt['permission_settings_title'];
1013
	$context['sub_template'] = 'show_settings';
1014
1015
	// Needed for the inline permission functions, and the settings template.
1016
	require_once($sourcedir . '/ManageServer.php');
1017
1018
	$context['post_url'] = $scripturl . '?action=admin;area=permissions;save;sa=settings';
1019
1020
	// Saving the settings?
1021
	if (isset($_GET['save']))
1022
	{
1023
		checkSession();
1024
		call_integration_hook('integrate_save_permission_settings');
1025
		saveDBSettings($config_vars);
1026
1027
		// Clear all deny permissions...if we want that.
1028
		if (empty($modSettings['permission_enable_deny']))
1029
		{
1030
			$smcFunc['db_query']('', '
1031
				DELETE FROM {db_prefix}permissions
1032
				WHERE add_deny = {int:denied}',
1033
				array(
1034
					'denied' => 0,
1035
				)
1036
			);
1037
			$smcFunc['db_query']('', '
1038
				DELETE FROM {db_prefix}board_permissions
1039
				WHERE add_deny = {int:denied}',
1040
				array(
1041
					'denied' => 0,
1042
				)
1043
			);
1044
		}
1045
1046
		// Make sure there are no postgroup based permissions left.
1047
		if (empty($modSettings['permission_enable_postgroups']))
1048
		{
1049
			// Get a list of postgroups.
1050
			$post_groups = array();
1051
			$request = $smcFunc['db_query']('', '
1052
				SELECT id_group
1053
				FROM {db_prefix}membergroups
1054
				WHERE min_posts != {int:min_posts}',
1055
				array(
1056
					'min_posts' => -1,
1057
				)
1058
			);
1059
			while ($row = $smcFunc['db_fetch_assoc']($request))
1060
				$post_groups[] = $row['id_group'];
1061
			$smcFunc['db_free_result']($request);
1062
1063
			// Remove'em.
1064
			$smcFunc['db_query']('', '
1065
				DELETE FROM {db_prefix}permissions
1066
				WHERE id_group IN ({array_int:post_group_list})',
1067
				array(
1068
					'post_group_list' => $post_groups,
1069
				)
1070
			);
1071
			$smcFunc['db_query']('', '
1072
				DELETE FROM {db_prefix}board_permissions
1073
				WHERE id_group IN ({array_int:post_group_list})',
1074
				array(
1075
					'post_group_list' => $post_groups,
1076
				)
1077
			);
1078
			$smcFunc['db_query']('', '
1079
				UPDATE {db_prefix}membergroups
1080
				SET id_parent = {int:not_inherited}
1081
				WHERE id_parent IN ({array_int:post_group_list})',
1082
				array(
1083
					'post_group_list' => $post_groups,
1084
					'not_inherited' => -2,
1085
				)
1086
			);
1087
		}
1088
1089
		$_SESSION['adm-save'] = true;
1090
		redirectexit('action=admin;area=permissions;sa=settings');
1091
	}
1092
1093
	// We need this for the in-line permissions
1094
	createToken('admin-mp');
1095
1096
	prepareDBSettingContext($config_vars);
1097
}
1098
1099
/**
1100
 * Set the permission level for a specific profile, group, or group for a profile.
1101
 *
1102
 * @internal
1103
 *
1104
 * @param string $level The level ('restrict', 'standard', etc.)
1105
 * @param int $group The group to set the permission for
1106
 * @param string|int $profile The ID of the permissions profile or 'null' if we're setting it for a group
1107
 */
1108
function setPermissionLevel($level, $group, $profile = 'null')
1109
{
1110
	global $smcFunc, $context;
1111
1112
	loadIllegalPermissions();
1113
	loadIllegalGuestPermissions();
1114
	loadIllegalBBCHtmlGroups();
1115
1116
	// Levels by group... restrict, standard, moderator, maintenance.
1117
	$groupLevels = array(
1118
		'board' => array('inherit' => array()),
1119
		'group' => array('inherit' => array())
1120
	);
1121
	// Levels by board... standard, publish, free.
1122
	$boardLevels = array('inherit' => array());
1123
1124
	// Restrictive - ie. guests.
1125
	$groupLevels['global']['restrict'] = array(
1126
		'search_posts',
1127
		'calendar_view',
1128
		'view_stats',
1129
		'who_view',
1130
		'profile_identity_own',
1131
	);
1132
	$groupLevels['board']['restrict'] = array(
1133
		'poll_view',
1134
		'post_new',
1135
		'post_reply_own',
1136
		'post_reply_any',
1137
		'delete_own',
1138
		'modify_own',
1139
		'report_any',
1140
	);
1141
1142
	// Standard - ie. members.  They can do anything Restrictive can.
1143
	$groupLevels['global']['standard'] = array_merge($groupLevels['global']['restrict'], array(
1144
		'view_mlist',
1145
		'likes_like',
1146
		'mention',
1147
		'pm_read',
1148
		'pm_send',
1149
		'profile_view',
1150
		'profile_extra_own',
1151
		'profile_signature_own',
1152
		'profile_forum_own',
1153
		'profile_website_own',
1154
		'profile_password_own',
1155
		'profile_server_avatar',
1156
		'profile_displayed_name',
1157
		'profile_upload_avatar',
1158
		'profile_remote_avatar',
1159
		'profile_remove_own',
1160
		'report_user',
1161
	));
1162
	$groupLevels['board']['standard'] = array_merge($groupLevels['board']['restrict'], array(
1163
		'poll_vote',
1164
		'poll_edit_own',
1165
		'poll_post',
1166
		'poll_add_own',
1167
		'post_attachment',
1168
		'lock_own',
1169
		'remove_own',
1170
		'view_attachments',
1171
	));
1172
1173
	// Moderator - ie. moderators :P.  They can do what standard can, and more.
1174
	$groupLevels['global']['moderator'] = array_merge($groupLevels['global']['standard'], array(
1175
		'calendar_post',
1176
		'calendar_edit_own',
1177
		'access_mod_center',
1178
		'issue_warning',
1179
	));
1180
	$groupLevels['board']['moderator'] = array_merge($groupLevels['board']['standard'], array(
1181
		'make_sticky',
1182
		'poll_edit_any',
1183
		'delete_any',
1184
		'modify_any',
1185
		'lock_any',
1186
		'remove_any',
1187
		'move_any',
1188
		'merge_any',
1189
		'split_any',
1190
		'poll_lock_any',
1191
		'poll_remove_any',
1192
		'poll_add_any',
1193
		'approve_posts',
1194
	));
1195
1196
	// Maintenance - wannabe admins.  They can do almost everything.
1197
	$groupLevels['global']['maintenance'] = array_merge($groupLevels['global']['moderator'], array(
1198
		'manage_attachments',
1199
		'manage_smileys',
1200
		'manage_boards',
1201
		'moderate_forum',
1202
		'manage_membergroups',
1203
		'manage_bans',
1204
		'admin_forum',
1205
		'bbc_html',
1206
		'manage_permissions',
1207
		'edit_news',
1208
		'calendar_edit_any',
1209
		'profile_identity_any',
1210
		'profile_extra_any',
1211
		'profile_signature_any',
1212
		'profile_website_any',
1213
		'profile_displayed_name_any',
1214
		'profile_password_any',
1215
		'profile_title_any',
1216
	));
1217
	$groupLevels['board']['maintenance'] = array_merge($groupLevels['board']['moderator'], array(
1218
	));
1219
1220
	// Standard - nothing above the group permissions. (this SHOULD be empty.)
1221
	$boardLevels['standard'] = array(
1222
	);
1223
1224
	// Locked - just that, you can't post here.
1225
	$boardLevels['locked'] = array(
1226
		'poll_view',
1227
		'report_any',
1228
		'view_attachments',
1229
	);
1230
1231
	// Publisher - just a little more...
1232
	$boardLevels['publish'] = array_merge($boardLevels['locked'], array(
1233
		'post_new',
1234
		'post_reply_own',
1235
		'post_reply_any',
1236
		'delete_own',
1237
		'modify_own',
1238
		'delete_replies',
1239
		'modify_replies',
1240
		'poll_vote',
1241
		'poll_edit_own',
1242
		'poll_post',
1243
		'poll_add_own',
1244
		'poll_remove_own',
1245
		'post_attachment',
1246
		'lock_own',
1247
		'remove_own',
1248
	));
1249
1250
	// Free for All - Scary.  Just scary.
1251
	$boardLevels['free'] = array_merge($boardLevels['publish'], array(
1252
		'poll_lock_any',
1253
		'poll_edit_any',
1254
		'poll_add_any',
1255
		'poll_remove_any',
1256
		'make_sticky',
1257
		'lock_any',
1258
		'remove_any',
1259
		'delete_any',
1260
		'split_any',
1261
		'merge_any',
1262
		'modify_any',
1263
		'approve_posts',
1264
	));
1265
1266
	call_integration_hook('integrate_load_permission_levels', array(&$groupLevels, &$boardLevels));
1267
1268
	// Make sure we're not granting someone too many permissions!
1269
	foreach ($groupLevels['global'][$level] as $k => $permission)
1270
	{
1271
		if (!empty($context['illegal_permissions']) && in_array($permission, $context['illegal_permissions']))
1272
			unset($groupLevels['global'][$level][$k]);
1273
1274
		if (isset($context['permissions_excluded'][$permission]) && in_array($group, $context['permissions_excluded'][$permission]))
1275
			unset($groupLevels['global'][$level][$k]);
1276
	}
1277
	foreach ($groupLevels['board'][$level] as $k => $permission)
1278
		if (isset($context['permissions_excluded'][$permission]) && in_array($group, $context['permissions_excluded'][$permission]))
1279
			unset($groupLevels['board'][$level][$k]);
1280
1281
	// Reset all cached permissions.
1282
	updateSettings(array('settings_updated' => time()));
1283
1284
	// Setting group permissions.
1285
	if ($profile === 'null' && $group !== 'null')
1286
	{
1287
		$group = (int) $group;
1288
1289
		if (empty($groupLevels['global'][$level]))
1290
			return;
1291
1292
		$smcFunc['db_query']('', '
1293
			DELETE FROM {db_prefix}permissions
1294
			WHERE id_group = {int:current_group}
1295
			' . (empty($context['illegal_permissions']) ? '' : ' AND permission NOT IN ({array_string:illegal_permissions})'),
1296
			array(
1297
				'current_group' => $group,
1298
				'illegal_permissions' => !empty($context['illegal_permissions']) ? $context['illegal_permissions'] : array(),
1299
			)
1300
		);
1301
		$smcFunc['db_query']('', '
1302
			DELETE FROM {db_prefix}board_permissions
1303
			WHERE id_group = {int:current_group}
1304
				AND id_profile = {int:default_profile}',
1305
			array(
1306
				'current_group' => $group,
1307
				'default_profile' => 1,
1308
			)
1309
		);
1310
1311
		$groupInserts = array();
1312
		foreach ($groupLevels['global'][$level] as $permission)
1313
			$groupInserts[] = array($group, $permission);
1314
1315
		$smcFunc['db_insert']('insert',
1316
			'{db_prefix}permissions',
1317
			array('id_group' => 'int', 'permission' => 'string'),
1318
			$groupInserts,
1319
			array('id_group')
1320
		);
1321
1322
		$boardInserts = array();
1323
		foreach ($groupLevels['board'][$level] as $permission)
1324
			$boardInserts[] = array(1, $group, $permission);
1325
1326
		$smcFunc['db_insert']('insert',
1327
			'{db_prefix}board_permissions',
1328
			array('id_profile' => 'int', 'id_group' => 'int', 'permission' => 'string'),
1329
			$boardInserts,
1330
			array('id_profile', 'id_group')
1331
		);
1332
1333
		removeIllegalBBCHtmlPermission();
1334
	}
1335
	// Setting profile permissions for a specific group.
1336
	elseif ($profile !== 'null' && $group !== 'null' && ($profile == 1 || $profile > 4))
1337
	{
1338
		$group = (int) $group;
1339
		$profile = (int) $profile;
1340
1341
		if (!empty($groupLevels['global'][$level]))
1342
		{
1343
			$smcFunc['db_query']('', '
1344
				DELETE FROM {db_prefix}board_permissions
1345
				WHERE id_group = {int:current_group}
1346
					AND id_profile = {int:current_profile}',
1347
				array(
1348
					'current_group' => $group,
1349
					'current_profile' => $profile,
1350
				)
1351
			);
1352
		}
1353
1354
		if (!empty($groupLevels['board'][$level]))
1355
		{
1356
			$boardInserts = array();
1357
			foreach ($groupLevels['board'][$level] as $permission)
1358
				$boardInserts[] = array($profile, $group, $permission);
1359
1360
			$smcFunc['db_insert']('insert',
1361
				'{db_prefix}board_permissions',
1362
				array('id_profile' => 'int', 'id_group' => 'int', 'permission' => 'string'),
1363
				$boardInserts,
1364
				array('id_profile', 'id_group')
1365
			);
1366
		}
1367
	}
1368
	// Setting profile permissions for all groups.
1369
	elseif ($profile !== 'null' && $group === 'null' && ($profile == 1 || $profile > 4))
0 ignored issues
show
introduced by
The condition $group === 'null' is always false.
Loading history...
1370
	{
1371
		$profile = (int) $profile;
1372
1373
		$smcFunc['db_query']('', '
1374
			DELETE FROM {db_prefix}board_permissions
1375
			WHERE id_profile = {int:current_profile}',
1376
			array(
1377
				'current_profile' => $profile,
1378
			)
1379
		);
1380
1381
		if (empty($boardLevels[$level]))
1382
			return;
1383
1384
		// Get all the groups...
1385
		$query = $smcFunc['db_query']('', '
1386
			SELECT id_group
1387
			FROM {db_prefix}membergroups
1388
			WHERE id_group > {int:moderator_group}
1389
			ORDER BY min_posts, CASE WHEN id_group < {int:newbie_group} THEN id_group ELSE 4 END, group_name',
1390
			array(
1391
				'moderator_group' => 3,
1392
				'newbie_group' => 4,
1393
			)
1394
		);
1395
		while ($row = $smcFunc['db_fetch_row']($query))
1396
		{
1397
			$group = $row[0];
1398
1399
			$boardInserts = array();
1400
			foreach ($boardLevels[$level] as $permission)
1401
				$boardInserts[] = array($profile, $group, $permission);
1402
1403
			$smcFunc['db_insert']('insert',
1404
				'{db_prefix}board_permissions',
1405
				array('id_profile' => 'int', 'id_group' => 'int', 'permission' => 'string'),
1406
				$boardInserts,
1407
				array('id_profile', 'id_group')
1408
			);
1409
		}
1410
		$smcFunc['db_free_result']($query);
1411
1412
		// Add permissions for ungrouped members.
1413
		$boardInserts = array();
1414
		foreach ($boardLevels[$level] as $permission)
1415
			$boardInserts[] = array($profile, 0, $permission);
1416
1417
		$smcFunc['db_insert']('insert',
1418
			'{db_prefix}board_permissions',
1419
			array('id_profile' => 'int', 'id_group' => 'int', 'permission' => 'string'),
1420
			$boardInserts,
1421
			array('id_profile', 'id_group')
1422
		);
1423
	}
1424
	// $profile and $group are both null!
1425
	else
1426
		fatal_lang_error('no_access', false);
1427
1428
	// Make sure $modSettings['board_manager_groups'] is up to date.
1429
	if (!in_array('manage_boards', $context['illegal_permissions']))
1430
		updateBoardManagers();
1431
}
1432
1433
/**
1434
 * Load permissions into $context['permissions'].
1435
 *
1436
 * @internal
1437
 */
1438
function loadAllPermissions()
1439
{
1440
	global $context, $txt, $modSettings;
1441
1442
	// List of all the groups dependant on the currently selected view - for the order so it looks pretty, yea?
1443
	// Note to Mod authors - you don't need to stick your permission group here if you don't mind SMF sticking it the last group of the page.
1444
	$permissionGroups = array(
1445
		'membergroup' => array(
1446
			'general',
1447
			'pm',
1448
			'calendar',
1449
			'maintenance',
1450
			'member_admin',
1451
			'profile',
1452
			'likes',
1453
			'mentions',
1454
			'bbc',
1455
		),
1456
		'board' => array(
1457
			'general_board',
1458
			'topic',
1459
			'post',
1460
			'poll',
1461
			'notification',
1462
			'attachment',
1463
		),
1464
	);
1465
1466
	/*   The format of this list is as follows:
1467
		'membergroup' => array(
1468
			'permissions_inside' => array(has_multiple_options, view_group),
1469
		),
1470
		'board' => array(
1471
			'permissions_inside' => array(has_multiple_options, view_group),
1472
		);
1473
	*/
1474
	$permissionList = array(
1475
		'membergroup' => array(
1476
			'view_stats' => array(false, 'general'),
1477
			'view_mlist' => array(false, 'general'),
1478
			'who_view' => array(false, 'general'),
1479
			'search_posts' => array(false, 'general'),
1480
			'pm_read' => array(false, 'pm'),
1481
			'pm_send' => array(false, 'pm'),
1482
			'pm_draft' => array(false, 'pm'),
1483
			'calendar_view' => array(false, 'calendar'),
1484
			'calendar_post' => array(false, 'calendar'),
1485
			'calendar_edit' => array(true, 'calendar'),
1486
			'admin_forum' => array(false, 'maintenance'),
1487
			'manage_boards' => array(false, 'maintenance'),
1488
			'manage_attachments' => array(false, 'maintenance'),
1489
			'manage_smileys' => array(false, 'maintenance'),
1490
			'edit_news' => array(false, 'maintenance'),
1491
			'access_mod_center' => array(false, 'maintenance'),
1492
			'moderate_forum' => array(false, 'member_admin'),
1493
			'manage_membergroups' => array(false, 'member_admin'),
1494
			'manage_permissions' => array(false, 'member_admin'),
1495
			'manage_bans' => array(false, 'member_admin'),
1496
			'send_mail' => array(false, 'member_admin'),
1497
			'issue_warning' => array(false, 'member_admin'),
1498
			'profile_view' => array(false, 'profile'),
1499
			'profile_forum' => array(true, 'profile'),
1500
			'profile_extra' => array(true, 'profile'),
1501
			'profile_signature' => array(true, 'profile'),
1502
			'profile_website' => array(true, 'profile'),
1503
			'profile_title' => array(true, 'profile'),
1504
			'profile_blurb' => array(true, 'profile'),
1505
			'profile_server_avatar' => array(false, 'profile'),
1506
			'profile_upload_avatar' => array(false, 'profile'),
1507
			'profile_remote_avatar' => array(false, 'profile'),
1508
			'report_user' => array(false, 'profile'),
1509
			'profile_identity' => array(true, 'profile_account'),
1510
			'profile_displayed_name' => array(true, 'profile_account'),
1511
			'profile_password' => array(true, 'profile_account'),
1512
			'profile_remove' => array(true, 'profile_account'),
1513
			'view_warning' => array(true, 'profile_account'),
1514
			'likes_like' => array(false, 'likes'),
1515
			'mention' => array(false, 'mentions'),
1516
		),
1517
		'board' => array(
1518
			'moderate_board' => array(false, 'general_board'),
1519
			'approve_posts' => array(false, 'general_board'),
1520
			'post_new' => array(false, 'topic'),
1521
			'post_unapproved_topics' => array(false, 'topic'),
1522
			'post_reply' => array(true, 'topic'),
1523
			'post_unapproved_replies' => array(true, 'topic'),
1524
			'post_draft' => array(false, 'topic'),
1525
			'merge_any' => array(false, 'topic'),
1526
			'split_any' => array(false, 'topic'),
1527
			'make_sticky' => array(false, 'topic'),
1528
			'move' => array(true, 'topic', 'moderate'),
1529
			'lock' => array(true, 'topic', 'moderate'),
1530
			'remove' => array(true, 'topic', 'modify'),
1531
			'modify_replies' => array(false, 'topic'),
1532
			'delete_replies' => array(false, 'topic'),
1533
			'announce_topic' => array(false, 'topic'),
1534
			'delete' => array(true, 'post'),
1535
			'modify' => array(true, 'post'),
1536
			'report_any' => array(false, 'post'),
1537
			'poll_view' => array(false, 'poll'),
1538
			'poll_vote' => array(false, 'poll'),
1539
			'poll_post' => array(false, 'poll'),
1540
			'poll_add' => array(true, 'poll'),
1541
			'poll_edit' => array(true, 'poll'),
1542
			'poll_lock' => array(true, 'poll'),
1543
			'poll_remove' => array(true, 'poll'),
1544
			'view_attachments' => array(false, 'attachment'),
1545
			'post_unapproved_attachments' => array(false, 'attachment'),
1546
			'post_attachment' => array(false, 'attachment'),
1547
		),
1548
	);
1549
1550
	// In case a mod screwed things up...
1551
	if (!in_array('html', $context['restricted_bbc']))
1552
		$context['restricted_bbc'][] = 'html';
1553
1554
	// Add the permissions for the restricted BBCodes
1555
	foreach ($context['restricted_bbc'] as $bbc)
1556
	{
1557
		$permissionList['membergroup']['bbc_' . $bbc] = array(false, 'bbc');
1558
		$txt['permissionname_bbc_' . $bbc] = sprintf($txt['permissionname_bbc'], $bbc);
1559
	}
1560
1561
	// All permission groups that will be shown in the left column on classic view.
1562
	$leftPermissionGroups = array(
1563
		'general',
1564
		'calendar',
1565
		'maintenance',
1566
		'member_admin',
1567
		'topic',
1568
		'post',
1569
	);
1570
1571
	// We need to know what permissions we can't give to guests.
1572
	loadIllegalGuestPermissions();
1573
1574
	// We also need to know which groups can't be given the bbc_html permission.
1575
	loadIllegalBBCHtmlGroups();
1576
1577
	// Some permissions are hidden if features are off.
1578
	$hiddenPermissions = array();
1579
	$relabelPermissions = array(); // Permissions to apply a different label to.
1580
	if (empty($modSettings['cal_enabled']))
1581
	{
1582
		$hiddenPermissions[] = 'calendar_view';
1583
		$hiddenPermissions[] = 'calendar_post';
1584
		$hiddenPermissions[] = 'calendar_edit';
1585
	}
1586
	if ($modSettings['warning_settings'][0] == 0)
1587
	{
1588
		$hiddenPermissions[] = 'issue_warning';
1589
		$hiddenPermissions[] = 'view_warning';
1590
	}
1591
1592
	// Post moderation?
1593
	if (!$modSettings['postmod_active'])
1594
	{
1595
		$hiddenPermissions[] = 'approve_posts';
1596
		$hiddenPermissions[] = 'post_unapproved_topics';
1597
		$hiddenPermissions[] = 'post_unapproved_replies';
1598
		$hiddenPermissions[] = 'post_unapproved_attachments';
1599
	}
1600
	// If post moderation is enabled, these are named differently...
1601
	else
1602
	{
1603
		// Relabel the topics permissions
1604
		$relabelPermissions['post_new'] = 'auto_approve_topics';
1605
1606
		// Relabel the reply permissions
1607
		$relabelPermissions['post_reply'] = 'auto_approve_replies';
1608
1609
		// Relabel the attachment permissions
1610
		$relabelPermissions['post_attachment'] = 'auto_approve_attachments';
1611
	}
1612
1613
	// Are attachments enabled?
1614
	if (empty($modSettings['attachmentEnable']))
1615
	{
1616
		$hiddenPermissions[] = 'manage_attachments';
1617
		$hiddenPermissions[] = 'view_attachments';
1618
		$hiddenPermissions[] = 'post_unapproved_attachments';
1619
		$hiddenPermissions[] = 'post_attachment';
1620
	}
1621
1622
	// Hide Likes/Mentions permissions...
1623
	if (empty($modSettings['enable_likes']))
1624
	{
1625
		$hiddenPermissions[] = 'likes_like';
1626
	}
1627
	if (empty($modSettings['enable_mentions']))
1628
	{
1629
		$hiddenPermissions[] = 'mention';
1630
	}
1631
1632
	// Provide a practical way to modify permissions.
1633
	call_integration_hook('integrate_load_permissions', array(&$permissionGroups, &$permissionList, &$leftPermissionGroups, &$hiddenPermissions, &$relabelPermissions));
1634
1635
	$permissionList['membergroup']['bbc_cowsay'] = array(false, 'bbc');
1636
	$hiddenPermissions[] = 'bbc_cowsay';
1637
	$txt['permissionname_bbc_cowsay'] = sprintf($txt['permissionname_bbc'], 'cowsay');
1638
1639
	$context['permissions'] = array();
1640
	$context['hidden_permissions'] = array();
1641
	foreach ($permissionList as $permissionType => $permissionList)
1642
	{
1643
		$context['permissions'][$permissionType] = array(
1644
			'id' => $permissionType,
1645
			'columns' => array()
1646
		);
1647
		foreach ($permissionList as $permission => $permissionArray)
1648
		{
1649
			// If this permission shouldn't be given to certain groups (e.g. guests), don't.
1650
			if (isset($context['group']['id']) && isset($context['permissions_excluded'][$permission]) && in_array($context['group']['id'], $context['permissions_excluded'][$permission]))
1651
				continue;
1652
1653
			// What groups will this permission be in?
1654
			$own_group = $permissionArray[1];
1655
1656
			// First, Do these groups actually exist - if not add them.
1657
			if (!isset($permissionGroups[$permissionType][$own_group]))
1658
				$permissionGroups[$permissionType][$own_group] = true;
1659
1660
			// What column should this be located into?
1661
			$position = !in_array($own_group, $leftPermissionGroups) ? 1 : 0;
1662
1663
			// If the groups have not yet been created be sure to create them.
1664
			$bothGroups = array('own' => $own_group);
1665
1666
			foreach ($bothGroups as $group)
1667
				if (!isset($context['permissions'][$permissionType]['columns'][$position][$group]))
1668
					$context['permissions'][$permissionType]['columns'][$position][$group] = array(
1669
						'type' => $permissionType,
1670
						'id' => $group,
1671
						'name' => $txt['permissiongroup_' . $group],
1672
						'icon' => isset($txt['permissionicon_' . $group]) ? $txt['permissionicon_' . $group] : $txt['permissionicon'],
1673
						'help' => isset($txt['permissionhelp_' . $group]) ? $txt['permissionhelp_' . $group] : '',
1674
						'hidden' => false,
1675
						'permissions' => array()
1676
					);
1677
1678
			$context['permissions'][$permissionType]['columns'][$position][$own_group]['permissions'][$permission] = array(
1679
				'id' => $permission,
1680
				'name' => !isset($relabelPermissions[$permission]) ? $txt['permissionname_' . $permission] : $txt[$relabelPermissions[$permission]],
1681
				'show_help' => isset($txt['permissionhelp_' . $permission]),
1682
				'note' => isset($txt['permissionnote_' . $permission]) ? $txt['permissionnote_' . $permission] : '',
1683
				'has_own_any' => $permissionArray[0],
1684
				'own' => array(
1685
					'id' => $permission . '_own',
1686
					'name' => $permissionArray[0] ? $txt['permissionname_' . $permission . '_own'] : ''
1687
				),
1688
				'any' => array(
1689
					'id' => $permission . '_any',
1690
					'name' => $permissionArray[0] ? $txt['permissionname_' . $permission . '_any'] : ''
1691
				),
1692
				'hidden' => in_array($permission, $hiddenPermissions),
1693
			);
1694
1695
			if (in_array($permission, $hiddenPermissions))
1696
			{
1697
				if ($permissionArray[0])
1698
				{
1699
					$context['hidden_permissions'][] = $permission . '_own';
1700
					$context['hidden_permissions'][] = $permission . '_any';
1701
				}
1702
				else
1703
					$context['hidden_permissions'][] = $permission;
1704
			}
1705
		}
1706
		ksort($context['permissions'][$permissionType]['columns']);
1707
1708
		// Check we don't leave any empty groups - and mark hidden ones as such.
1709
		foreach ($context['permissions'][$permissionType]['columns'] as $column => $groups)
1710
			foreach ($groups as $id => $group)
1711
			{
1712
				if (empty($group['permissions']))
1713
					unset($context['permissions'][$permissionType]['columns'][$column][$id]);
1714
				else
1715
				{
1716
					$foundNonHidden = false;
1717
					foreach ($group['permissions'] as $permission)
1718
						if (empty($permission['hidden']))
1719
							$foundNonHidden = true;
1720
					if (!$foundNonHidden)
1721
						$context['permissions'][$permissionType]['columns'][$column][$id]['hidden'] = true;
1722
				}
1723
			}
1724
	}
1725
}
1726
1727
/**
1728
 * Initialize a form with inline permissions settings.
1729
 * It loads a context variable for each permission.
1730
 * This function is used by several settings screens to set specific permissions.
1731
 *
1732
 * To exclude groups from the form for a given permission, add the group IDs as
1733
 * an array to $context['excluded_permissions'][$permission]. For backwards
1734
 * compatibility, it is also possible to pass group IDs in via the
1735
 * $excluded_groups parameter, which will exclude the groups from the forms for
1736
 * all of the permissions passed in via $permissions.
1737
 *
1738
 * @internal
1739
 *
1740
 * @param array $permissions The permissions to display inline
1741
 * @param array $excluded_groups The IDs of one or more groups to exclude
1742
 *
1743
 * Uses ManagePermissions language
1744
 * Uses ManagePermissions template
1745
 */
1746
function init_inline_permissions($permissions, $excluded_groups = array())
1747
{
1748
	global $context, $txt, $modSettings, $smcFunc;
1749
1750
	loadLanguage('ManagePermissions');
1751
	loadTemplate('ManagePermissions');
1752
	$context['can_change_permissions'] = allowedTo('manage_permissions');
1753
1754
	// Nothing to initialize here.
1755
	if (!$context['can_change_permissions'])
1756
		return;
1757
1758
	// Load the permission settings for guests
1759
	foreach ($permissions as $permission)
1760
		$context[$permission] = array(
1761
			-1 => array(
1762
				'id' => -1,
1763
				'name' => $txt['membergroups_guests'],
1764
				'is_postgroup' => false,
1765
				'status' => 'off',
1766
			),
1767
			0 => array(
1768
				'id' => 0,
1769
				'name' => $txt['membergroups_members'],
1770
				'is_postgroup' => false,
1771
				'status' => 'off',
1772
			),
1773
		);
1774
1775
	$request = $smcFunc['db_query']('', '
1776
		SELECT id_group, CASE WHEN add_deny = {int:denied} THEN {string:deny} ELSE {string:on} END AS status, permission
1777
		FROM {db_prefix}permissions
1778
		WHERE id_group IN (-1, 0)
1779
			AND permission IN ({array_string:permissions})',
1780
		array(
1781
			'denied' => 0,
1782
			'permissions' => $permissions,
1783
			'deny' => 'deny',
1784
			'on' => 'on',
1785
		)
1786
	);
1787
	while ($row = $smcFunc['db_fetch_assoc']($request))
1788
		$context[$row['permission']][$row['id_group']]['status'] = $row['status'];
1789
	$smcFunc['db_free_result']($request);
1790
1791
	$request = $smcFunc['db_query']('', '
1792
		SELECT mg.id_group, mg.group_name, mg.min_posts, COALESCE(p.add_deny, -1) AS status, p.permission
1793
		FROM {db_prefix}membergroups AS mg
1794
			LEFT JOIN {db_prefix}permissions AS p ON (p.id_group = mg.id_group AND p.permission IN ({array_string:permissions}))
1795
		WHERE mg.id_group NOT IN (1, 3)
1796
			AND mg.id_parent = {int:not_inherited}' . (empty($modSettings['permission_enable_postgroups']) ? '
1797
			AND mg.min_posts = {int:min_posts}' : '') . '
1798
		ORDER BY mg.min_posts, CASE WHEN mg.id_group < {int:newbie_group} THEN mg.id_group ELSE 4 END, mg.group_name',
1799
		array(
1800
			'not_inherited' => -2,
1801
			'min_posts' => -1,
1802
			'newbie_group' => 4,
1803
			'permissions' => $permissions,
1804
		)
1805
	);
1806
	while ($row = $smcFunc['db_fetch_assoc']($request))
1807
	{
1808
		// Initialize each permission as being 'off' until proven otherwise.
1809
		foreach ($permissions as $permission)
1810
			if (!isset($context[$permission][$row['id_group']]))
1811
				$context[$permission][$row['id_group']] = array(
1812
					'id' => $row['id_group'],
1813
					'name' => $row['group_name'],
1814
					'is_postgroup' => $row['min_posts'] != -1,
1815
					'status' => 'off',
1816
				);
1817
1818
		$context[$row['permission']][$row['id_group']]['status'] = empty($row['status']) ? 'deny' : ($row['status'] == 1 ? 'on' : 'off');
1819
	}
1820
	$smcFunc['db_free_result']($request);
1821
1822
	// Make sure we honor the "illegal guest permissions"
1823
	loadIllegalGuestPermissions();
1824
1825
	// Only special people can have this permission
1826
	if (in_array('bbc_html', $permissions))
1827
		loadIllegalBBCHtmlGroups();
1828
1829
	// Are any of these permissions that guests can't have?
1830
	$non_guest_perms = array_intersect(str_replace(array('_any', '_own'), '', $permissions), $context['non_guest_permissions']);
1831
	foreach ($non_guest_perms as $permission)
1832
	{
1833
		if (!isset($context['permissions_excluded'][$permission]) || !in_array(-1, $context['permissions_excluded'][$permission]))
1834
			$context['permissions_excluded'][$permission][] = -1;
1835
	}
1836
1837
	// Any explicitly excluded groups for this call?
1838
	if (!empty($excluded_groups))
1839
	{
1840
		// Make sure this is an array of integers
1841
		$excluded_groups = array_filter(
1842
			(array) $excluded_groups,
1843
			function ($v)
1844
			{
1845
				return is_int($v) || is_string($v) && (string) intval($v) === $v;
1846
			}
1847
		);
1848
1849
		foreach ($permissions as $permission)
1850
			$context['permissions_excluded'][$permission] = array_unique(array_merge($context['permissions_excluded'][$permission], $excluded_groups));
1851
	}
1852
1853
	// Some permissions cannot be given to certain groups. Remove the groups.
1854
	foreach ($permissions as $permission)
1855
	{
1856
		if (!isset($context['permissions_excluded'][$permission]))
1857
			continue;
1858
1859
		foreach ($context['permissions_excluded'][$permission] as $group)
1860
		{
1861
			if (isset($context[$permission][$group]))
1862
				unset($context[$permission][$group]);
1863
		}
1864
1865
		// There's no point showing a form with nobody in it
1866
		if (empty($context[$permission]))
1867
			unset($context['config_vars'][$permission], $context[$permission]);
1868
	}
1869
1870
	// Create the token for the separate inline permission verification.
1871
	createToken('admin-mp');
1872
}
1873
1874
/**
1875
 * Show a collapsible box to set a specific permission.
1876
 * The function is called by templates to show a list of permissions settings.
1877
 * Calls the template function template_inline_permissions().
1878
 *
1879
 * @param string $permission The permission to display inline
1880
 */
1881
function theme_inline_permissions($permission)
1882
{
1883
	global $context;
1884
1885
	$context['current_permission'] = $permission;
1886
	$context['member_groups'] = $context[$permission];
1887
1888
	template_inline_permissions();
1889
}
1890
1891
/**
1892
 * Save the permissions of a form containing inline permissions.
1893
 *
1894
 * @internal
1895
 *
1896
 * @param array $permissions The permissions to save
1897
 */
1898
function save_inline_permissions($permissions)
1899
{
1900
	global $context, $smcFunc;
1901
1902
	// No permissions? Not a great deal to do here.
1903
	if (!allowedTo('manage_permissions'))
1904
		return;
1905
1906
	// Almighty session check, verify our ways.
1907
	checkSession();
1908
	validateToken('admin-mp');
1909
1910
	// Check they can't do certain things.
1911
	loadIllegalPermissions();
1912
	if (in_array('bbc_html', $permissions))
1913
		loadIllegalBBCHtmlGroups();
1914
1915
	$insertRows = array();
1916
	foreach ($permissions as $permission)
1917
	{
1918
		if (!isset($_POST[$permission]))
1919
			continue;
1920
1921
		foreach ($_POST[$permission] as $id_group => $value)
1922
		{
1923
			if ($value == 'on' && !empty($context['excluded_permissions'][$permission]) && in_array($id_group, $context['excluded_permissions'][$permission]))
1924
				continue;
1925
1926
			if (in_array($value, array('on', 'deny')) && (empty($context['illegal_permissions']) || !in_array($permission, $context['illegal_permissions'])))
1927
				$insertRows[] = array((int) $id_group, $permission, $value == 'on' ? 1 : 0);
1928
		}
1929
	}
1930
1931
	// Remove the old permissions...
1932
	$smcFunc['db_query']('', '
1933
		DELETE FROM {db_prefix}permissions
1934
		WHERE permission IN ({array_string:permissions})
1935
			' . (empty($context['illegal_permissions']) ? '' : ' AND permission NOT IN ({array_string:illegal_permissions})'),
1936
		array(
1937
			'illegal_permissions' => !empty($context['illegal_permissions']) ? $context['illegal_permissions'] : array(),
1938
			'permissions' => $permissions,
1939
		)
1940
	);
1941
1942
	// ...and replace them with new ones.
1943
	if (!empty($insertRows))
1944
		$smcFunc['db_insert']('insert',
1945
			'{db_prefix}permissions',
1946
			array('id_group' => 'int', 'permission' => 'string', 'add_deny' => 'int'),
1947
			$insertRows,
1948
			array('id_group', 'permission')
1949
		);
1950
1951
	// Do a full child update.
1952
	updateChildPermissions(array(), -1);
1953
1954
	// Make sure $modSettings['board_manager_groups'] is up to date.
1955
	if (!in_array('manage_boards', $context['illegal_permissions']))
1956
		updateBoardManagers();
1957
1958
	updateSettings(array('settings_updated' => time()));
1959
}
1960
1961
/**
1962
 * Load permissions profiles.
1963
 */
1964
function loadPermissionProfiles()
1965
{
1966
	global $context, $txt, $smcFunc;
1967
1968
	$request = $smcFunc['db_query']('', '
1969
		SELECT id_profile, profile_name
1970
		FROM {db_prefix}permission_profiles
1971
		ORDER BY id_profile',
1972
		array(
1973
		)
1974
	);
1975
	$context['profiles'] = array();
1976
	while ($row = $smcFunc['db_fetch_assoc']($request))
1977
	{
1978
		// Format the label nicely.
1979
		if (isset($txt['permissions_profile_' . $row['profile_name']]))
1980
			$name = $txt['permissions_profile_' . $row['profile_name']];
1981
		else
1982
			$name = $row['profile_name'];
1983
1984
		$context['profiles'][$row['id_profile']] = array(
1985
			'id' => $row['id_profile'],
1986
			'name' => $name,
1987
			'can_modify' => $row['id_profile'] == 1 || $row['id_profile'] > 4,
1988
			'unformatted_name' => $row['profile_name'],
1989
		);
1990
	}
1991
	$smcFunc['db_free_result']($request);
1992
}
1993
1994
/**
1995
 * Add/Edit/Delete profiles.
1996
 */
1997
function EditPermissionProfiles()
1998
{
1999
	global $context, $txt, $smcFunc;
2000
2001
	// Setup the template, first for fun.
2002
	$context['page_title'] = $txt['permissions_profile_edit'];
2003
	$context['sub_template'] = 'edit_profiles';
2004
2005
	// If we're creating a new one do it first.
2006
	if (isset($_POST['create']) && trim($_POST['profile_name']) != '')
2007
	{
2008
		checkSession();
2009
		validateToken('admin-mpp');
2010
2011
		$_POST['copy_from'] = (int) $_POST['copy_from'];
2012
		$_POST['profile_name'] = $smcFunc['htmlspecialchars']($_POST['profile_name']);
2013
2014
		// Insert the profile itself.
2015
		$profile_id = $smcFunc['db_insert']('',
2016
			'{db_prefix}permission_profiles',
2017
			array(
2018
				'profile_name' => 'string',
2019
			),
2020
			array(
2021
				$_POST['profile_name'],
2022
			),
2023
			array('id_profile'),
2024
			1
2025
		);
2026
2027
		// Load the permissions from the one it's being copied from.
2028
		$request = $smcFunc['db_query']('', '
2029
			SELECT id_group, permission, add_deny
2030
			FROM {db_prefix}board_permissions
2031
			WHERE id_profile = {int:copy_from}',
2032
			array(
2033
				'copy_from' => $_POST['copy_from'],
2034
			)
2035
		);
2036
		$inserts = array();
2037
		while ($row = $smcFunc['db_fetch_assoc']($request))
2038
			$inserts[] = array($profile_id, $row['id_group'], $row['permission'], $row['add_deny']);
2039
		$smcFunc['db_free_result']($request);
2040
2041
		if (!empty($inserts))
2042
			$smcFunc['db_insert']('insert',
2043
				'{db_prefix}board_permissions',
2044
				array('id_profile' => 'int', 'id_group' => 'int', 'permission' => 'string', 'add_deny' => 'int'),
2045
				$inserts,
2046
				array('id_profile', 'id_group', 'permission')
2047
			);
2048
	}
2049
	// Renaming?
2050
	elseif (isset($_POST['rename']))
2051
	{
2052
		checkSession();
2053
		validateToken('admin-mpp');
2054
2055
		// Just showing the boxes?
2056
		if (!isset($_POST['rename_profile']))
2057
			$context['show_rename_boxes'] = true;
2058
		else
2059
		{
2060
			foreach ($_POST['rename_profile'] as $id => $value)
2061
			{
2062
				$value = $smcFunc['htmlspecialchars']($value);
2063
2064
				if (trim($value) != '' && $id > 4)
2065
					$smcFunc['db_query']('', '
2066
						UPDATE {db_prefix}permission_profiles
2067
						SET profile_name = {string:profile_name}
2068
						WHERE id_profile = {int:current_profile}',
2069
						array(
2070
							'current_profile' => (int) $id,
2071
							'profile_name' => $value,
2072
						)
2073
					);
2074
			}
2075
		}
2076
	}
2077
	// Deleting?
2078
	elseif (isset($_POST['delete']) && !empty($_POST['delete_profile']))
2079
	{
2080
		checkSession();
2081
		validateToken('admin-mpp');
2082
2083
		$profiles = array();
2084
		foreach ($_POST['delete_profile'] as $profile)
2085
			if ($profile > 4)
2086
				$profiles[] = (int) $profile;
2087
2088
		// Verify it's not in use...
2089
		$request = $smcFunc['db_query']('', '
2090
			SELECT id_board
2091
			FROM {db_prefix}boards
2092
			WHERE id_profile IN ({array_int:profile_list})
2093
			LIMIT 1',
2094
			array(
2095
				'profile_list' => $profiles,
2096
			)
2097
		);
2098
		if ($smcFunc['db_num_rows']($request) != 0)
2099
			fatal_lang_error('no_access', false);
2100
		$smcFunc['db_free_result']($request);
2101
2102
		// Oh well, delete.
2103
		$smcFunc['db_query']('', '
2104
			DELETE FROM {db_prefix}permission_profiles
2105
			WHERE id_profile IN ({array_int:profile_list})',
2106
			array(
2107
				'profile_list' => $profiles,
2108
			)
2109
		);
2110
	}
2111
2112
	// Clearly, we'll need this!
2113
	loadPermissionProfiles();
2114
2115
	// Work out what ones are in use.
2116
	$request = $smcFunc['db_query']('', '
2117
		SELECT id_profile, COUNT(*) AS board_count
2118
		FROM {db_prefix}boards
2119
		GROUP BY id_profile',
2120
		array(
2121
		)
2122
	);
2123
	while ($row = $smcFunc['db_fetch_assoc']($request))
2124
		if (isset($context['profiles'][$row['id_profile']]))
2125
		{
2126
			$context['profiles'][$row['id_profile']]['in_use'] = true;
2127
			$context['profiles'][$row['id_profile']]['boards'] = $row['board_count'];
2128
			$context['profiles'][$row['id_profile']]['boards_text'] = $row['board_count'] > 1 ? sprintf($txt['permissions_profile_used_by_many'], $row['board_count']) : $txt['permissions_profile_used_by_' . ($row['board_count'] ? 'one' : 'none')];
2129
		}
2130
	$smcFunc['db_free_result']($request);
2131
2132
	// What can we do with these?
2133
	$context['can_edit_something'] = false;
2134
	foreach ($context['profiles'] as $id => $profile)
2135
	{
2136
		// Can't delete special ones.
2137
		$context['profiles'][$id]['can_edit'] = isset($txt['permissions_profile_' . $profile['unformatted_name']]) ? false : true;
2138
		if ($context['profiles'][$id]['can_edit'])
2139
			$context['can_edit_something'] = true;
2140
2141
		// You can only delete it if you can edit it AND it's not in use.
2142
		$context['profiles'][$id]['can_delete'] = $context['profiles'][$id]['can_edit'] && empty($profile['in_use']) ? true : false;
2143
	}
2144
2145
	createToken('admin-mpp');
2146
}
2147
2148
/**
2149
 * This function updates the permissions of any groups based off this group.
2150
 *
2151
 * @param null|array $parents The parent groups
2152
 * @param null|int $profile the ID of a permissions profile to update
2153
 * @return void|false Returns nothing if successful or false if there are no child groups to update
2154
 */
2155
function updateChildPermissions($parents, $profile = null)
2156
{
2157
	global $smcFunc;
2158
2159
	// All the parent groups to sort out.
2160
	if (!is_array($parents))
2161
		$parents = array($parents);
2162
2163
	// Find all the children of this group.
2164
	$request = $smcFunc['db_query']('', '
2165
		SELECT id_parent, id_group
2166
		FROM {db_prefix}membergroups
2167
		WHERE id_parent != {int:not_inherited}
2168
			' . (empty($parents) ? '' : 'AND id_parent IN ({array_int:parent_list})'),
2169
		array(
2170
			'parent_list' => $parents,
2171
			'not_inherited' => -2,
2172
		)
2173
	);
2174
	$children = array();
2175
	$parents = array();
2176
	$child_groups = array();
2177
	while ($row = $smcFunc['db_fetch_assoc']($request))
2178
	{
2179
		$children[$row['id_parent']][] = $row['id_group'];
2180
		$child_groups[] = $row['id_group'];
2181
		$parents[] = $row['id_parent'];
2182
	}
2183
	$smcFunc['db_free_result']($request);
2184
2185
	$parents = array_unique($parents);
2186
2187
	// Not a sausage, or a child?
2188
	if (empty($children))
2189
		return false;
2190
2191
	// First off, are we doing general permissions?
2192
	if ($profile < 1 || $profile === null)
2193
	{
2194
		// Fetch all the parent permissions.
2195
		$request = $smcFunc['db_query']('', '
2196
			SELECT id_group, permission, add_deny
2197
			FROM {db_prefix}permissions
2198
			WHERE id_group IN ({array_int:parent_list})',
2199
			array(
2200
				'parent_list' => $parents,
2201
			)
2202
		);
2203
		$permissions = array();
2204
		while ($row = $smcFunc['db_fetch_assoc']($request))
2205
			foreach ($children[$row['id_group']] as $child)
2206
				$permissions[] = array($child, $row['permission'], $row['add_deny']);
2207
		$smcFunc['db_free_result']($request);
2208
2209
		$smcFunc['db_query']('', '
2210
			DELETE FROM {db_prefix}permissions
2211
			WHERE id_group IN ({array_int:child_groups})',
2212
			array(
2213
				'child_groups' => $child_groups,
2214
			)
2215
		);
2216
2217
		// Finally insert.
2218
		if (!empty($permissions))
2219
		{
2220
			$smcFunc['db_insert']('insert',
2221
				'{db_prefix}permissions',
2222
				array('id_group' => 'int', 'permission' => 'string', 'add_deny' => 'int'),
2223
				$permissions,
2224
				array('id_group', 'permission')
2225
			);
2226
		}
2227
	}
2228
2229
	// Then, what about board profiles?
2230
	if ($profile != -1)
2231
	{
2232
		$profileQuery = $profile === null ? '' : ' AND id_profile = {int:current_profile}';
2233
2234
		// Again, get all the parent permissions.
2235
		$request = $smcFunc['db_query']('', '
2236
			SELECT id_profile, id_group, permission, add_deny
2237
			FROM {db_prefix}board_permissions
2238
			WHERE id_group IN ({array_int:parent_groups})
2239
				' . $profileQuery,
2240
			array(
2241
				'parent_groups' => $parents,
2242
				'current_profile' => $profile !== null && $profile ? $profile : 1,
2243
			)
2244
		);
2245
		$permissions = array();
2246
		while ($row = $smcFunc['db_fetch_assoc']($request))
2247
			foreach ($children[$row['id_group']] as $child)
2248
				$permissions[] = array($child, $row['id_profile'], $row['permission'], $row['add_deny']);
2249
		$smcFunc['db_free_result']($request);
2250
2251
		$smcFunc['db_query']('', '
2252
			DELETE FROM {db_prefix}board_permissions
2253
			WHERE id_group IN ({array_int:child_groups})
2254
				' . $profileQuery,
2255
			array(
2256
				'child_groups' => $child_groups,
2257
				'current_profile' => $profile !== null && $profile ? $profile : 1,
2258
			)
2259
		);
2260
2261
		// Do the insert.
2262
		if (!empty($permissions))
2263
		{
2264
			$smcFunc['db_insert']('insert',
2265
				'{db_prefix}board_permissions',
2266
				array('id_group' => 'int', 'id_profile' => 'int', 'permission' => 'string', 'add_deny' => 'int'),
2267
				$permissions,
2268
				array('id_group', 'id_profile', 'permission')
2269
			);
2270
		}
2271
	}
2272
}
2273
2274
/**
2275
 * Load permissions someone cannot grant.
2276
 */
2277
function loadIllegalPermissions()
2278
{
2279
	global $context;
2280
2281
	$context['illegal_permissions'] = array();
2282
	if (!allowedTo('admin_forum'))
2283
	{
2284
		$context['illegal_permissions'][] = 'admin_forum';
2285
		$context['illegal_permissions'][] = 'bbc_html';
2286
	}
2287
	if (!allowedTo('manage_membergroups'))
2288
		$context['illegal_permissions'][] = 'manage_membergroups';
2289
	if (!allowedTo('manage_permissions'))
2290
		$context['illegal_permissions'][] = 'manage_permissions';
2291
2292
	call_integration_hook('integrate_load_illegal_permissions');
2293
}
2294
2295
/**
2296
 * Loads the permissions that can not be given to guests.
2297
 * Stores the permissions in $context['non_guest_permissions'].
2298
 * Also populates $context['permissions_excluded'] with the info.
2299
 */
2300
function loadIllegalGuestPermissions()
2301
{
2302
	global $context;
2303
2304
	$context['non_guest_permissions'] = array(
2305
		'access_mod_center',
2306
		'admin_forum',
2307
		'announce_topic',
2308
		'approve_posts',
2309
		'bbc_html',
2310
		'calendar_edit',
2311
		'delete',
2312
		'delete_replies',
2313
		'edit_news',
2314
		'issue_warning',
2315
		'likes_like',
2316
		'lock',
2317
		'make_sticky',
2318
		'manage_attachments',
2319
		'manage_bans',
2320
		'manage_boards',
2321
		'manage_membergroups',
2322
		'manage_permissions',
2323
		'manage_smileys',
2324
		'merge_any',
2325
		'moderate_board',
2326
		'moderate_forum',
2327
		'modify',
2328
		'modify_replies',
2329
		'move',
2330
		'pm_autosave_draft',
2331
		'pm_draft',
2332
		'pm_read',
2333
		'pm_send',
2334
		'poll_add',
2335
		'poll_edit',
2336
		'poll_lock',
2337
		'poll_remove',
2338
		'post_autosave_draft',
2339
		'post_draft',
2340
		'profile_blurb',
2341
		'profile_displayed_name',
2342
		'profile_extra',
2343
		'profile_forum',
2344
		'profile_identity',
2345
		'profile_website',
2346
		'profile_password',
2347
		'profile_remove',
2348
		'profile_remote_avatar',
2349
		'profile_server_avatar',
2350
		'profile_signature',
2351
		'profile_title',
2352
		'profile_upload_avatar',
2353
		'view_warning_own',
2354
		'remove',
2355
		'report_any',
2356
		'report_user',
2357
		'send_mail',
2358
		'split_any',
2359
	);
2360
2361
	call_integration_hook('integrate_load_illegal_guest_permissions');
2362
2363
	// Also add this info to $context['permissions_excluded'] to make life easier for everyone
2364
	foreach ($context['non_guest_permissions'] as $permission)
2365
	{
2366
		if (empty($context['permissions_excluded'][$permission]) || !in_array($permission, $context['permissions_excluded'][$permission]))
2367
			$context['permissions_excluded'][$permission][] = -1;
2368
	}
2369
}
2370
2371
/**
2372
 * Loads a list of membergroups who cannot be granted the bbc_html permission.
2373
 * Stores the groups in $context['permissions_excluded']['bbc_html'].
2374
 */
2375
function loadIllegalBBCHtmlGroups()
2376
{
2377
	global $context, $smcFunc;
2378
2379
	$context['permissions_excluded']['bbc_html'] = array(-1, 0);
2380
2381
	$request = $smcFunc['db_query']('', '
2382
		SELECT id_group
2383
		FROM {db_prefix}membergroups
2384
		WHERE id_group != 1 AND id_group NOT IN (
2385
			SELECT DISTINCT id_group
2386
			FROM {db_prefix}permissions
2387
			WHERE permission IN ({array_string:permissions})
2388
				AND add_deny = {int:add}
2389
		)',
2390
		array(
2391
			'permissions' => array('admin_forum', 'manage_membergroups', 'manage_permissions'),
2392
			'add' => 1,
2393
		)
2394
	);
2395
	while ($row = $smcFunc['db_fetch_assoc']($request))
2396
		$context['permissions_excluded']['bbc_html'][] = $row['id_group'];
2397
	$smcFunc['db_free_result']($request);
2398
2399
	$context['permissions_excluded']['bbc_html'] = array_unique($context['permissions_excluded']['bbc_html']);
2400
}
2401
2402
/**
2403
 * Removes the bbc_html permission from anyone who shouldn't have it
2404
 *
2405
 * @param bool $reload Before acting, refresh the list of membergroups who cannot be granted the bbc_html permission
2406
 */
2407
function removeIllegalBBCHtmlPermission($reload = false)
2408
{
2409
	global $context, $smcFunc;
2410
2411
	if (empty($context['permissions_excluded']['bbc_html']) || $reload)
2412
		loadIllegalBBCHtmlGroups();
2413
2414
	$smcFunc['db_query']('', '
2415
		DELETE FROM {db_prefix}permissions
2416
		WHERE id_group IN ({array_int:current_group_list})
2417
			AND permission = {string:current_permission}
2418
			AND add_deny = {int:add}',
2419
		array(
2420
			'current_group_list' => $context['permissions_excluded']['bbc_html'],
2421
			'current_permission' => 'bbc_html',
2422
			'add' => 1,
2423
		)
2424
	);
2425
}
2426
2427
/**
2428
 * Makes sure $modSettings['board_manager_groups'] is up to date.
2429
 */
2430
function updateBoardManagers()
2431
{
2432
	global $sourcedir;
2433
2434
	require_once($sourcedir . '/Subs-Members.php');
2435
	$board_managers = groupsAllowedTo('manage_boards', null);
2436
	$board_managers = implode(',', $board_managers['allowed']);
2437
2438
	updateSettings(array('board_manager_groups' => $board_managers), true);
2439
}
2440
2441
/**
2442
 * Present a nice way of applying post moderation.
2443
 */
2444
function ModifyPostModeration()
2445
{
2446
	global $context, $txt, $smcFunc, $modSettings, $sourcedir;
2447
2448
	// Just in case.
2449
	checkSession('get');
2450
2451
	$context['page_title'] = $txt['permissions_post_moderation'];
2452
	$context['sub_template'] = 'postmod_permissions';
2453
	$context['current_profile'] = isset($_REQUEST['pid']) ? (int) $_REQUEST['pid'] : 1;
2454
2455
	// Load all the permission profiles.
2456
	loadPermissionProfiles();
2457
2458
	// Mappings, our key => array(can_do_moderated, can_do_all)
2459
	$mappings = array(
2460
		'new_topic' => array('post_new', 'post_unapproved_topics'),
2461
		'replies_own' => array('post_reply_own', 'post_unapproved_replies_own'),
2462
		'replies_any' => array('post_reply_any', 'post_unapproved_replies_any'),
2463
		'attachment' => array('post_attachment', 'post_unapproved_attachments'),
2464
	);
2465
2466
	call_integration_hook('integrate_post_moderation_mapping', array(&$mappings));
2467
2468
	// Start this with the guests/members.
2469
	$context['profile_groups'] = array(
2470
		-1 => array(
2471
			'id' => -1,
2472
			'name' => $txt['membergroups_guests'],
2473
			'color' => '',
2474
			'new_topic' => 'disallow',
2475
			'replies_own' => 'disallow',
2476
			'replies_any' => 'disallow',
2477
			'attachment' => 'disallow',
2478
			'children' => array(),
2479
		),
2480
		0 => array(
2481
			'id' => 0,
2482
			'name' => $txt['membergroups_members'],
2483
			'color' => '',
2484
			'new_topic' => 'disallow',
2485
			'replies_own' => 'disallow',
2486
			'replies_any' => 'disallow',
2487
			'attachment' => 'disallow',
2488
			'children' => array(),
2489
		),
2490
	);
2491
2492
	// Load the groups.
2493
	$request = $smcFunc['db_query']('', '
2494
		SELECT id_group, group_name, online_color, id_parent
2495
		FROM {db_prefix}membergroups
2496
		WHERE id_group != {int:admin_group}
2497
			' . (empty($modSettings['permission_enable_postgroups']) ? ' AND min_posts = {int:min_posts}' : '') . '
2498
		ORDER BY id_parent ASC',
2499
		array(
2500
			'admin_group' => 1,
2501
			'min_posts' => -1,
2502
		)
2503
	);
2504
	while ($row = $smcFunc['db_fetch_assoc']($request))
2505
	{
2506
		if ($row['id_parent'] == -2)
2507
		{
2508
			$context['profile_groups'][$row['id_group']] = array(
2509
				'id' => $row['id_group'],
2510
				'name' => $row['group_name'],
2511
				'color' => $row['online_color'],
2512
				'new_topic' => 'disallow',
2513
				'replies_own' => 'disallow',
2514
				'replies_any' => 'disallow',
2515
				'attachment' => 'disallow',
2516
				'children' => array(),
2517
			);
2518
		}
2519
		elseif (isset($context['profile_groups'][$row['id_parent']]))
2520
			$context['profile_groups'][$row['id_parent']]['children'][] = $row['group_name'];
2521
	}
2522
	$smcFunc['db_free_result']($request);
2523
2524
	// What are the permissions we are querying?
2525
	$all_permissions = array();
2526
	foreach ($mappings as $perm_set)
2527
		$all_permissions = array_merge($all_permissions, $perm_set);
2528
2529
	// If we're saving the changes then do just that - save them.
2530
	if (!empty($_POST['save_changes']) && ($context['current_profile'] == 1 || $context['current_profile'] > 4))
2531
	{
2532
		validateToken('admin-mppm');
2533
2534
		// First, are we saving a new value for enabled post moderation?
2535
		$new_setting = !empty($_POST['postmod_active']);
2536
		if ($new_setting != $modSettings['postmod_active'])
2537
		{
2538
			if ($new_setting)
2539
			{
2540
				// Turning it on. This seems easy enough.
2541
				updateSettings(array('postmod_active' => 1));
2542
			}
2543
			else
2544
			{
2545
				// Turning it off. Not so straightforward. We have to turn off warnings to moderation level, and make everything approved.
2546
				updateSettings(array(
2547
					'postmod_active' => 0,
2548
					'warning_moderate' => 0,
2549
				));
2550
2551
				require_once($sourcedir . '/PostModeration.php');
2552
				approveAllData();
2553
			}
2554
		}
2555
		elseif ($modSettings['postmod_active'])
2556
		{
2557
			// We're not saving a new setting - and if it's still enabled we have more work to do.
2558
2559
			// Start by deleting all the permissions relevant.
2560
			$smcFunc['db_query']('', '
2561
				DELETE FROM {db_prefix}board_permissions
2562
				WHERE id_profile = {int:current_profile}
2563
					AND permission IN ({array_string:permissions})
2564
					AND id_group IN ({array_int:profile_group_list})',
2565
				array(
2566
					'profile_group_list' => array_keys($context['profile_groups']),
2567
					'current_profile' => $context['current_profile'],
2568
					'permissions' => $all_permissions,
2569
				)
2570
			);
2571
2572
			// Do it group by group.
2573
			$new_permissions = array();
2574
			foreach ($context['profile_groups'] as $id => $group)
2575
			{
2576
				foreach ($mappings as $index => $data)
2577
				{
2578
					if (isset($_POST[$index][$group['id']]))
2579
					{
2580
						if ($_POST[$index][$group['id']] == 'allow')
2581
						{
2582
							// Give them both sets for fun.
2583
							$new_permissions[] = array($context['current_profile'], $group['id'], $data[0], 1);
2584
							$new_permissions[] = array($context['current_profile'], $group['id'], $data[1], 1);
2585
						}
2586
						elseif ($_POST[$index][$group['id']] == 'moderate')
2587
							$new_permissions[] = array($context['current_profile'], $group['id'], $data[1], 1);
2588
					}
2589
				}
2590
			}
2591
2592
			// Insert new permissions.
2593
			if (!empty($new_permissions))
2594
				$smcFunc['db_insert']('',
2595
					'{db_prefix}board_permissions',
2596
					array('id_profile' => 'int', 'id_group' => 'int', 'permission' => 'string', 'add_deny' => 'int'),
2597
					$new_permissions,
2598
					array('id_profile', 'id_group', 'permission')
2599
				);
2600
		}
2601
	}
2602
2603
	// Now get all the permissions!
2604
	$request = $smcFunc['db_query']('', '
2605
		SELECT id_group, permission, add_deny
2606
		FROM {db_prefix}board_permissions
2607
		WHERE id_profile = {int:current_profile}
2608
			AND permission IN ({array_string:permissions})
2609
			AND id_group IN ({array_int:profile_group_list})',
2610
		array(
2611
			'profile_group_list' => array_keys($context['profile_groups']),
2612
			'current_profile' => $context['current_profile'],
2613
			'permissions' => $all_permissions,
2614
		)
2615
	);
2616
	while ($row = $smcFunc['db_fetch_assoc']($request))
2617
	{
2618
		foreach ($mappings as $key => $data)
2619
		{
2620
			foreach ($data as $index => $perm)
2621
			{
2622
				if ($perm == $row['permission'])
2623
				{
2624
					// Only bother if it's not denied.
2625
					if ($row['add_deny'])
2626
					{
2627
						// Full allowance?
2628
						if ($index == 0)
2629
							$context['profile_groups'][$row['id_group']][$key] = 'allow';
2630
						// Otherwise only bother with moderate if not on allow.
2631
						elseif ($context['profile_groups'][$row['id_group']][$key] != 'allow')
2632
							$context['profile_groups'][$row['id_group']][$key] = 'moderate';
2633
					}
2634
				}
2635
			}
2636
		}
2637
	}
2638
	$smcFunc['db_free_result']($request);
2639
2640
	createToken('admin-mppm');
2641
}
2642
2643
?>