Failed Conditions
Branch release-2.1 (4e22cf)
by Rick
06:39
created

ManageMembergroups.php ➔ ModifyMembergroupsettings()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 37
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 18
nc 2
nop 0
dl 0
loc 37
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is concerned with anything in the Manage Membergroups admin screen.
5
 *
6
 * Simple Machines Forum (SMF)
7
 *
8
 * @package SMF
9
 * @author Simple Machines http://www.simplemachines.org
10
 * @copyright 2017 Simple Machines and individual contributors
11
 * @license http://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1 Beta 4
14
 */
15
16
if (!defined('SMF'))
17
	die('No direct access...');
18
19
20
/**
21
 * Main dispatcher, the entrance point for all 'Manage Membergroup' actions.
22
 * It forwards to a function based on the given subaction, default being subaction 'index', or, without manage_membergroup
23
 * permissions, then 'settings'.
24
 * Called by ?action=admin;area=membergroups.
25
 * Requires the manage_membergroups or the admin_forum permission.
26
 *
27
 * @uses ManageMembergroups template.
28
 * @uses ManageMembers language file.
29
*/
30
function ModifyMembergroups()
31
{
32
	global $context, $txt, $sourcedir;
33
34
	$subActions = array(
35
		'add' => array('AddMembergroup', 'manage_membergroups'),
36
		'delete' => array('DeleteMembergroup', 'manage_membergroups'),
37
		'edit' => array('EditMembergroup', 'manage_membergroups'),
38
		'index' => array('MembergroupIndex', 'manage_membergroups'),
39
		'members' => array('MembergroupMembers', 'manage_membergroups', 'Groups.php'),
40
		'settings' => array('ModifyMembergroupsettings', 'admin_forum'),
41
	);
42
43
	// Default to sub action 'index' or 'settings' depending on permissions.
44
	$_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : (allowedTo('manage_membergroups') ? 'index' : 'settings');
45
46
	// Is it elsewhere?
47
	if (isset($subActions[$_REQUEST['sa']][2]))
48
		require_once($sourcedir . '/' . $subActions[$_REQUEST['sa']][2]);
49
50
	// Do the permission check, you might not be allowed her.
51
	isAllowedTo($subActions[$_REQUEST['sa']][1]);
52
53
	// Language and template stuff, the usual.
54
	loadLanguage('ManageMembers');
55
	loadTemplate('ManageMembergroups');
56
57
	// Setup the admin tabs.
58
	$context[$context['admin_menu_name']]['tab_data'] = array(
59
		'title' => $txt['membergroups_title'],
60
		'help' => 'membergroups',
61
		'description' => $txt['membergroups_description'],
62
	);
63
64
	call_integration_hook('integrate_manage_membergroups', array(&$subActions));
65
66
	// Call the right function.
67
	call_helper($subActions[$_REQUEST['sa']][0]);
68
}
69
70
/**
71
 * Shows an overview of the current membergroups.
72
 * Called by ?action=admin;area=membergroups.
73
 * Requires the manage_membergroups permission.
74
 * Splits the membergroups in regular ones and post count based groups.
75
 * It also counts the number of members part of each membergroup.
76
 *
77
 * @uses ManageMembergroups template, main.
78
 */
79
function MembergroupIndex()
80
{
81
	global $txt, $scripturl, $context, $sourcedir;
82
83
	$context['page_title'] = $txt['membergroups_title'];
84
85
	// The first list shows the regular membergroups.
86
	$listOptions = array(
87
		'id' => 'regular_membergroups_list',
88
		'title' => $txt['membergroups_regular'],
89
		'base_href' => $scripturl . '?action=admin;area=membergroups' . (isset($_REQUEST['sort2']) ? ';sort2=' . urlencode($_REQUEST['sort2']) : ''),
90
		'default_sort_col' => 'name',
91
		'get_items' => array(
92
			'file' => $sourcedir . '/Subs-Membergroups.php',
93
			'function' => 'list_getMembergroups',
94
			'params' => array(
95
				'regular',
96
			),
97
		),
98
		'columns' => array(
99
			'name' => array(
100
				'header' => array(
101
					'value' => $txt['membergroups_name'],
102
				),
103
				'data' => array(
104
					'function' => function($rowData) use ($scripturl)
105
					{
106
						// Since the moderator group has no explicit members, no link is needed.
107
						if ($rowData['id_group'] == 3)
108
							$group_name = $rowData['group_name'];
109 View Code Duplication
						else
110
						{
111
							$color_style = empty($rowData['online_color']) ? '' : sprintf(' style="color: %1$s;"', $rowData['online_color']);
112
							$group_name = sprintf('<a href="%1$s?action=admin;area=membergroups;sa=members;group=%2$d"%3$s>%4$s</a>', $scripturl, $rowData['id_group'], $color_style, $rowData['group_name']);
113
						}
114
115
						// Add a help option for moderator and administrator.
116 View Code Duplication
						if ($rowData['id_group'] == 1)
117
							$group_name .= sprintf(' (<a href="%1$s?action=helpadmin;help=membergroup_administrator" onclick="return reqOverlayDiv(this.href);">?</a>)', $scripturl);
118
						elseif ($rowData['id_group'] == 3)
119
							$group_name .= sprintf(' (<a href="%1$s?action=helpadmin;help=membergroup_moderator" onclick="return reqOverlayDiv(this.href);">?</a>)', $scripturl);
120
121
						return $group_name;
122
					},
123
				),
124
				'sort' => array(
125
					'default' => 'CASE WHEN mg.id_group < 4 THEN mg.id_group ELSE 4 END, mg.group_name',
126
					'reverse' => 'CASE WHEN mg.id_group < 4 THEN mg.id_group ELSE 4 END, mg.group_name DESC',
127
				),
128
			),
129
			'icons' => array(
130
				'header' => array(
131
					'value' => $txt['membergroups_icons'],
132
				),
133
				'data' => array(
134
					'db' => 'icons',
135
				),
136
				'sort' => array(
137
					'default' => 'mg.icons',
138
					'reverse' => 'mg.icons DESC',
139
				)
140
			),
141
			'members' => array(
142
				'header' => array(
143
					'value' => $txt['membergroups_members_top'],
144
					'class' => 'centercol',
145
				),
146
				'data' => array(
147 View Code Duplication
					'function' => function($rowData) use ($txt)
148
					{
149
						// No explicit members for the moderator group.
150
						return $rowData['id_group'] == 3 ? $txt['membergroups_guests_na'] : comma_format($rowData['num_members']);
151
					},
152
					'class' => 'centercol',
153
				),
154
				'sort' => array(
155
					'default' => 'CASE WHEN mg.id_group < 4 THEN mg.id_group ELSE 4 END, 1',
156
					'reverse' => 'CASE WHEN mg.id_group < 4 THEN mg.id_group ELSE 4 END, 1 DESC',
157
				),
158
			),
159
			'modify' => array(
160
				'header' => array(
161
					'value' => $txt['modify'],
162
					'class' => 'centercol',
163
				),
164
				'data' => array(
165
					'sprintf' => array(
166
						'format' => '<a href="' . $scripturl . '?action=admin;area=membergroups;sa=edit;group=%1$d">' . $txt['membergroups_modify'] . '</a>',
167
						'params' => array(
168
							'id_group' => false,
169
						),
170
					),
171
					'class' => 'centercol',
172
				),
173
			),
174
		),
175
		'additional_rows' => array(
176
			array(
177
				'position' => 'above_table_headers',
178
				'value' => '<a class="button_link" href="' . $scripturl . '?action=admin;area=membergroups;sa=add;generalgroup">' . $txt['membergroups_add_group'] . '</a>',
179
			),
180
			array(
181
				'position' => 'below_table_data',
182
				'value' => '<a class="button_link" href="' . $scripturl . '?action=admin;area=membergroups;sa=add;generalgroup">' . $txt['membergroups_add_group'] . '</a>',
183
			),
184
		),
185
	);
186
187
	require_once($sourcedir . '/Subs-List.php');
188
	createList($listOptions);
189
190
	// The second list shows the post count based groups.
191
	$listOptions = array(
192
		'id' => 'post_count_membergroups_list',
193
		'title' => $txt['membergroups_post'],
194
		'base_href' => $scripturl . '?action=admin;area=membergroups' . (isset($_REQUEST['sort']) ? ';sort=' . urlencode($_REQUEST['sort']) : ''),
195
		'default_sort_col' => 'required_posts',
196
		'request_vars' => array(
197
			'sort' => 'sort2',
198
			'desc' => 'desc2',
199
		),
200
		'get_items' => array(
201
			'file' => $sourcedir . '/Subs-Membergroups.php',
202
			'function' => 'list_getMembergroups',
203
			'params' => array(
204
				'post_count',
205
			),
206
		),
207
		'columns' => array(
208
			'name' => array(
209
				'header' => array(
210
					'value' => $txt['membergroups_name'],
211
				),
212
				'data' => array(
213
					'function' => function($rowData) use ($scripturl)
214
					{
215
						$colorStyle = empty($rowData['online_color']) ? '' : sprintf(' style="color: %1$s;"', $rowData['online_color']);
216
						return sprintf('<a href="%1$s?action=moderate;area=viewgroups;sa=members;group=%2$d"%3$s>%4$s</a>', $scripturl, $rowData['id_group'], $colorStyle, $rowData['group_name']);
217
					},
218
				),
219
				'sort' => array(
220
					'default' => 'mg.group_name',
221
					'reverse' => 'mg.group_name DESC',
222
				),
223
			),
224
			'icons' => array(
225
				'header' => array(
226
					'value' => $txt['membergroups_icons'],
227
				),
228
				'data' => array(
229
					'db' => 'icons',
230
				),
231
				'sort' => array(
232
					'default' => 'CASE WHEN mg.id_group < 4 THEN mg.id_group ELSE 4 END, icons',
233
					'reverse' => 'CASE WHEN mg.id_group < 4 THEN mg.id_group ELSE 4 END, icons DESC',
234
				)
235
			),
236
			'members' => array(
237
				'header' => array(
238
					'value' => $txt['membergroups_members_top'],
239
					'class' => 'centercol',
240
				),
241
				'data' => array(
242
					'db' => 'num_members',
243
					'class' => 'centercol',
244
				),
245
				'sort' => array(
246
					'default' => '1 DESC',
247
					'reverse' => '1',
248
				),
249
			),
250
			'required_posts' => array(
251
				'header' => array(
252
					'value' => $txt['membergroups_min_posts'],
253
					'class' => 'centercol',
254
				),
255
				'data' => array(
256
					'db' => 'min_posts',
257
					'class' => 'centercol',
258
				),
259
				'sort' => array(
260
					'default' => 'mg.min_posts',
261
					'reverse' => 'mg.min_posts DESC',
262
				),
263
			),
264
			'modify' => array(
265
				'header' => array(
266
					'value' => $txt['modify'],
267
					'class' => 'centercol',
268
				),
269
				'data' => array(
270
					'sprintf' => array(
271
						'format' => '<a href="' . $scripturl . '?action=admin;area=membergroups;sa=edit;group=%1$d">' . $txt['membergroups_modify'] . '</a>',
272
						'params' => array(
273
							'id_group' => false,
274
						),
275
					),
276
					'class' => 'centercol',
277
				),
278
			),
279
		),
280
		'additional_rows' => array(
281
			array(
282
				'position' => 'below_table_data',
283
				'value' => '<a class="button_link" href="' . $scripturl . '?action=admin;area=membergroups;sa=add;postgroup">' . $txt['membergroups_add_group'] . '</a>',
284
			),
285
		),
286
	);
287
288
	createList($listOptions);
289
}
290
291
/**
292
 * This function handles adding a membergroup and setting some initial properties.
293
 * Called by ?action=admin;area=membergroups;sa=add.
294
 * It requires the manage_membergroups permission.
295
 * Allows to use a predefined permission profile or copy one from another group.
296
 * Redirects to action=admin;area=membergroups;sa=edit;group=x.
297
 *
298
 * @uses the new_group sub template of ManageMembergroups.
299
 */
300
function AddMembergroup()
301
{
302
	global $context, $txt, $sourcedir, $modSettings, $smcFunc;
303
304
	// A form was submitted, we can start adding.
305
	if (isset($_POST['group_name']) && trim($_POST['group_name']) != '')
306
	{
307
		checkSession();
308
		validateToken('admin-mmg');
309
310
		$postCountBasedGroup = isset($_POST['min_posts']) && (!isset($_POST['postgroup_based']) || !empty($_POST['postgroup_based']));
311
		$_POST['group_type'] = !isset($_POST['group_type']) || $_POST['group_type'] < 0 || $_POST['group_type'] > 3 || ($_POST['group_type'] == 1 && !allowedTo('admin_forum')) ? 0 : (int) $_POST['group_type'];
312
313
		call_integration_hook('integrate_pre_add_membergroup', array());
314
315
		$id_group = $smcFunc['db_insert']('',
316
			'{db_prefix}membergroups',
317
			array(
318
				'description' => 'string', 'group_name' => 'string-80', 'min_posts' => 'int',
319
				'icons' => 'string', 'online_color' => 'string', 'group_type' => 'int',
320
			),
321
			array(
322
				'', $smcFunc['htmlspecialchars']($_POST['group_name'], ENT_QUOTES), ($postCountBasedGroup ? (int) $_POST['min_posts'] : '-1'),
323
				'1#icon.png', '', $_POST['group_type'],
324
			),
325
			array('id_group'),
326
			1
327
		);
328
329
		call_integration_hook('integrate_add_membergroup', array($id_group, $postCountBasedGroup));
330
331
		// Update the post groups now, if this is a post group!
332
		if (isset($_POST['min_posts']))
333
			updateStats('postgroups');
334
335
		// You cannot set permissions for post groups if they are disabled.
336
		if ($postCountBasedGroup && empty($modSettings['permission_enable_postgroups']))
337
			$_POST['perm_type'] = '';
338
339
		if ($_POST['perm_type'] == 'predefined')
340
		{
341
			// Set default permission level.
342
			require_once($sourcedir . '/ManagePermissions.php');
343
			setPermissionLevel($_POST['level'], $id_group, 'null');
344
		}
345
		// Copy or inherit the permissions!
346
		elseif ($_POST['perm_type'] == 'copy' || $_POST['perm_type'] == 'inherit')
347
		{
348
			$copy_id = $_POST['perm_type'] == 'copy' ? (int) $_POST['copyperm'] : (int) $_POST['inheritperm'];
349
350
			// Are you a powerful admin?
351 View Code Duplication
			if (!allowedTo('admin_forum'))
352
			{
353
				$request = $smcFunc['db_query']('', '
354
					SELECT group_type
355
					FROM {db_prefix}membergroups
356
					WHERE id_group = {int:copy_from}
357
					LIMIT {int:limit}',
358
					array(
359
						'copy_from' => $copy_id,
360
						'limit' => 1,
361
					)
362
				);
363
				list ($copy_type) = $smcFunc['db_fetch_row']($request);
364
				$smcFunc['db_free_result']($request);
365
366
				// Protected groups are... well, protected!
0 ignored issues
show
Unused Code Comprehensibility introduced by
39% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
367
				if ($copy_type == 1)
368
					fatal_lang_error('membergroup_does_not_exist');
369
			}
370
371
			// Don't allow copying of a real priviledged person!
372
			require_once($sourcedir . '/ManagePermissions.php');
373
			loadIllegalPermissions();
374
375
			$request = $smcFunc['db_query']('', '
376
				SELECT permission, add_deny
377
				FROM {db_prefix}permissions
378
				WHERE id_group = {int:copy_from}',
379
				array(
380
					'copy_from' => $copy_id,
381
				)
382
			);
383
			$inserts = array();
384
			while ($row = $smcFunc['db_fetch_assoc']($request))
385
			{
386
				if (empty($context['illegal_permissions']) || !in_array($row['permission'], $context['illegal_permissions']))
387
					$inserts[] = array($id_group, $row['permission'], $row['add_deny']);
388
			}
389
			$smcFunc['db_free_result']($request);
390
391
			if (!empty($inserts))
392
				$smcFunc['db_insert']('insert',
393
					'{db_prefix}permissions',
394
					array('id_group' => 'int', 'permission' => 'string', 'add_deny' => 'int'),
395
					$inserts,
396
					array('id_group', 'permission')
397
				);
398
399
			$request = $smcFunc['db_query']('', '
400
				SELECT id_profile, permission, add_deny
401
				FROM {db_prefix}board_permissions
402
				WHERE id_group = {int:copy_from}',
403
				array(
404
					'copy_from' => $copy_id,
405
				)
406
			);
407
			$inserts = array();
408
			while ($row = $smcFunc['db_fetch_assoc']($request))
409
				$inserts[] = array($id_group, $row['id_profile'], $row['permission'], $row['add_deny']);
410
			$smcFunc['db_free_result']($request);
411
412 View Code Duplication
			if (!empty($inserts))
413
				$smcFunc['db_insert']('insert',
414
					'{db_prefix}board_permissions',
415
					array('id_group' => 'int', 'id_profile' => 'int', 'permission' => 'string', 'add_deny' => 'int'),
416
					$inserts,
417
					array('id_group', 'id_profile', 'permission')
418
				);
419
420
			// Also get some membergroup information if we're copying and not copying from guests...
421
			if ($copy_id > 0 && $_POST['perm_type'] == 'copy')
422
			{
423
				$request = $smcFunc['db_query']('', '
424
					SELECT online_color, max_messages, icons
425
					FROM {db_prefix}membergroups
426
					WHERE id_group = {int:copy_from}
427
					LIMIT 1',
428
					array(
429
						'copy_from' => $copy_id,
430
					)
431
				);
432
				$group_info = $smcFunc['db_fetch_assoc']($request);
433
				$smcFunc['db_free_result']($request);
434
435
				// ...and update the new membergroup with it.
436
				$smcFunc['db_query']('', '
437
					UPDATE {db_prefix}membergroups
438
					SET
439
						online_color = {string:online_color},
440
						max_messages = {int:max_messages},
441
						icons = {string:icons}
442
					WHERE id_group = {int:current_group}',
443
					array(
444
						'max_messages' => $group_info['max_messages'],
445
						'current_group' => $id_group,
446
						'online_color' => $group_info['online_color'],
447
						'icons' => $group_info['icons'],
448
					)
449
				);
450
			}
451
			// If inheriting say so...
452
			elseif ($_POST['perm_type'] == 'inherit')
453
			{
454
				$smcFunc['db_query']('', '
455
					UPDATE {db_prefix}membergroups
456
					SET id_parent = {int:copy_from}
457
					WHERE id_group = {int:current_group}',
458
					array(
459
						'copy_from' => $copy_id,
460
						'current_group' => $id_group,
461
					)
462
				);
463
			}
464
		}
465
466
		// Make sure all boards selected are stored in a proper array.
467
		$accesses = empty($_POST['boardaccess']) || !is_array($_POST['boardaccess']) ? array() : $_POST['boardaccess'];
468
		$changed_boards['allow'] = array();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$changed_boards was never initialized. Although not strictly required by PHP, it is generally a good practice to add $changed_boards = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
469
		$changed_boards['deny'] = array();
470
		$changed_boards['ignore'] = array();
471
		foreach ($accesses as $group_id => $action)
472
			$changed_boards[$action][] = (int) $group_id;
473
474
		foreach (array('allow', 'deny') as $board_action)
475
		{
476
			// Only do this if they have special access requirements.
477
			if (!empty($changed_boards[$board_action]))
478
				$smcFunc['db_query']('', '
479
					UPDATE {db_prefix}boards
480
					SET {raw:column} = CASE WHEN {raw:column} = {string:blank_string} THEN {string:group_id_string} ELSE CONCAT({raw:column}, {string:comma_group}) END
481
					WHERE id_board IN ({array_int:board_list})',
482
					array(
483
						'board_list' => $changed_boards[$board_action],
484
						'blank_string' => '',
485
						'group_id_string' => (string) $id_group,
486
						'comma_group' => ',' . $id_group,
487
						'column' => $board_action == 'allow' ? 'member_groups' : 'deny_member_groups',
488
					)
489
				);
490
		}
491
492
		// If this is joinable then set it to show group membership in people's profiles.
493
		if (empty($modSettings['show_group_membership']) && $_POST['group_type'] > 1)
494
			updateSettings(array('show_group_membership' => 1));
495
496
		// Rebuild the group cache.
497
		updateSettings(array(
498
			'settings_updated' => time(),
499
		));
500
501
		// We did it.
502
		logAction('add_group', array('group' => $smcFunc['htmlspecialchars']($_POST['group_name'])), 'admin');
503
504
		// Go change some more settings.
505
		redirectexit('action=admin;area=membergroups;sa=edit;group=' . $id_group);
506
	}
507
508
	// Just show the 'add membergroup' screen.
509
	$context['page_title'] = $txt['membergroups_new_group'];
510
	$context['sub_template'] = 'new_group';
511
	$context['post_group'] = isset($_REQUEST['postgroup']);
512
	$context['undefined_group'] = !isset($_REQUEST['postgroup']) && !isset($_REQUEST['generalgroup']);
513
	$context['allow_protected'] = allowedTo('admin_forum');
514
515
	if (!empty($modSettings['deny_boards_access']))
516
		loadLanguage('ManagePermissions');
517
518
	$result = $smcFunc['db_query']('', '
519
		SELECT id_group, group_name
520
		FROM {db_prefix}membergroups
521
		WHERE (id_group > {int:moderator_group} OR id_group = {int:global_mod_group})' . (empty($modSettings['permission_enable_postgroups']) ? '
522
			AND min_posts = {int:min_posts}' : '') . (allowedTo('admin_forum') ? '' : '
523
			AND group_type != {int:is_protected}') . '
524
		ORDER BY min_posts, id_group != {int:global_mod_group}, group_name',
525
		array(
526
			'moderator_group' => 3,
527
			'global_mod_group' => 2,
528
			'min_posts' => -1,
529
			'is_protected' => 1,
530
		)
531
	);
532
	$context['groups'] = array();
533
	while ($row = $smcFunc['db_fetch_assoc']($result))
534
		$context['groups'][] = array(
535
			'id' => $row['id_group'],
536
			'name' => $row['group_name']
537
		);
538
	$smcFunc['db_free_result']($result);
539
540
	$request = $smcFunc['db_query']('', '
541
		SELECT b.id_cat, c.name AS cat_name, b.id_board, b.name, b.child_level
542
		FROM {db_prefix}boards AS b
543
			LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
544
		ORDER BY board_order',
545
		array(
546
		)
547
	);
548
	$context['num_boards'] = $smcFunc['db_num_rows']($request);
549
550
	$context['categories'] = array();
551
	while ($row = $smcFunc['db_fetch_assoc']($request))
552
	{
553
		// This category hasn't been set up yet..
554
		if (!isset($context['categories'][$row['id_cat']]))
555
			$context['categories'][$row['id_cat']] = array(
556
				'id' => $row['id_cat'],
557
				'name' => $row['cat_name'],
558
				'boards' => array()
559
			);
560
561
		// Set this board up, and let the template know when it's a child.  (indent them..)
562
		$context['categories'][$row['id_cat']]['boards'][$row['id_board']] = array(
563
			'id' => $row['id_board'],
564
			'name' => $row['name'],
565
			'child_level' => $row['child_level'],
566
			'allow' => false,
567
			'deny' => false
568
		);
569
570
	}
571
	$smcFunc['db_free_result']($request);
572
573
	// Now, let's sort the list of categories into the boards for templates that like that.
574
	$temp_boards = array();
575 View Code Duplication
	foreach ($context['categories'] as $category)
576
	{
577
		$temp_boards[] = array(
578
			'name' => $category['name'],
579
			'child_ids' => array_keys($category['boards'])
580
		);
581
		$temp_boards = array_merge($temp_boards, array_values($category['boards']));
582
583
		// Include a list of boards per category for easy toggling.
584
		$context['categories'][$category['id']]['child_ids'] = array_keys($category['boards']);
585
	}
586
587
	createToken('admin-mmg');
588
}
589
590
/**
591
 * Deleting a membergroup by URL (not implemented).
592
 * Called by ?action=admin;area=membergroups;sa=delete;group=x;session_var=y.
593
 * Requires the manage_membergroups permission.
594
 * Redirects to ?action=admin;area=membergroups.
595
 *
596
 * @todo look at this
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
597
 */
598
function DeleteMembergroup()
599
{
600
	global $sourcedir;
601
602
	checkSession('get');
603
604
	require_once($sourcedir . '/Subs-Membergroups.php');
605
	$result = deleteMembergroups((int) $_REQUEST['group']);
606
	// Need to throw a warning if it went wrong, but this is the only one we have a message for...
607
	if ($result === 'group_cannot_delete_sub')
608
		fatal_lang_error('membergroups_cannot_delete_paid', false);
609
610
	// Go back to the membergroup index.
611
	redirectexit('action=admin;area=membergroups;');
612
}
613
614
/**
615
 * Editing a membergroup.
616
 * Screen to edit a specific membergroup.
617
 * Called by ?action=admin;area=membergroups;sa=edit;group=x.
618
 * It requires the manage_membergroups permission.
619
 * Also handles the delete button of the edit form.
620
 * Redirects to ?action=admin;area=membergroups.
621
 *
622
 * @uses the edit_group sub template of ManageMembergroups.
623
 */
624
function EditMembergroup()
625
{
626
	global $context, $txt, $sourcedir, $modSettings, $smcFunc, $settings;
627
628
	$_REQUEST['group'] = isset($_REQUEST['group']) && $_REQUEST['group'] > 0 ? (int) $_REQUEST['group'] : 0;
629
630
	if (!empty($modSettings['deny_boards_access']))
631
		loadLanguage('ManagePermissions');
632
633
	// Make sure this group is editable.
634
	if (!empty($_REQUEST['group']))
635
	{
636
		$request = $smcFunc['db_query']('', '
637
			SELECT id_group
638
			FROM {db_prefix}membergroups
639
			WHERE id_group = {int:current_group}' . (allowedTo('admin_forum') ? '' : '
640
				AND group_type != {int:is_protected}') . '
641
			LIMIT {int:limit}',
642
			array(
643
				'current_group' => $_REQUEST['group'],
644
				'is_protected' => 1,
645
				'limit' => 1,
646
			)
647
		);
648
		list ($_REQUEST['group']) = $smcFunc['db_fetch_row']($request);
649
		$smcFunc['db_free_result']($request);
650
	}
651
652
	// Now, do we have a valid id?
653
	if (empty($_REQUEST['group']))
654
		fatal_lang_error('membergroup_does_not_exist', false);
655
656
	// People who can manage boards are a bit special.
657
	require_once($sourcedir . '/Subs-Members.php');
658
	$board_managers = groupsAllowedTo('manage_boards', null);
659
	$context['can_manage_boards'] = in_array($_REQUEST['group'], $board_managers['allowed']);
660
661
	// Can this group moderate any boards?
662
	$request = $smcFunc['db_query']('', '
663
		SELECT COUNT(id_board)
664
		FROM {db_prefix}moderator_groups
665
		WHERE id_group = {int:current_group}',
666
		array(
667
			'current_group' => $_REQUEST['group'],
668
		)
669
	);
670
671
	// Why don't we have a $smcFunc['db_result'] function?
672
	$result = $smcFunc['db_fetch_row']($request);
673
	$context['is_moderator_group'] = ($result[0] > 0);
674
	$smcFunc['db_free_result']($request);
675
676
	// The delete this membergroup button was pressed.
677
	if (isset($_POST['delete']))
678
	{
679
		checkSession();
680
		validateToken('admin-mmg');
681
682
		require_once($sourcedir . '/Subs-Membergroups.php');
683
		$result = deleteMembergroups($_REQUEST['group']);
684
		// Need to throw a warning if it went wrong, but this is the only one we have a message for...
685
		if ($result === 'group_cannot_delete_sub')
686
			fatal_lang_error('membergroups_cannot_delete_paid', false);
687
688
		redirectexit('action=admin;area=membergroups;');
689
	}
690
	// A form was submitted with the new membergroup settings.
691
	elseif (isset($_POST['save']))
692
	{
693
		// Validate the session.
694
		checkSession();
695
		validateToken('admin-mmg');
696
697
		// Can they really inherit from this group?
698
		if ($_REQUEST['group'] > 1 && $_REQUEST['group'] != 3 && isset($_POST['group_inherit']) && $_POST['group_inherit'] != -2 && !allowedTo('admin_forum'))
699
		{
700
			$request = $smcFunc['db_query']('', '
701
				SELECT group_type
702
				FROM {db_prefix}membergroups
703
				WHERE id_group = {int:inherit_from}
704
				LIMIT {int:limit}',
705
				array(
706
					'inherit_from' => $_POST['group_inherit'],
707
					'limit' => 1,
708
				)
709
			);
710
			list ($inherit_type) = $smcFunc['db_fetch_row']($request);
711
			$smcFunc['db_free_result']($request);
712
		}
713
714
		// Set variables to their proper value.
715
		$_POST['max_messages'] = isset($_POST['max_messages']) ? (int) $_POST['max_messages'] : 0;
716
		$_POST['min_posts'] = isset($_POST['min_posts']) && isset($_POST['group_type']) && $_POST['group_type'] == -1 && $_REQUEST['group'] > 3 ? abs($_POST['min_posts']) : ($_REQUEST['group'] == 4 ? 0 : -1);
717
		$_POST['icons'] = (empty($_POST['icon_count']) || $_POST['icon_count'] < 0) ? '' : min((int) $_POST['icon_count'], 99) . '#' . $_POST['icon_image'];
718
		$_POST['group_desc'] = isset($_POST['group_desc']) && ($_REQUEST['group'] == 1 || (isset($_POST['group_type']) && $_POST['group_type'] != -1)) ? trim($_POST['group_desc']) : '';
719
		$_POST['group_type'] = !isset($_POST['group_type']) || $_POST['group_type'] < 0 || $_POST['group_type'] > 3 || ($_POST['group_type'] == 1 && !allowedTo('admin_forum')) ? 0 : (int) $_POST['group_type'];
720
		$_POST['group_hidden'] = empty($_POST['group_hidden']) || $_POST['min_posts'] != -1 || $_REQUEST['group'] == 3 ? 0 : (int) $_POST['group_hidden'];
721
		$_POST['group_inherit'] = $_REQUEST['group'] > 1 && $_REQUEST['group'] != 3 && (empty($inherit_type) || $inherit_type != 1) ? (int) $_POST['group_inherit'] : -2;
0 ignored issues
show
Bug introduced by
The variable $inherit_type does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
722
		$_POST['group_tfa_force'] = (empty($modSettings['tfa_mode']) || $modSettings['tfa_mode'] != 2 || empty($_POST['group_tfa_force'])) ? 0 : 1;
723
724
		//@todo Don't set online_color for the Moderators group?
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
725
726
		// Do the update of the membergroup settings.
727
		$smcFunc['db_query']('', '
728
			UPDATE {db_prefix}membergroups
729
			SET group_name = {string:group_name}, online_color = {string:online_color},
730
				max_messages = {int:max_messages}, min_posts = {int:min_posts}, icons = {string:icons},
731
				description = {string:group_desc}, group_type = {int:group_type}, hidden = {int:group_hidden},
732
				id_parent = {int:group_inherit}, tfa_required = {int:tfa_required}
733
			WHERE id_group = {int:current_group}',
734
			array(
735
				'max_messages' => $_POST['max_messages'],
736
				'min_posts' => $_POST['min_posts'],
737
				'group_type' => $_POST['group_type'],
738
				'group_hidden' => $_POST['group_hidden'],
739
				'group_inherit' => $_POST['group_inherit'],
740
				'current_group' => (int) $_REQUEST['group'],
741
				'group_name' => $smcFunc['htmlspecialchars']($_POST['group_name']),
742
				'online_color' => $_POST['online_color'],
743
				'icons' => $_POST['icons'],
744
				'group_desc' => $_POST['group_desc'],
745
				'tfa_required' => $_POST['group_tfa_force'],
746
			)
747
		);
748
749
		call_integration_hook('integrate_save_membergroup', array((int) $_REQUEST['group']));
750
751
		// Time to update the boards this membergroup has access to.
752
		if ($_REQUEST['group'] == 2 || $_REQUEST['group'] > 3)
753
		{
754
			$accesses = empty($_POST['boardaccess']) || !is_array($_POST['boardaccess']) ? array() : $_POST['boardaccess'];
755
756
			// If they can manage boards, the rules are a bit different. They can see everything.
757
			if ($context['can_manage_boards'])
758
			{
759
				$accesses = array();
760
				$request = $smcFunc['db_query']('', '
761
					SELECT id_board
762
					FROM {db_prefix}boards');
763
				while ($row = $smcFunc['db_fetch_assoc']($request))
764
					$accesses[(int) $row['id_board']] = 'allow';
765
				$smcFunc['db_free_result']($request);
766
			}
767
768
			$changed_boards['allow'] = array();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$changed_boards was never initialized. Although not strictly required by PHP, it is generally a good practice to add $changed_boards = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
769
			$changed_boards['deny'] = array();
770
			$changed_boards['ignore'] = array();
771
			foreach ($accesses as $group_id => $action)
772
				$changed_boards[$action][] = (int) $group_id;
773
774
			foreach (array('allow', 'deny') as $board_action)
775
			{
776
				// Find all board this group is in, but shouldn't be in.
777
				$request = $smcFunc['db_query']('', '
778
					SELECT id_board, {raw:column}
779
					FROM {db_prefix}boards
780
					WHERE FIND_IN_SET({string:current_group}, {raw:column}) != 0' . (empty($changed_boards[$board_action]) ? '' : '
781
						AND id_board NOT IN ({array_int:board_access_list})'),
782
					array(
783
						'current_group' => (int) $_REQUEST['group'],
784
						'board_access_list' => $changed_boards[$board_action],
785
						'column' => $board_action == 'allow' ? 'member_groups' : 'deny_member_groups',
786
					)
787
				);
788
				while ($row = $smcFunc['db_fetch_assoc']($request))
789
					$smcFunc['db_query']('', '
790
						UPDATE {db_prefix}boards
791
						SET {raw:column} = {string:member_group_access}
792
						WHERE id_board = {int:current_board}',
793
						array(
794
							'current_board' => $row['id_board'],
795
							'member_group_access' => implode(',', array_diff(explode(',', $row['member_groups']), array($_REQUEST['group']))),
796
							'column' => $board_action == 'allow' ? 'member_groups' : 'deny_member_groups',
797
						)
798
					);
799
				$smcFunc['db_free_result']($request);
800
801
				// Add the membergroup to all boards that hadn't been set yet.
802
				if (!empty($changed_boards[$board_action]))
803
					$smcFunc['db_query']('', '
804
						UPDATE {db_prefix}boards
805
						SET {raw:column} = CASE WHEN {raw:column} = {string:blank_string} THEN {string:group_id_string} ELSE CONCAT({raw:column}, {string:comma_group}) END
806
						WHERE id_board IN ({array_int:board_list})
807
							AND FIND_IN_SET({int:current_group}, {raw:column}) = 0',
808
						array(
809
							'board_list' => $changed_boards[$board_action],
810
							'blank_string' => '',
811
							'current_group' => (int) $_REQUEST['group'],
812
							'group_id_string' => (string) (int) $_REQUEST['group'],
813
							'comma_group' => ',' . $_REQUEST['group'],
814
							'column' => $board_action == 'allow' ? 'member_groups' : 'deny_member_groups',
815
						)
816
					);
817
			}
818
		}
819
820
		// Remove everyone from this group!
821
		if ($_POST['min_posts'] != -1)
822
		{
823
			$smcFunc['db_query']('', '
824
				UPDATE {db_prefix}members
825
				SET id_group = {int:regular_member}
826
				WHERE id_group = {int:current_group}',
827
				array(
828
					'regular_member' => 0,
829
					'current_group' => (int) $_REQUEST['group'],
830
				)
831
			);
832
833
			$request = $smcFunc['db_query']('', '
834
				SELECT id_member, additional_groups
835
				FROM {db_prefix}members
836
				WHERE FIND_IN_SET({string:current_group}, additional_groups) != 0',
837
				array(
838
					'current_group' => (int) $_REQUEST['group'],
839
				)
840
			);
841
			$updates = array();
842 View Code Duplication
			while ($row = $smcFunc['db_fetch_assoc']($request))
843
				$updates[$row['additional_groups']][] = $row['id_member'];
844
			$smcFunc['db_free_result']($request);
845
846 View Code Duplication
			foreach ($updates as $additional_groups => $memberArray)
847
				updateMemberData($memberArray, array('additional_groups' => implode(',', array_diff(explode(',', $additional_groups), array((int) $_REQUEST['group'])))));
848
849
			// Sorry, but post groups can't moderate boards
850
			$smcFunc['db_query']('', '
851
				DELETE FROM {db_prefix}moderator_groups
852
				WHERE id_group = {int:current_group}',
853
				array(
854
					'current_group' => (int) $_REQUEST['group'],
855
				)
856
			);
857
		}
858
		elseif ($_REQUEST['group'] != 3)
859
		{
860
			// Making it a hidden group? If so remove everyone with it as primary group (Actually, just make them additional).
861
			if ($_POST['group_hidden'] == 2)
862
			{
863
				$request = $smcFunc['db_query']('', '
864
					SELECT id_member, additional_groups
865
					FROM {db_prefix}members
866
					WHERE id_group = {int:current_group}
867
						AND FIND_IN_SET({int:current_group}, additional_groups) = 0',
868
					array(
869
						'current_group' => (int) $_REQUEST['group'],
870
					)
871
				);
872
				$updates = array();
873 View Code Duplication
				while ($row = $smcFunc['db_fetch_assoc']($request))
874
					$updates[$row['additional_groups']][] = $row['id_member'];
875
				$smcFunc['db_free_result']($request);
876
877
				foreach ($updates as $additional_groups => $memberArray)
878
				{
879
					$new_groups = (!empty($additional_groups) ? $additional_groups . ',' : '') . $_REQUEST['group']; // We already validated this a while ago.
880
					updateMemberData($memberArray, array('additional_groups' => $new_groups));
881
				}
882
883
				$smcFunc['db_query']('', '
884
					UPDATE {db_prefix}members
885
					SET id_group = {int:regular_member}
886
					WHERE id_group = {int:current_group}',
887
					array(
888
						'regular_member' => 0,
889
						'current_group' => $_REQUEST['group'],
890
					)
891
				);
892
893
				// Hidden groups can't moderate boards
894
				$smcFunc['db_query']('', '
895
					DELETE FROM {db_prefix}moderator_groups
896
					WHERE id_group = {int:current_group}',
897
					array(
898
						'current_group' => $_REQUEST['group'],
899
					)
900
				);
901
			}
902
903
			// Either way, let's check our "show group membership" setting is correct.
904
			$request = $smcFunc['db_query']('', '
905
				SELECT COUNT(*)
906
				FROM {db_prefix}membergroups
907
				WHERE group_type > {int:non_joinable}',
908
				array(
909
					'non_joinable' => 1,
910
				)
911
			);
912
			list ($have_joinable) = $smcFunc['db_fetch_row']($request);
913
			$smcFunc['db_free_result']($request);
914
915
			// Do we need to update the setting?
916
			if ((empty($modSettings['show_group_membership']) && $have_joinable) || (!empty($modSettings['show_group_membership']) && !$have_joinable))
917
				updateSettings(array('show_group_membership' => $have_joinable ? 1 : 0));
918
		}
919
920
		// Do we need to set inherited permissions?
921
		if ($_POST['group_inherit'] != -2 && $_POST['group_inherit'] != $_POST['old_inherit'])
922
		{
923
			require_once($sourcedir . '/ManagePermissions.php');
924
			updateChildPermissions($_POST['group_inherit']);
925
		}
926
927
		// Finally, moderators!
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
928
		$moderator_string = isset($_POST['group_moderators']) ? trim($_POST['group_moderators']) : '';
929
		$smcFunc['db_query']('', '
930
			DELETE FROM {db_prefix}group_moderators
931
			WHERE id_group = {int:current_group}',
932
			array(
933
				'current_group' => $_REQUEST['group'],
934
			)
935
		);
936
		if ((!empty($moderator_string) || !empty($_POST['moderator_list'])) && $_POST['min_posts'] == -1 && $_REQUEST['group'] != 3)
937
		{
938
			$group_moderators = array();
939
940
			// Get all the usernames from the string
941
			if (!empty($moderator_string))
942
			{
943
				$moderator_string = strtr(preg_replace('~&amp;#(\d{4,5}|[2-9]\d{2,4}|1[2-9]\d);~', '&#$1;', $smcFunc['htmlspecialchars']($moderator_string, ENT_QUOTES)), array('&quot;' => '"'));
944
				preg_match_all('~"([^"]+)"~', $moderator_string, $matches);
945
				$moderators = array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $moderator_string)));
946 View Code Duplication
				for ($k = 0, $n = count($moderators); $k < $n; $k++)
947
				{
948
					$moderators[$k] = trim($moderators[$k]);
949
950
					if (strlen($moderators[$k]) == 0)
951
						unset($moderators[$k]);
952
				}
953
954
				// Find all the id_member's for the member_name's in the list.
955
				if (!empty($moderators))
956
				{
957
					$request = $smcFunc['db_query']('', '
958
						SELECT id_member
959
						FROM {db_prefix}members
960
						WHERE member_name IN ({array_string:moderators}) OR real_name IN ({array_string:moderators})
961
						LIMIT {int:count}',
962
						array(
963
							'moderators' => $moderators,
964
							'count' => count($moderators),
965
						)
966
					);
967
					while ($row = $smcFunc['db_fetch_assoc']($request))
968
						$group_moderators[] = $row['id_member'];
969
					$smcFunc['db_free_result']($request);
970
				}
971
			}
972
973 View Code Duplication
			if (!empty($_POST['moderator_list']))
974
			{
975
				$moderators = array();
976
				foreach ($_POST['moderator_list'] as $moderator)
977
					$moderators[] = (int) $moderator;
978
979
				if (!empty($moderators))
980
				{
981
					$request = $smcFunc['db_query']('', '
982
						SELECT id_member
983
						FROM {db_prefix}members
984
						WHERE id_member IN ({array_int:moderators})
985
						LIMIT {int:num_moderators}',
986
						array(
987
							'moderators' => $moderators,
988
							'num_moderators' => count($moderators),
989
						)
990
					);
991
					while ($row = $smcFunc['db_fetch_assoc']($request))
992
						$group_moderators[] = $row['id_member'];
993
					$smcFunc['db_free_result']($request);
994
				}
995
			}
996
997
			// Make sure we don't have any duplicates first...
998
			$group_moderators = array_unique($group_moderators);
999
1000
			// Found some?
1001
			if (!empty($group_moderators))
1002
			{
1003
				$mod_insert = array();
1004
				foreach ($group_moderators as $moderator)
1005
					$mod_insert[] = array($_REQUEST['group'], $moderator);
1006
1007
				$smcFunc['db_insert']('insert',
1008
					'{db_prefix}group_moderators',
1009
					array('id_group' => 'int', 'id_member' => 'int'),
1010
					$mod_insert,
1011
					array('id_group', 'id_member')
1012
				);
1013
			}
1014
		}
1015
1016
		// There might have been some post group changes.
1017
		updateStats('postgroups');
1018
		// We've definitely changed some group stuff.
1019
		updateSettings(array(
1020
			'settings_updated' => time(),
1021
		));
1022
1023
		// Log the edit.
1024
		logAction('edited_group', array('group' => $smcFunc['htmlspecialchars']($_POST['group_name'])), 'admin');
1025
1026
		redirectexit('action=admin;area=membergroups');
1027
	}
1028
1029
	// Fetch the current group information.
1030
	$request = $smcFunc['db_query']('', '
1031
		SELECT group_name, description, min_posts, online_color, max_messages, icons, group_type, hidden, id_parent, tfa_required
1032
		FROM {db_prefix}membergroups
1033
		WHERE id_group = {int:current_group}
1034
		LIMIT 1',
1035
		array(
1036
			'current_group' => (int) $_REQUEST['group'],
1037
		)
1038
	);
1039
	if ($smcFunc['db_num_rows']($request) == 0)
1040
		fatal_lang_error('membergroup_does_not_exist', false);
1041
	$row = $smcFunc['db_fetch_assoc']($request);
1042
	$smcFunc['db_free_result']($request);
1043
1044
	$row['icons'] = explode('#', $row['icons']);
1045
1046
	$context['group'] = array(
1047
		'id' => $_REQUEST['group'],
1048
		'name' => $row['group_name'],
1049
		'description' => $smcFunc['htmlspecialchars']($row['description'], ENT_QUOTES),
1050
		'editable_name' => $row['group_name'],
1051
		'color' => $row['online_color'],
1052
		'min_posts' => $row['min_posts'],
1053
		'max_messages' => $row['max_messages'],
1054
		'icon_count' => (int) $row['icons'][0],
1055
		'icon_image' => isset($row['icons'][1]) ? $row['icons'][1] : '',
1056
		'is_post_group' => $row['min_posts'] != -1,
1057
		'type' => $row['min_posts'] != -1 ? 0 : $row['group_type'],
1058
		'hidden' => $row['min_posts'] == -1 ? $row['hidden'] : 0,
1059
		'inherited_from' => $row['id_parent'],
1060
		'allow_post_group' => $_REQUEST['group'] == 2 || $_REQUEST['group'] > 4,
1061
		'allow_delete' => $_REQUEST['group'] == 2 || $_REQUEST['group'] > 4,
1062
		'allow_protected' => allowedTo('admin_forum'),
1063
		'tfa_required' => $row['tfa_required'],
1064
	);
1065
1066
	// Get any moderators for this group
1067
	$request = $smcFunc['db_query']('', '
1068
		SELECT mem.id_member, mem.real_name
1069
		FROM {db_prefix}group_moderators AS mods
1070
			INNER JOIN {db_prefix}members AS mem ON (mem.id_member = mods.id_member)
1071
		WHERE mods.id_group = {int:current_group}',
1072
		array(
1073
			'current_group' => $_REQUEST['group'],
1074
		)
1075
	);
1076
	$context['group']['moderators'] = array();
1077
	while ($row = $smcFunc['db_fetch_assoc']($request))
1078
		$context['group']['moderators'][$row['id_member']] = $row['real_name'];
1079
	$smcFunc['db_free_result']($request);
1080
1081
	$context['group']['moderator_list'] = empty($context['group']['moderators']) ? '' : '&quot;' . implode('&quot;, &quot;', $context['group']['moderators']) . '&quot;';
1082
1083 View Code Duplication
	if (!empty($context['group']['moderators']))
1084
		list ($context['group']['last_moderator_id']) = array_slice(array_keys($context['group']['moderators']), -1);
1085
1086
	// Get a list of boards this membergroup is allowed to see.
1087
	$context['boards'] = array();
1088
	if ($_REQUEST['group'] == 2 || $_REQUEST['group'] > 3)
1089
	{
1090
		$request = $smcFunc['db_query']('', '
1091
			SELECT b.id_cat, c.name as cat_name, b.id_board, b.name, b.child_level,
1092
			FIND_IN_SET({string:current_group}, b.member_groups) != 0 AS can_access, FIND_IN_SET({string:current_group}, b.deny_member_groups) != 0 AS cannot_access
1093
			FROM {db_prefix}boards AS b
1094
				LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
1095
			ORDER BY board_order',
1096
			array(
1097
				'current_group' => (int) $_REQUEST['group'],
1098
			)
1099
		);
1100
		$context['categories'] = array();
1101
		while ($row = $smcFunc['db_fetch_assoc']($request))
1102
		{
1103
			// This category hasn't been set up yet..
1104
			if (!isset($context['categories'][$row['id_cat']]))
1105
				$context['categories'][$row['id_cat']] = array(
1106
					'id' => $row['id_cat'],
1107
					'name' => $row['cat_name'],
1108
					'boards' => array()
1109
				);
1110
1111
			// Set this board up, and let the template know when it's a child.  (indent them..)
1112
			$context['categories'][$row['id_cat']]['boards'][$row['id_board']] = array(
1113
				'id' => $row['id_board'],
1114
				'name' => $row['name'],
1115
				'child_level' => $row['child_level'],
1116
				'allow' => !(empty($row['can_access']) || $row['can_access'] == 'f'),
1117
				'deny' => !(empty($row['cannot_access']) || $row['cannot_access'] == 'f'),
1118
			);
1119
		}
1120
		$smcFunc['db_free_result']($request);
1121
1122
		// Now, let's sort the list of categories into the boards for templates that like that.
1123
		$temp_boards = array();
1124 View Code Duplication
		foreach ($context['categories'] as $category)
1125
		{
1126
			$temp_boards[] = array(
1127
				'name' => $category['name'],
1128
				'child_ids' => array_keys($category['boards'])
1129
			);
1130
			$temp_boards = array_merge($temp_boards, array_values($category['boards']));
1131
1132
			// Include a list of boards per category for easy toggling.
1133
			$context['categories'][$category['id']]['child_ids'] = array_keys($category['boards']);
1134
		}
1135
	}
1136
1137
	// Get a list of all the image formats we can select.
1138
	$imageExts = array('png', 'jpg', 'jpeg', 'bmp', 'gif');
1139
1140
	// Scan the directory.
1141
	$context['possible_icons'] = array();
1142
	if ($files = scandir($settings['default_theme_dir'] . '/images/membericons'))
1143
	{
1144
		// Loop through every file in the directory.
1145
		foreach ($files as $value)
1146
		{
1147
			// Grab the image extension.
1148
			$ext = pathinfo($settings['default_theme_dir'] . '/images/membericons/' . $value, PATHINFO_EXTENSION);
1149
1150
			// If the extension is not empty, and it is valid
1151
			if (!empty($ext) && in_array($ext, $imageExts))
1152
			{
1153
				// Get the size of the image.
1154
				$image_info = getimagesize($settings['default_theme_dir'] . '/images/membericons/' . $value);
1155
1156
				// If this is bigger than 128 in width or 32 in height, skip this one.
1157
				if ($image_info == false || $image_info[0] > 128 || $image_info[1] > 32)
1158
					continue;
1159
1160
				// Else it's valid. Add it in.
1161
				else
1162
					$context['possible_icons'][] = $value;
1163
			}
1164
		}
1165
	}
1166
1167
	// Insert our JS, if we have possible icons.
1168
	if (!empty($context['possible_icons']))
1169
		loadJavaScriptFile('icondropdown.js', array('validate' => true), 'smf_icondropdown');
1170
1171
		loadJavaScriptFile('suggest.js', array('defer' => false), 'smf_suggest');
1172
1173
	// Finally, get all the groups this could be inherited off.
1174
	$request = $smcFunc['db_query']('', '
1175
		SELECT id_group, group_name
1176
		FROM {db_prefix}membergroups
1177
		WHERE id_group != {int:current_group}' .
1178
			(empty($modSettings['permission_enable_postgroups']) ? '
1179
			AND min_posts = {int:min_posts}' : '') . (allowedTo('admin_forum') ? '' : '
1180
			AND group_type != {int:is_protected}') . '
1181
			AND id_group NOT IN (1, 3)
1182
			AND id_parent = {int:not_inherited}',
1183
		array(
1184
			'current_group' => (int) $_REQUEST['group'],
1185
			'min_posts' => -1,
1186
			'not_inherited' => -2,
1187
			'is_protected' => 1,
1188
		)
1189
	);
1190
	$context['inheritable_groups'] = array();
1191
	while ($row = $smcFunc['db_fetch_assoc']($request))
1192
		$context['inheritable_groups'][$row['id_group']] = $row['group_name'];
1193
	$smcFunc['db_free_result']($request);
1194
1195
	call_integration_hook('integrate_view_membergroup');
1196
1197
	$context['sub_template'] = 'edit_group';
1198
	$context['page_title'] = $txt['membergroups_edit_group'];
1199
1200
	createToken('admin-mmg');
1201
}
1202
1203
/**
1204
 * Set some general membergroup settings and permissions.
1205
 * Called by ?action=admin;area=membergroups;sa=settings
1206
 * Requires the admin_forum permission (and manage_permissions for changing permissions)
1207
 * Redirects to itself.
1208
 *
1209
 * @uses membergroup_settings sub template of ManageMembergroups.
1210
 */
1211
function ModifyMembergroupsettings()
1212
{
1213
	global $context, $sourcedir, $scripturl, $txt;
1214
1215
	$context['sub_template'] = 'show_settings';
1216
	$context['page_title'] = $txt['membergroups_settings'];
1217
1218
	// Needed for the settings functions.
1219
	require_once($sourcedir . '/ManageServer.php');
1220
1221
	// Only one thing here!
1222
	$config_vars = array(
1223
			array('permissions', 'manage_membergroups'),
1224
	);
1225
1226
	call_integration_hook('integrate_modify_membergroup_settings', array(&$config_vars));
1227
1228
	if (isset($_REQUEST['save']))
1229
	{
1230
		checkSession();
1231
		call_integration_hook('integrate_save_membergroup_settings');
1232
1233
		// Yeppers, saving this...
1234
		saveDBSettings($config_vars);
1235
		$_SESSION['adm-save'] = true;
1236
		redirectexit('action=admin;area=membergroups;sa=settings');
1237
	}
1238
1239
	// Some simple context.
1240
	$context['post_url'] = $scripturl . '?action=admin;area=membergroups;save;sa=settings';
1241
	$context['settings_title'] = $txt['membergroups_settings'];
1242
1243
	// We need this for the in-line permissions
1244
	createToken('admin-mp');
1245
1246
	prepareDBSettingContext($config_vars);
1247
}
1248
1249
?>