Issues (1061)

Sources/Subs-Boards.php (6 issues)

1
<?php
2
3
/**
4
 * This file is mainly concerned with minor tasks relating to boards, such as
5
 * marking them read, collapsing categories, or quick moderation.
6
 *
7
 * Simple Machines Forum (SMF)
8
 *
9
 * @package SMF
10
 * @author Simple Machines https://www.simplemachines.org
11
 * @copyright 2020 Simple Machines and individual contributors
12
 * @license https://www.simplemachines.org/about/smf/license.php BSD
13
 *
14
 * @version 2.1 RC2
15
 */
16
17
if (!defined('SMF'))
18
	die('No direct access...');
19
20
/**
21
 * Mark a board or multiple boards read.
22
 *
23
 * @param int|array $boards The ID of a single board or an array of boards
24
 * @param bool $unread Whether we're marking them as unread
25
 */
26
function markBoardsRead($boards, $unread = false)
27
{
28
	global $user_info, $modSettings, $smcFunc;
29
30
	// Force $boards to be an array.
31
	if (!is_array($boards))
32
		$boards = array($boards);
33
	else
34
		$boards = array_unique($boards);
35
36
	// No boards, nothing to mark as read.
37
	if (empty($boards))
38
		return;
39
40
	// Allow the user to mark a board as unread.
41
	if ($unread)
42
	{
43
		// Clear out all the places where this lovely info is stored.
44
		// @todo Maybe not log_mark_read?
45
		$smcFunc['db_query']('', '
46
			DELETE FROM {db_prefix}log_mark_read
47
			WHERE id_board IN ({array_int:board_list})
48
				AND id_member = {int:current_member}',
49
			array(
50
				'current_member' => $user_info['id'],
51
				'board_list' => $boards,
52
			)
53
		);
54
		$smcFunc['db_query']('', '
55
			DELETE FROM {db_prefix}log_boards
56
			WHERE id_board IN ({array_int:board_list})
57
				AND id_member = {int:current_member}',
58
			array(
59
				'current_member' => $user_info['id'],
60
				'board_list' => $boards,
61
			)
62
		);
63
	}
64
	// Otherwise mark the board as read.
65
	else
66
	{
67
		$markRead = array();
68
		foreach ($boards as $board)
69
			$markRead[] = array($modSettings['maxMsgID'], $user_info['id'], $board);
70
71
		// Update log_mark_read and log_boards.
72
		$smcFunc['db_insert']('replace',
73
			'{db_prefix}log_mark_read',
74
			array('id_msg' => 'int', 'id_member' => 'int', 'id_board' => 'int'),
75
			$markRead,
76
			array('id_board', 'id_member')
77
		);
78
79
		$smcFunc['db_insert']('replace',
80
			'{db_prefix}log_boards',
81
			array('id_msg' => 'int', 'id_member' => 'int', 'id_board' => 'int'),
82
			$markRead,
83
			array('id_board', 'id_member')
84
		);
85
	}
86
87
	// Get rid of useless log_topics data, because log_mark_read is better for it - even if marking unread - I think so...
88
	// @todo look at this...
89
	// The call to markBoardsRead() in Display() used to be simply
90
	// marking log_boards (the previous query only)
91
	$result = $smcFunc['db_query']('', '
92
		SELECT MIN(id_topic)
93
		FROM {db_prefix}log_topics
94
		WHERE id_member = {int:current_member}',
95
		array(
96
			'current_member' => $user_info['id'],
97
		)
98
	);
99
	list ($lowest_topic) = $smcFunc['db_fetch_row']($result);
100
	$smcFunc['db_free_result']($result);
101
102
	if (empty($lowest_topic))
103
		return;
104
105
	// @todo SLOW This query seems to eat it sometimes.
106
	$result = $smcFunc['db_query']('', '
107
		SELECT lt.id_topic
108
		FROM {db_prefix}log_topics AS lt
109
			INNER JOIN {db_prefix}topics AS t /*!40000 USE INDEX (PRIMARY) */ ON (t.id_topic = lt.id_topic
110
				AND t.id_board IN ({array_int:board_list}))
111
		WHERE lt.id_member = {int:current_member}
112
			AND lt.id_topic >= {int:lowest_topic}
113
			AND lt.unwatched != 1',
114
		array(
115
			'current_member' => $user_info['id'],
116
			'board_list' => $boards,
117
			'lowest_topic' => $lowest_topic,
118
		)
119
	);
120
	$topics = array();
121
	while ($row = $smcFunc['db_fetch_assoc']($result))
122
		$topics[] = $row['id_topic'];
123
	$smcFunc['db_free_result']($result);
124
125
	if (!empty($topics))
126
		$smcFunc['db_query']('', '
127
			DELETE FROM {db_prefix}log_topics
128
			WHERE id_member = {int:current_member}
129
				AND id_topic IN ({array_int:topic_list})',
130
			array(
131
				'current_member' => $user_info['id'],
132
				'topic_list' => $topics,
133
			)
134
		);
135
}
136
137
/**
138
 * Mark one or more boards as read.
139
 */
140
function MarkRead()
141
{
142
	global $board, $topic, $user_info, $board_info, $modSettings, $smcFunc;
143
144
	// No Guests allowed!
145
	is_not_guest();
146
147
	checkSession('get');
148
149
	if (isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'all')
150
	{
151
		// Find all the boards this user can see.
152
		$result = $smcFunc['db_query']('', '
153
			SELECT b.id_board
154
			FROM {db_prefix}boards AS b
155
			WHERE {query_see_board}',
156
			array(
157
			)
158
		);
159
		$boards = array();
160
		while ($row = $smcFunc['db_fetch_assoc']($result))
161
			$boards[] = $row['id_board'];
162
		$smcFunc['db_free_result']($result);
163
164
		if (!empty($boards))
165
			markBoardsRead($boards, isset($_REQUEST['unread']));
166
167
		$_SESSION['id_msg_last_visit'] = $modSettings['maxMsgID'];
168
		if (!empty($_SESSION['old_url']) && strpos($_SESSION['old_url'], 'action=unread') !== false)
169
			redirectexit('action=unread');
170
171
		if (isset($_SESSION['topicseen_cache']))
172
			$_SESSION['topicseen_cache'] = array();
173
174
		redirectexit();
175
	}
176
	elseif (isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'unreadreplies')
177
	{
178
		// Make sure all the topics are integers!
179
		$topics = array_map('intval', explode('-', $_REQUEST['topics']));
180
181
		$request = $smcFunc['db_query']('', '
182
			SELECT id_topic, unwatched
183
			FROM {db_prefix}log_topics
184
			WHERE id_topic IN ({array_int:selected_topics})
185
				AND id_member = {int:current_user}',
186
			array(
187
				'selected_topics' => $topics,
188
				'current_user' => $user_info['id'],
189
			)
190
		);
191
		$logged_topics = array();
192
		while ($row = $smcFunc['db_fetch_assoc']($request))
193
			$logged_topics[$row['id_topic']] = $row['unwatched'];
194
		$smcFunc['db_free_result']($request);
195
196
		$markRead = array();
197
		foreach ($topics as $id_topic)
198
			$markRead[] = array($modSettings['maxMsgID'], $user_info['id'], $id_topic, (isset($logged_topics[$topic]) ? $logged_topics[$topic] : 0));
199
200
		$smcFunc['db_insert']('replace',
201
			'{db_prefix}log_topics',
202
			array('id_msg' => 'int', 'id_member' => 'int', 'id_topic' => 'int', 'unwatched' => 'int'),
203
			$markRead,
204
			array('id_member', 'id_topic')
205
		);
206
207
		if (isset($_SESSION['topicseen_cache']))
208
			$_SESSION['topicseen_cache'] = array();
209
210
		redirectexit('action=unreadreplies');
211
	}
212
213
	// Special case: mark a topic unread!
214
	elseif (isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'topic')
215
	{
216
		// First, let's figure out what the latest message is.
217
		$result = $smcFunc['db_query']('', '
218
			SELECT t.id_first_msg, t.id_last_msg, COALESCE(lt.unwatched, 0) as unwatched
219
			FROM {db_prefix}topics as t
220
				LEFT JOIN {db_prefix}log_topics as lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
221
			WHERE t.id_topic = {int:current_topic}',
222
			array(
223
				'current_topic' => $topic,
224
				'current_member' => $user_info['id'],
225
			)
226
		);
227
		$topicinfo = $smcFunc['db_fetch_assoc']($result);
228
		$smcFunc['db_free_result']($result);
229
230
		if (!empty($_GET['t']))
231
		{
232
			// If they read the whole topic, go back to the beginning.
233
			if ($_GET['t'] >= $topicinfo['id_last_msg'])
234
				$earlyMsg = 0;
235
			// If they want to mark the whole thing read, same.
236
			elseif ($_GET['t'] <= $topicinfo['id_first_msg'])
237
				$earlyMsg = 0;
238
			// Otherwise, get the latest message before the named one.
239
			else
240
			{
241
				$result = $smcFunc['db_query']('', '
242
					SELECT MAX(id_msg)
243
					FROM {db_prefix}messages
244
					WHERE id_topic = {int:current_topic}
245
						AND id_msg >= {int:id_first_msg}
246
						AND id_msg < {int:topic_msg_id}',
247
					array(
248
						'current_topic' => $topic,
249
						'topic_msg_id' => (int) $_GET['t'],
250
						'id_first_msg' => $topicinfo['id_first_msg'],
251
					)
252
				);
253
				list ($earlyMsg) = $smcFunc['db_fetch_row']($result);
254
				$smcFunc['db_free_result']($result);
255
			}
256
		}
257
		// Marking read from first page?  That's the whole topic.
258
		elseif ($_REQUEST['start'] == 0)
259
			$earlyMsg = 0;
260
		else
261
		{
262
			$result = $smcFunc['db_query']('', '
263
				SELECT id_msg
264
				FROM {db_prefix}messages
265
				WHERE id_topic = {int:current_topic}
266
				ORDER BY id_msg
267
				LIMIT {int:start}, 1',
268
				array(
269
					'current_topic' => $topic,
270
					'start' => (int) $_REQUEST['start'],
271
				)
272
			);
273
			list ($earlyMsg) = $smcFunc['db_fetch_row']($result);
274
			$smcFunc['db_free_result']($result);
275
276
			$earlyMsg--;
277
		}
278
279
		// Blam, unread!
280
		$smcFunc['db_insert']('replace',
281
			'{db_prefix}log_topics',
282
			array('id_msg' => 'int', 'id_member' => 'int', 'id_topic' => 'int', 'unwatched' => 'int'),
283
			array($earlyMsg, $user_info['id'], $topic, $topicinfo['unwatched']),
284
			array('id_member', 'id_topic')
285
		);
286
287
		redirectexit('board=' . $board . '.0');
288
	}
289
	else
290
	{
291
		$categories = array();
292
		$boards = array();
293
294
		if (isset($_REQUEST['c']))
295
		{
296
			$_REQUEST['c'] = explode(',', $_REQUEST['c']);
297
			foreach ($_REQUEST['c'] as $c)
298
				$categories[] = (int) $c;
299
		}
300
		if (isset($_REQUEST['boards']))
301
		{
302
			$_REQUEST['boards'] = explode(',', $_REQUEST['boards']);
303
			foreach ($_REQUEST['boards'] as $b)
304
				$boards[] = (int) $b;
305
		}
306
		if (!empty($board))
307
			$boards[] = (int) $board;
308
309
		if (isset($_REQUEST['children']) && !empty($boards))
310
		{
311
			// They want to mark the entire tree starting with the boards specified
312
			// The easiest thing is to just get all the boards they can see, but since we've specified the top of tree we ignore some of them
313
314
			$request = $smcFunc['db_query']('', '
315
				SELECT b.id_board, b.id_parent
316
				FROM {db_prefix}boards AS b
317
				WHERE {query_see_board}
318
					AND b.child_level > {int:no_parents}
319
					AND b.id_board NOT IN ({array_int:board_list})
320
				ORDER BY child_level ASC',
321
				array(
322
					'no_parents' => 0,
323
					'board_list' => $boards,
324
				)
325
			);
326
			while ($row = $smcFunc['db_fetch_assoc']($request))
327
				if (in_array($row['id_parent'], $boards))
328
					$boards[] = $row['id_board'];
329
330
			$smcFunc['db_free_result']($request);
331
		}
332
333
		$clauses = array();
334
		$clauseParameters = array();
335
		if (!empty($categories))
336
		{
337
			$clauses[] = 'id_cat IN ({array_int:category_list})';
338
			$clauseParameters['category_list'] = $categories;
339
		}
340
		if (!empty($boards))
341
		{
342
			$clauses[] = 'id_board IN ({array_int:board_list})';
343
			$clauseParameters['board_list'] = $boards;
344
		}
345
346
		if (empty($clauses))
347
			redirectexit();
348
349
		$request = $smcFunc['db_query']('', '
350
			SELECT b.id_board
351
			FROM {db_prefix}boards AS b
352
			WHERE {query_see_board}
353
				AND b.' . implode(' OR b.', $clauses),
354
			array_merge($clauseParameters, array(
355
			))
356
		);
357
		$boards = array();
358
		while ($row = $smcFunc['db_fetch_assoc']($request))
359
			$boards[] = $row['id_board'];
360
		$smcFunc['db_free_result']($request);
361
362
		if (empty($boards))
363
			redirectexit();
364
365
		markBoardsRead($boards, isset($_REQUEST['unread']));
366
367
		foreach ($boards as $b)
368
		{
369
			if (isset($_SESSION['topicseen_cache'][$b]))
370
				$_SESSION['topicseen_cache'][$b] = array();
371
		}
372
373
		if (!isset($_REQUEST['unread']))
374
		{
375
			// Find all the boards this user can see.
376
			$result = $smcFunc['db_query']('', '
377
				SELECT b.id_board
378
				FROM {db_prefix}boards AS b
379
				WHERE b.id_parent IN ({array_int:parent_list})
380
					AND {query_see_board}',
381
				array(
382
					'parent_list' => $boards,
383
				)
384
			);
385
			if ($smcFunc['db_num_rows']($result) > 0)
386
			{
387
				$logBoardInserts = array();
388
				while ($row = $smcFunc['db_fetch_assoc']($result))
389
					$logBoardInserts[] = array($modSettings['maxMsgID'], $user_info['id'], $row['id_board']);
390
391
				$smcFunc['db_insert']('replace',
392
					'{db_prefix}log_boards',
393
					array('id_msg' => 'int', 'id_member' => 'int', 'id_board' => 'int'),
394
					$logBoardInserts,
395
					array('id_member', 'id_board')
396
				);
397
			}
398
			$smcFunc['db_free_result']($result);
399
400
			if (empty($board))
401
				redirectexit();
402
			else
403
				redirectexit('board=' . $board . '.0');
404
		}
405
		else
406
		{
407
			if (empty($board_info['parent']))
408
				redirectexit();
409
			else
410
				redirectexit('board=' . $board_info['parent'] . '.0');
411
		}
412
	}
413
}
414
415
/**
416
 * Get the id_member associated with the specified message.
417
 *
418
 * @param int $messageID The ID of the message
419
 * @return int The ID of the member associated with that post
420
 */
421
function getMsgMemberID($messageID)
422
{
423
	global $smcFunc;
424
425
	// Find the topic and make sure the member still exists.
426
	$result = $smcFunc['db_query']('', '
427
		SELECT COALESCE(mem.id_member, 0)
428
		FROM {db_prefix}messages AS m
429
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
430
		WHERE m.id_msg = {int:selected_message}
431
		LIMIT 1',
432
		array(
433
			'selected_message' => (int) $messageID,
434
		)
435
	);
436
	if ($smcFunc['db_num_rows']($result) > 0)
437
		list ($memberID) = $smcFunc['db_fetch_row']($result);
438
	// The message doesn't even exist.
439
	else
440
		$memberID = 0;
441
442
	$smcFunc['db_free_result']($result);
443
444
	return (int) $memberID;
445
}
446
447
/**
448
 * Modify the settings and position of a board.
449
 * Used by ManageBoards.php to change the settings of a board.
450
 *
451
 * @param int $board_id The ID of the board
452
 * @param array &$boardOptions An array of options related to the board
453
 */
454
function modifyBoard($board_id, &$boardOptions)
455
{
456
	global $cat_tree, $boards, $smcFunc;
457
458
	// Get some basic information about all boards and categories.
459
	getBoardTree();
460
461
	// Make sure given boards and categories exist.
462
	if (!isset($boards[$board_id]) || (isset($boardOptions['target_board']) && !isset($boards[$boardOptions['target_board']])) || (isset($boardOptions['target_category']) && !isset($cat_tree[$boardOptions['target_category']])))
463
		fatal_lang_error('no_board');
464
465
	$id = $board_id;
466
	call_integration_hook('integrate_pre_modify_board', array($id, &$boardOptions));
467
468
	// All things that will be updated in the database will be in $boardUpdates.
469
	$boardUpdates = array();
470
	$boardUpdateParameters = array();
471
472
	// In case the board has to be moved
473
	if (isset($boardOptions['move_to']))
474
	{
475
		// Move the board to the top of a given category.
476
		if ($boardOptions['move_to'] == 'top')
477
		{
478
			$id_cat = $boardOptions['target_category'];
479
			$child_level = 0;
480
			$id_parent = 0;
481
			$after = $cat_tree[$id_cat]['last_board_order'];
482
		}
483
484
		// Move the board to the bottom of a given category.
485
		elseif ($boardOptions['move_to'] == 'bottom')
486
		{
487
			$id_cat = $boardOptions['target_category'];
488
			$child_level = 0;
489
			$id_parent = 0;
490
			$after = 0;
491
			foreach ($cat_tree[$id_cat]['children'] as $id_board => $dummy)
492
				$after = max($after, $boards[$id_board]['order']);
493
		}
494
495
		// Make the board a child of a given board.
496
		elseif ($boardOptions['move_to'] == 'child')
497
		{
498
			$id_cat = $boards[$boardOptions['target_board']]['category'];
499
			$child_level = $boards[$boardOptions['target_board']]['level'] + 1;
500
			$id_parent = $boardOptions['target_board'];
501
502
			// People can be creative, in many ways...
503
			if (isChildOf($id_parent, $board_id))
504
				fatal_lang_error('mboards_parent_own_child_error', false);
505
			elseif ($id_parent == $board_id)
506
				fatal_lang_error('mboards_board_own_child_error', false);
507
508
			$after = $boards[$boardOptions['target_board']]['order'];
509
510
			// Check if there are already children and (if so) get the max board order.
511
			if (!empty($boards[$id_parent]['tree']['children']) && empty($boardOptions['move_first_child']))
512
				foreach ($boards[$id_parent]['tree']['children'] as $childBoard_id => $dummy)
513
					$after = max($after, $boards[$childBoard_id]['order']);
514
		}
515
516
		// Place a board before or after another board, on the same child level.
517
		elseif (in_array($boardOptions['move_to'], array('before', 'after')))
518
		{
519
			$id_cat = $boards[$boardOptions['target_board']]['category'];
520
			$child_level = $boards[$boardOptions['target_board']]['level'];
521
			$id_parent = $boards[$boardOptions['target_board']]['parent'];
522
			$after = $boards[$boardOptions['target_board']]['order'] - ($boardOptions['move_to'] == 'before' ? 1 : 0);
523
		}
524
525
		// Oops...?
526
		else
527
			trigger_error('modifyBoard(): The move_to value \'' . $boardOptions['move_to'] . '\' is incorrect', E_USER_ERROR);
528
529
		// Get a list of children of this board.
530
		$childList = array();
531
		recursiveBoards($childList, $boards[$board_id]['tree']);
532
533
		// See if there are changes that affect children.
534
		$childUpdates = array();
535
		$levelDiff = $child_level - $boards[$board_id]['level'];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $child_level does not seem to be defined for all execution paths leading up to this point.
Loading history...
536
		if ($levelDiff != 0)
537
			$childUpdates[] = 'child_level = child_level ' . ($levelDiff > 0 ? '+ ' : '') . '{int:level_diff}';
538
		if ($id_cat != $boards[$board_id]['category'])
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $id_cat does not seem to be defined for all execution paths leading up to this point.
Loading history...
539
			$childUpdates[] = 'id_cat = {int:category}';
540
541
		// Fix the children of this board.
542
		if (!empty($childList) && !empty($childUpdates))
543
			$smcFunc['db_query']('', '
544
				UPDATE {db_prefix}boards
545
				SET ' . implode(',
546
					', $childUpdates) . '
547
				WHERE id_board IN ({array_int:board_list})',
548
				array(
549
					'board_list' => $childList,
550
					'category' => $id_cat,
551
					'level_diff' => $levelDiff,
552
				)
553
			);
554
555
		// Make some room for this spot.
556
		$smcFunc['db_query']('', '
557
			UPDATE {db_prefix}boards
558
			SET board_order = board_order + {int:new_order}
559
			WHERE board_order > {int:insert_after}
560
				AND id_board != {int:selected_board}',
561
			array(
562
				'insert_after' => $after,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $after does not seem to be defined for all execution paths leading up to this point.
Loading history...
563
				'selected_board' => $board_id,
564
				'new_order' => 1 + count($childList),
565
			)
566
		);
567
568
		$boardUpdates[] = 'id_cat = {int:id_cat}';
569
		$boardUpdates[] = 'id_parent = {int:id_parent}';
570
		$boardUpdates[] = 'child_level = {int:child_level}';
571
		$boardUpdates[] = 'board_order = {int:board_order}';
572
		$boardUpdateParameters += array(
573
			'id_cat' => $id_cat,
574
			'id_parent' => $id_parent,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $id_parent does not seem to be defined for all execution paths leading up to this point.
Loading history...
575
			'child_level' => $child_level,
576
			'board_order' => $after + 1,
577
		);
578
	}
579
580
	// This setting is a little twisted in the database...
581
	if (isset($boardOptions['posts_count']))
582
	{
583
		$boardUpdates[] = 'count_posts = {int:count_posts}';
584
		$boardUpdateParameters['count_posts'] = $boardOptions['posts_count'] ? 0 : 1;
585
	}
586
587
	// Set the theme for this board.
588
	if (isset($boardOptions['board_theme']))
589
	{
590
		$boardUpdates[] = 'id_theme = {int:id_theme}';
591
		$boardUpdateParameters['id_theme'] = (int) $boardOptions['board_theme'];
592
	}
593
594
	// Should the board theme override the user preferred theme?
595
	if (isset($boardOptions['override_theme']))
596
	{
597
		$boardUpdates[] = 'override_theme = {int:override_theme}';
598
		$boardUpdateParameters['override_theme'] = $boardOptions['override_theme'] ? 1 : 0;
599
	}
600
601
	// Who's allowed to access this board.
602
	if (isset($boardOptions['access_groups']))
603
	{
604
		$boardUpdates[] = 'member_groups = {string:member_groups}';
605
		$boardUpdateParameters['member_groups'] = implode(',', $boardOptions['access_groups']);
606
	}
607
608
	// And who isn't.
609
	if (isset($boardOptions['deny_groups']))
610
	{
611
		$boardUpdates[] = 'deny_member_groups = {string:deny_groups}';
612
		$boardUpdateParameters['deny_groups'] = implode(',', $boardOptions['deny_groups']);
613
	}
614
615
	if (isset($boardOptions['board_name']))
616
	{
617
		$boardUpdates[] = 'name = {string:board_name}';
618
		$boardUpdateParameters['board_name'] = $boardOptions['board_name'];
619
	}
620
621
	if (isset($boardOptions['board_description']))
622
	{
623
		$boardUpdates[] = 'description = {string:board_description}';
624
		$boardUpdateParameters['board_description'] = $boardOptions['board_description'];
625
	}
626
627
	if (isset($boardOptions['profile']))
628
	{
629
		$boardUpdates[] = 'id_profile = {int:profile}';
630
		$boardUpdateParameters['profile'] = (int) $boardOptions['profile'];
631
	}
632
633
	if (isset($boardOptions['redirect']))
634
	{
635
		$boardUpdates[] = 'redirect = {string:redirect}';
636
		$boardUpdateParameters['redirect'] = $boardOptions['redirect'];
637
	}
638
639
	if (isset($boardOptions['num_posts']))
640
	{
641
		$boardUpdates[] = 'num_posts = {int:num_posts}';
642
		$boardUpdateParameters['num_posts'] = (int) $boardOptions['num_posts'];
643
	}
644
645
	$id = $board_id;
646
	call_integration_hook('integrate_modify_board', array($id, $boardOptions, &$boardUpdates, &$boardUpdateParameters));
647
648
	// Do the updates (if any).
649
	if (!empty($boardUpdates))
650
		$smcFunc['db_query']('', '
651
			UPDATE {db_prefix}boards
652
			SET
653
				' . implode(',
654
				', $boardUpdates) . '
655
			WHERE id_board = {int:selected_board}',
656
			array_merge($boardUpdateParameters, array(
657
				'selected_board' => $board_id,
658
			))
659
		);
660
661
	// Before we add new access_groups or deny_groups, remove all of the old entries
662
	$smcFunc['db_query']('', '
663
		DELETE FROM {db_prefix}board_permissions_view
664
		WHERE id_board = {int:selected_board}',
665
		array(
666
			'selected_board' => $board_id,
667
		)
668
	);
669
670
	// Do permission sync
671
	if (!empty($boardOptions['deny_groups']))
672
	{
673
		$insert = array();
674
		foreach ($boardOptions['deny_groups'] as $value)
675
			$insert[] = array($value, $board_id, 1);
676
677
		$smcFunc['db_insert']('insert',
678
			'{db_prefix}board_permissions_view',
679
			array('id_group' => 'int', 'id_board' => 'int', 'deny' => 'int'),
680
			$insert,
681
			array('id_group', 'id_board', 'deny')
682
		);
683
	}
684
685
	if (!empty($boardOptions['access_groups']))
686
	{
687
		$insert = array();
688
		foreach ($boardOptions['access_groups'] as $value)
689
			$insert[] = array($value, $board_id, 0);
690
691
		$smcFunc['db_insert']('insert',
692
			'{db_prefix}board_permissions_view',
693
			array('id_group' => 'int', 'id_board' => 'int', 'deny' => 'int'),
694
			$insert,
695
			array('id_group', 'id_board', 'deny')
696
		);
697
	}
698
699
	// Set moderators of this board.
700
	if (isset($boardOptions['moderators']) || isset($boardOptions['moderator_string']) || isset($boardOptions['moderator_groups']) || isset($boardOptions['moderator_group_string']))
701
	{
702
		// Reset current moderators for this board - if there are any!
703
		$smcFunc['db_query']('', '
704
			DELETE FROM {db_prefix}moderators
705
			WHERE id_board = {int:board_list}',
706
			array(
707
				'board_list' => $board_id,
708
			)
709
		);
710
711
		// Validate and get the IDs of the new moderators.
712
		if (isset($boardOptions['moderator_string']) && trim($boardOptions['moderator_string']) != '')
713
		{
714
			// Divvy out the usernames, remove extra space.
715
			$moderator_string = strtr($smcFunc['htmlspecialchars']($boardOptions['moderator_string'], ENT_QUOTES), array('&quot;' => '"'));
716
			preg_match_all('~"([^"]+)"~', $moderator_string, $matches);
717
			$moderators = array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $moderator_string)));
718
			for ($k = 0, $n = count($moderators); $k < $n; $k++)
719
			{
720
				$moderators[$k] = trim($moderators[$k]);
721
722
				if (strlen($moderators[$k]) == 0)
723
					unset($moderators[$k]);
724
			}
725
726
			// Find all the id_member's for the member_name's in the list.
727
			if (empty($boardOptions['moderators']))
728
				$boardOptions['moderators'] = array();
729
			if (!empty($moderators))
730
			{
731
				$request = $smcFunc['db_query']('', '
732
					SELECT id_member
733
					FROM {db_prefix}members
734
					WHERE member_name IN ({array_string:moderator_list}) OR real_name IN ({array_string:moderator_list})
735
					LIMIT {int:limit}',
736
					array(
737
						'moderator_list' => $moderators,
738
						'limit' => count($moderators),
739
					)
740
				);
741
				while ($row = $smcFunc['db_fetch_assoc']($request))
742
					$boardOptions['moderators'][] = $row['id_member'];
743
				$smcFunc['db_free_result']($request);
744
			}
745
		}
746
747
		// Add the moderators to the board.
748
		if (!empty($boardOptions['moderators']))
749
		{
750
			$inserts = array();
751
			foreach ($boardOptions['moderators'] as $moderator)
752
				$inserts[] = array($board_id, $moderator);
753
754
			$smcFunc['db_insert']('insert',
755
				'{db_prefix}moderators',
756
				array('id_board' => 'int', 'id_member' => 'int'),
757
				$inserts,
758
				array('id_board', 'id_member')
759
			);
760
		}
761
762
		// Reset current moderator groups for this board - if there are any!
763
		$smcFunc['db_query']('', '
764
			DELETE FROM {db_prefix}moderator_groups
765
			WHERE id_board = {int:board_list}',
766
			array(
767
				'board_list' => $board_id,
768
			)
769
		);
770
771
		// Validate and get the IDs of the new moderator groups.
772
		if (isset($boardOptions['moderator_group_string']) && trim($boardOptions['moderator_group_string']) != '')
773
		{
774
			// Divvy out the group names, remove extra space.
775
			$moderator_group_string = strtr($smcFunc['htmlspecialchars']($boardOptions['moderator_group_string'], ENT_QUOTES), array('&quot;' => '"'));
776
			preg_match_all('~"([^"]+)"~', $moderator_group_string, $matches);
777
			$moderator_groups = array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $moderator_group_string)));
778
			for ($k = 0, $n = count($moderator_groups); $k < $n; $k++)
779
			{
780
				$moderator_groups[$k] = trim($moderator_groups[$k]);
781
782
				if (strlen($moderator_groups[$k]) == 0)
783
					unset($moderator_groups[$k]);
784
			}
785
786
			/* 	Find all the id_group's for all the group names in the list
787
				But skip any invalid ones (invisible/post groups/Administrator/Moderator) */
788
			if (empty($boardOptions['moderator_groups']))
789
				$boardOptions['moderator_groups'] = array();
790
			if (!empty($moderator_groups))
791
			{
792
				$request = $smcFunc['db_query']('', '
793
					SELECT id_group
794
					FROM {db_prefix}membergroups
795
					WHERE group_name IN ({array_string:moderator_group_list})
796
						AND hidden = {int:visible}
797
						AND min_posts = {int:negative_one}
798
						AND id_group NOT IN ({array_int:invalid_groups})
799
					LIMIT {int:limit}',
800
					array(
801
						'visible' => 0,
802
						'negative_one' => -1,
803
						'invalid_groups' => array(1, 3),
804
						'moderator_group_list' => $moderator_groups,
805
						'limit' => count($moderator_groups),
806
					)
807
				);
808
				while ($row = $smcFunc['db_fetch_assoc']($request))
809
				{
810
					$boardOptions['moderator_groups'][] = $row['id_group'];
811
				}
812
				$smcFunc['db_free_result']($request);
813
			}
814
		}
815
816
		// Add the moderator groups to the board.
817
		if (!empty($boardOptions['moderator_groups']))
818
		{
819
			$inserts = array();
820
			foreach ($boardOptions['moderator_groups'] as $moderator_group)
821
				$inserts[] = array($board_id, $moderator_group);
822
823
			$smcFunc['db_insert']('insert',
824
				'{db_prefix}moderator_groups',
825
				array('id_board' => 'int', 'id_group' => 'int'),
826
				$inserts,
827
				array('id_board', 'id_group')
828
			);
829
		}
830
831
		// Note that caches can now be wrong!
832
		updateSettings(array('settings_updated' => time()));
833
	}
834
835
	if (isset($boardOptions['move_to']))
836
		reorderBoards();
837
838
	clean_cache('data');
839
840
	if (empty($boardOptions['dont_log']))
841
		logAction('edit_board', array('board' => $board_id), 'admin');
842
}
843
844
/**
845
 * Create a new board and set its properties and position.
846
 * Allows (almost) the same options as the modifyBoard() function.
847
 * With the option inherit_permissions set, the parent board permissions
848
 * will be inherited.
849
 *
850
 * @param array $boardOptions An array of information for the new board
851
 * @return int The ID of the new board
852
 */
853
function createBoard($boardOptions)
854
{
855
	global $boards, $smcFunc;
856
857
	// Trigger an error if one of the required values is not set.
858
	if (!isset($boardOptions['board_name']) || trim($boardOptions['board_name']) == '' || !isset($boardOptions['move_to']) || !isset($boardOptions['target_category']))
859
		trigger_error('createBoard(): One or more of the required options is not set', E_USER_ERROR);
860
861
	if (in_array($boardOptions['move_to'], array('child', 'before', 'after')) && !isset($boardOptions['target_board']))
862
		trigger_error('createBoard(): Target board is not set', E_USER_ERROR);
863
864
	// Set every optional value to its default value.
865
	$boardOptions += array(
866
		'posts_count' => true,
867
		'override_theme' => false,
868
		'board_theme' => 0,
869
		'access_groups' => array(),
870
		'board_description' => '',
871
		'profile' => 1,
872
		'moderators' => '',
873
		'inherit_permissions' => true,
874
		'dont_log' => true,
875
	);
876
877
	$default_memgrps = '-1,0';
878
879
	$board_columns = array(
880
		'id_cat' => 'int', 'name' => 'string-255', 'description' => 'string', 'board_order' => 'int',
881
		'member_groups' => 'string', 'redirect' => 'string',
882
	);
883
	$board_parameters = array(
884
		$boardOptions['target_category'], $boardOptions['board_name'], '', 0,
885
		$default_memgrps, '',
886
	);
887
888
	call_integration_hook('integrate_create_board', array(&$boardOptions, &$board_columns, &$board_parameters));
889
890
	// Insert a board, the settings are dealt with later.
891
	$board_id = $smcFunc['db_insert']('',
892
		'{db_prefix}boards',
893
		$board_columns,
894
		$board_parameters,
895
		array('id_board'),
896
		1
897
	);
898
899
	$insert = array();
900
901
	foreach (explode(',', $default_memgrps) as $value)
902
		$insert[] = array($value, $board_id, 0);
903
904
	$smcFunc['db_insert']('',
905
		'{db_prefix}board_permissions_view',
906
		array('id_group' => 'int', 'id_board' => 'int', 'deny' => 'int'),
907
		$insert,
908
		array('id_group', 'id_board', 'deny'),
909
		1
910
	);
911
912
	if (empty($board_id))
913
		return 0;
914
915
	// Change the board according to the given specifications.
916
	modifyBoard($board_id, $boardOptions);
917
918
	// Do we want the parent permissions to be inherited?
919
	if ($boardOptions['inherit_permissions'])
920
	{
921
		getBoardTree();
922
923
		if (!empty($boards[$board_id]['parent']))
924
		{
925
			$request = $smcFunc['db_query']('', '
926
				SELECT id_profile
927
				FROM {db_prefix}boards
928
				WHERE id_board = {int:board_parent}
929
				LIMIT 1',
930
				array(
931
					'board_parent' => (int) $boards[$board_id]['parent'],
932
				)
933
			);
934
			list ($boardOptions['profile']) = $smcFunc['db_fetch_row']($request);
935
			$smcFunc['db_free_result']($request);
936
937
			$smcFunc['db_query']('', '
938
				UPDATE {db_prefix}boards
939
				SET id_profile = {int:new_profile}
940
				WHERE id_board = {int:current_board}',
941
				array(
942
					'new_profile' => $boardOptions['profile'],
943
					'current_board' => $board_id,
944
				)
945
			);
946
		}
947
	}
948
949
	// Clean the data cache.
950
	clean_cache('data');
951
952
	// Created it.
953
	logAction('add_board', array('board' => $board_id), 'admin');
954
955
	// Here you are, a new board, ready to be spammed.
956
	return $board_id;
957
}
958
959
/**
960
 * Remove one or more boards.
961
 * Allows to move the children of the board before deleting it
962
 * if moveChildrenTo is set to null, the child boards will be deleted.
963
 * Deletes:
964
 *   - all topics that are on the given boards;
965
 *   - all information that's associated with the given boards;
966
 * updates the statistics to reflect the new situation.
967
 *
968
 * @param array $boards_to_remove The boards to remove
969
 * @param int $moveChildrenTo The ID of the board to move the child boards to (null to remove the child boards, 0 to make them a top-level board)
970
 */
971
function deleteBoards($boards_to_remove, $moveChildrenTo = null)
972
{
973
	global $sourcedir, $boards, $smcFunc;
974
975
	// No boards to delete? Return!
976
	if (empty($boards_to_remove))
977
		return;
978
979
	getBoardTree();
980
981
	call_integration_hook('integrate_delete_board', array($boards_to_remove, &$moveChildrenTo));
982
983
	// If $moveChildrenTo is set to null, include the children in the removal.
984
	if ($moveChildrenTo === null)
985
	{
986
		// Get a list of the child boards that will also be removed.
987
		$child_boards_to_remove = array();
988
		foreach ($boards_to_remove as $board_to_remove)
989
			recursiveBoards($child_boards_to_remove, $boards[$board_to_remove]['tree']);
990
991
		// Merge the children with their parents.
992
		if (!empty($child_boards_to_remove))
993
			$boards_to_remove = array_unique(array_merge($boards_to_remove, $child_boards_to_remove));
994
	}
995
	// Move the children to a safe home.
996
	else
997
	{
998
		foreach ($boards_to_remove as $id_board)
999
		{
1000
			// @todo Separate category?
1001
			if ($moveChildrenTo === 0)
1002
				fixChildren($id_board, 0, 0);
1003
			else
1004
				fixChildren($id_board, $boards[$moveChildrenTo]['level'] + 1, $moveChildrenTo);
1005
		}
1006
	}
1007
1008
	// Delete ALL topics in the selected boards (done first so topics can't be marooned.)
1009
	$request = $smcFunc['db_query']('', '
1010
		SELECT id_topic
1011
		FROM {db_prefix}topics
1012
		WHERE id_board IN ({array_int:boards_to_remove})',
1013
		array(
1014
			'boards_to_remove' => $boards_to_remove,
1015
		)
1016
	);
1017
	$topics = array();
1018
	while ($row = $smcFunc['db_fetch_assoc']($request))
1019
		$topics[] = $row['id_topic'];
1020
	$smcFunc['db_free_result']($request);
1021
1022
	require_once($sourcedir . '/RemoveTopic.php');
1023
	removeTopics($topics, false);
1024
1025
	// Delete the board's logs.
1026
	$smcFunc['db_query']('', '
1027
		DELETE FROM {db_prefix}log_mark_read
1028
		WHERE id_board IN ({array_int:boards_to_remove})',
1029
		array(
1030
			'boards_to_remove' => $boards_to_remove,
1031
		)
1032
	);
1033
	$smcFunc['db_query']('', '
1034
		DELETE FROM {db_prefix}log_boards
1035
		WHERE id_board IN ({array_int:boards_to_remove})',
1036
		array(
1037
			'boards_to_remove' => $boards_to_remove,
1038
		)
1039
	);
1040
	$smcFunc['db_query']('', '
1041
		DELETE FROM {db_prefix}log_notify
1042
		WHERE id_board IN ({array_int:boards_to_remove})',
1043
		array(
1044
			'boards_to_remove' => $boards_to_remove,
1045
		)
1046
	);
1047
1048
	// Delete this board's moderators.
1049
	$smcFunc['db_query']('', '
1050
		DELETE FROM {db_prefix}moderators
1051
		WHERE id_board IN ({array_int:boards_to_remove})',
1052
		array(
1053
			'boards_to_remove' => $boards_to_remove,
1054
		)
1055
	);
1056
1057
	// Delete this board's moderator groups.
1058
	$smcFunc['db_query']('', '
1059
		DELETE FROM {db_prefix}moderator_groups
1060
		WHERE id_board IN ({array_int:boards_to_remove})',
1061
		array(
1062
			'boards_to_remove' => $boards_to_remove,
1063
		)
1064
	);
1065
1066
	// Delete any extra events in the calendar.
1067
	$smcFunc['db_query']('', '
1068
		DELETE FROM {db_prefix}calendar
1069
		WHERE id_board IN ({array_int:boards_to_remove})',
1070
		array(
1071
			'boards_to_remove' => $boards_to_remove,
1072
		)
1073
	);
1074
1075
	// Delete any message icons that only appear on these boards.
1076
	$smcFunc['db_query']('', '
1077
		DELETE FROM {db_prefix}message_icons
1078
		WHERE id_board IN ({array_int:boards_to_remove})',
1079
		array(
1080
			'boards_to_remove' => $boards_to_remove,
1081
		)
1082
	);
1083
1084
	// Delete the boards.
1085
	$smcFunc['db_query']('', '
1086
		DELETE FROM {db_prefix}boards
1087
		WHERE id_board IN ({array_int:boards_to_remove})',
1088
		array(
1089
			'boards_to_remove' => $boards_to_remove,
1090
		)
1091
	);
1092
1093
	// Delete permissions
1094
	$smcFunc['db_query']('', '
1095
		DELETE FROM {db_prefix}board_permissions_view
1096
		WHERE id_board IN ({array_int:boards_to_remove})',
1097
		array(
1098
			'boards_to_remove' => $boards_to_remove,
1099
		)
1100
	);
1101
1102
	// Latest message/topic might not be there anymore.
1103
	updateStats('message');
1104
	updateStats('topic');
1105
	updateSettings(array(
1106
		'calendar_updated' => time(),
1107
	));
1108
1109
	// Plus reset the cache to stop people getting odd results.
1110
	updateSettings(array('settings_updated' => time()));
1111
1112
	// Clean the cache as well.
1113
	clean_cache('data');
1114
1115
	// Let's do some serious logging.
1116
	foreach ($boards_to_remove as $id_board)
1117
		logAction('delete_board', array('boardname' => $boards[$id_board]['name']), 'admin');
1118
1119
	reorderBoards();
1120
}
1121
1122
/**
1123
 * Put all boards in the right order and sorts the records of the boards table.
1124
 * Used by modifyBoard(), deleteBoards(), modifyCategory(), and deleteCategories() functions
1125
 */
1126
function reorderBoards()
1127
{
1128
	global $cat_tree, $boardList, $boards, $smcFunc;
1129
1130
	getBoardTree();
1131
1132
	// Set the board order for each category.
1133
	$board_order = 0;
1134
	foreach ($cat_tree as $catID => $dummy)
1135
	{
1136
		foreach ($boardList[$catID] as $boardID)
1137
			if ($boards[$boardID]['order'] != ++$board_order)
1138
				$smcFunc['db_query']('', '
1139
					UPDATE {db_prefix}boards
1140
					SET board_order = {int:new_order}
1141
					WHERE id_board = {int:selected_board}',
1142
					array(
1143
						'new_order' => $board_order,
1144
						'selected_board' => $boardID,
1145
					)
1146
				);
1147
	}
1148
1149
	// Empty the board order cache
1150
	cache_put_data('board_order', null, -3600);
1151
}
1152
1153
/**
1154
 * Fixes the children of a board by setting their child_levels to new values.
1155
 * Used when a board is deleted or moved, to affect its children.
1156
 *
1157
 * @param int $parent The ID of the parent board
1158
 * @param int $newLevel The new child level for each of the child boards
1159
 * @param int $newParent The ID of the new parent board
1160
 */
1161
function fixChildren($parent, $newLevel, $newParent)
1162
{
1163
	global $smcFunc;
1164
1165
	// Grab all children of $parent...
1166
	$result = $smcFunc['db_query']('', '
1167
		SELECT id_board
1168
		FROM {db_prefix}boards
1169
		WHERE id_parent = {int:parent_board}',
1170
		array(
1171
			'parent_board' => $parent,
1172
		)
1173
	);
1174
	$children = array();
1175
	while ($row = $smcFunc['db_fetch_assoc']($result))
1176
		$children[] = $row['id_board'];
1177
	$smcFunc['db_free_result']($result);
1178
1179
	// ...and set it to a new parent and child_level.
1180
	$smcFunc['db_query']('', '
1181
		UPDATE {db_prefix}boards
1182
		SET id_parent = {int:new_parent}, child_level = {int:new_child_level}
1183
		WHERE id_parent = {int:parent_board}',
1184
		array(
1185
			'new_parent' => $newParent,
1186
			'new_child_level' => $newLevel,
1187
			'parent_board' => $parent,
1188
		)
1189
	);
1190
1191
	// Recursively fix the children of the children.
1192
	foreach ($children as $child)
1193
		fixChildren($child, $newLevel + 1, $child);
1194
}
1195
1196
/**
1197
 * Tries to load up the entire board order and category very very quickly
1198
 * Returns an array with two elements, cats and boards
1199
 *
1200
 * @return array An array of categories and boards
1201
 */
1202
function getTreeOrder()
1203
{
1204
	global $smcFunc;
1205
1206
	static $tree_order = array(
1207
		'cats' => array(),
1208
		'boards' => array(),
1209
	);
1210
1211
	if (!empty($tree_order['boards']))
1212
		return $tree_order;
1213
1214
	if (($cached = cache_get_data('board_order', 86400)) !== null)
1215
	{
1216
		$tree_order = $cached;
1217
		return $cached;
1218
	}
1219
1220
	$request = $smcFunc['db_query']('', '
1221
		SELECT b.id_board, b.id_cat
1222
		FROM {db_prefix}boards AS b
1223
		ORDER BY b.board_order',
1224
		array()
1225
	);
1226
1227
	foreach ($smcFunc['db_fetch_all']($request) as $row)
1228
	{
1229
		if (!in_array($row['id_cat'], $tree_order['cats']))
1230
			$tree_order['cats'][] = $row['id_cat'];
1231
		$tree_order['boards'][] = $row['id_board'];
1232
	}
1233
	$smcFunc['db_free_result']($request);
1234
1235
	cache_put_data('board_order', $tree_order, 86400);
1236
1237
	return $tree_order;
1238
}
1239
1240
/**
1241
 * Takes a board array and sorts it
1242
 *
1243
 * @param array &$boards The boards
1244
 */
1245
function sortBoards(array &$boards)
1246
{
1247
	$tree = getTreeOrder();
1248
1249
	$ordered = array();
1250
	foreach ($tree['boards'] as $board)
1251
		if (!empty($boards[$board]))
1252
		{
1253
			$ordered[$board] = $boards[$board];
1254
1255
			if (is_array($ordered[$board]) && !empty($ordered[$board]['boards']))
1256
				sortBoards($ordered[$board]['boards']);
1257
1258
			if (is_array($ordered[$board]) && !empty($ordered[$board]['children']))
1259
				sortBoards($ordered[$board]['children']);
1260
		}
1261
1262
	$boards = $ordered;
1263
}
1264
1265
/**
1266
 * Takes a category array and sorts it
1267
 *
1268
 * @param array &$categories The categories
1269
 */
1270
function sortCategories(array &$categories)
1271
{
1272
	$tree = getTreeOrder();
1273
1274
	$ordered = array();
1275
	foreach ($tree['cats'] as $cat)
1276
		if (!empty($categories[$cat]))
1277
		{
1278
			$ordered[$cat] = $categories[$cat];
1279
			if (!empty($ordered[$cat]['boards']))
1280
				sortBoards($ordered[$cat]['boards']);
1281
		}
1282
1283
	$categories = $ordered;
1284
}
1285
1286
/**
1287
 * Returns the given board's moderators, with their names and links
1288
 *
1289
 * @param array $boards The boards to get moderators of
1290
 * @return array An array containing information about the moderators of each board
1291
 */
1292
function getBoardModerators(array $boards)
1293
{
1294
	global $smcFunc, $scripturl, $txt;
1295
1296
	if (empty($boards))
1297
		return array();
1298
1299
	$request = $smcFunc['db_query']('', '
1300
		SELECT mem.id_member, mem.real_name, mo.id_board
1301
		FROM {db_prefix}moderators AS mo
1302
			INNER JOIN {db_prefix}members AS mem ON (mem.id_member = mo.id_member)
1303
		WHERE mo.id_board IN ({array_int:boards})',
1304
		array(
1305
			'boards' => $boards,
1306
		)
1307
	);
1308
	$moderators = array();
1309
	while ($row = $smcFunc['db_fetch_assoc']($request))
1310
	{
1311
		if (empty($moderators[$row['id_board']]))
1312
			$moderators[$row['id_board']] = array();
1313
1314
		$moderators[$row['id_board']][] = array(
1315
			'id' => $row['id_member'],
1316
			'name' => $row['real_name'],
1317
			'href' => $scripturl . '?action=profile;u=' . $row['id_member'],
1318
			'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '" title="' . $txt['board_moderator'] . '">' . $row['real_name'] . '</a>',
1319
		);
1320
	}
1321
	$smcFunc['db_free_result']($request);
1322
1323
	return $moderators;
1324
}
1325
1326
/**
1327
 * Returns board's moderator groups with their names and link
1328
 *
1329
 * @param array $boards The boards to get moderator groups of
1330
 * @return array An array containing information about the groups assigned to moderate each board
1331
 */
1332
function getBoardModeratorGroups(array $boards)
1333
{
1334
	global $smcFunc, $scripturl, $txt;
1335
1336
	if (empty($boards))
1337
		return array();
1338
1339
	$request = $smcFunc['db_query']('', '
1340
		SELECT mg.id_group, mg.group_name, bg.id_board
1341
		FROM {db_prefix}moderator_groups AS bg
1342
			INNER JOIN {db_prefix}membergroups AS mg ON (mg.id_group = bg.id_group)
1343
		WHERE bg.id_board IN ({array_int:boards})',
1344
		array(
1345
			'boards' => $boards,
1346
		)
1347
	);
1348
	$groups = array();
1349
	while ($row = $smcFunc['db_fetch_assoc']($request))
1350
	{
1351
		if (empty($groups[$row['id_board']]))
1352
			$groups[$row['id_board']] = array();
1353
1354
		$groups[$row['id_board']][] = array(
1355
			'id' => $row['id_group'],
1356
			'name' => $row['group_name'],
1357
			'href' => $scripturl . '?action=groups;sa=members;group=' . $row['id_group'],
1358
			'link' => '<a href="' . $scripturl . '?action=groups;sa=members;group=' . $row['id_group'] . '" title="' . $txt['board_moderator'] . '">' . $row['group_name'] . '</a>',
1359
		);
1360
	}
1361
1362
	return $groups;
1363
}
1364
1365
/**
1366
 * Load a lot of useful information regarding the boards and categories.
1367
 * The information retrieved is stored in globals:
1368
 *  $boards		properties of each board.
1369
 *  $boardList	a list of boards grouped by category ID.
1370
 *  $cat_tree	properties of each category.
1371
 */
1372
function getBoardTree()
1373
{
1374
	global $cat_tree, $boards, $boardList, $smcFunc;
1375
1376
	$boardColumns = array(
1377
		'COALESCE(b.id_board, 0) AS id_board', 'b.id_parent', 'b.name AS board_name',
1378
		'b.description', 'b.child_level', 'b.board_order', 'b.count_posts', 'b.member_groups',
1379
		'b.id_theme', 'b.override_theme', 'b.id_profile', 'b.redirect', 'b.num_posts',
1380
		'b.num_topics', 'b.deny_member_groups', 'c.id_cat', 'c.name AS cat_name',
1381
		'c.description AS cat_desc', 'c.cat_order', 'c.can_collapse',
1382
	);
1383
	$boardParameters = array();
1384
	$boardJoins = array();
1385
	$boardWhere = array();
1386
	$boardOrder = array('c.cat_order', 'b.child_level', 'b.board_order');
1387
1388
	// Let mods add extra columns, parameters, etc., to the SELECT query
1389
	call_integration_hook('integrate_pre_boardtree', array(&$boardColumns, &$boardParameters, &$boardJoins, &$boardWhere, &$boardOrder));
1390
1391
	$boardColumns = array_unique($boardColumns);
1392
	$boardParameters = array_unique($boardParameters);
1393
	$boardJoins = array_unique($boardJoins);
1394
	$boardWhere = array_unique($boardWhere);
1395
	$boardOrder = array_unique($boardOrder);
1396
1397
	// Getting all the board and category information you'd ever wanted.
1398
	$request = $smcFunc['db_query']('', '
1399
		SELECT
1400
			' . implode(', ', $boardColumns) . '
1401
		FROM {db_prefix}categories AS c
1402
			LEFT JOIN {db_prefix}boards AS b ON (b.id_cat = c.id_cat)' . implode('
1403
			', $boardJoins) . '
1404
		WHERE {query_see_board}' . (empty($boardWhere) ? '' : '
1405
			AND (' . implode(') AND (', $boardWhere) . ')') . '
1406
		ORDER BY ' . implode(', ', $boardOrder),
1407
		$boardParameters
1408
	);
1409
	$cat_tree = array();
1410
	$boards = array();
1411
	$last_board_order = 0;
1412
	while ($row = $smcFunc['db_fetch_assoc']($request))
1413
	{
1414
		if (!isset($cat_tree[$row['id_cat']]))
1415
		{
1416
			$cat_tree[$row['id_cat']] = array(
1417
				'node' => array(
1418
					'id' => $row['id_cat'],
1419
					'name' => $row['cat_name'],
1420
					'description' => $row['cat_desc'],
1421
					'order' => $row['cat_order'],
1422
					'can_collapse' => $row['can_collapse']
1423
				),
1424
				'is_first' => empty($cat_tree),
1425
				'last_board_order' => $last_board_order,
1426
				'children' => array()
1427
			);
1428
			$prevBoard = 0;
1429
			$curLevel = 0;
1430
		}
1431
1432
		if (!empty($row['id_board']))
1433
		{
1434
			if ($row['child_level'] != $curLevel)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $curLevel does not seem to be defined for all execution paths leading up to this point.
Loading history...
1435
				$prevBoard = 0;
1436
1437
			$boards[$row['id_board']] = array(
1438
				'id' => $row['id_board'],
1439
				'category' => $row['id_cat'],
1440
				'parent' => $row['id_parent'],
1441
				'level' => $row['child_level'],
1442
				'order' => $row['board_order'],
1443
				'name' => $row['board_name'],
1444
				'member_groups' => explode(',', $row['member_groups']),
1445
				'deny_groups' => explode(',', $row['deny_member_groups']),
1446
				'description' => $row['description'],
1447
				'count_posts' => empty($row['count_posts']),
1448
				'posts' => $row['num_posts'],
1449
				'topics' => $row['num_topics'],
1450
				'theme' => $row['id_theme'],
1451
				'override_theme' => $row['override_theme'],
1452
				'profile' => $row['id_profile'],
1453
				'redirect' => $row['redirect'],
1454
				'prev_board' => $prevBoard
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $prevBoard does not seem to be defined for all execution paths leading up to this point.
Loading history...
1455
			);
1456
			$prevBoard = $row['id_board'];
1457
			$last_board_order = $row['board_order'];
1458
1459
			if (empty($row['child_level']))
1460
			{
1461
				$cat_tree[$row['id_cat']]['children'][$row['id_board']] = array(
1462
					'node' => &$boards[$row['id_board']],
1463
					'is_first' => empty($cat_tree[$row['id_cat']]['children']),
1464
					'children' => array()
1465
				);
1466
				$boards[$row['id_board']]['tree'] = &$cat_tree[$row['id_cat']]['children'][$row['id_board']];
1467
			}
1468
			else
1469
			{
1470
				// Parent doesn't exist!
1471
				if (!isset($boards[$row['id_parent']]['tree']))
1472
					fatal_lang_error('no_valid_parent', false, array($row['board_name']));
1473
1474
				// Wrong childlevel...we can silently fix this...
1475
				if ($boards[$row['id_parent']]['tree']['node']['level'] != $row['child_level'] - 1)
1476
					$smcFunc['db_query']('', '
1477
						UPDATE {db_prefix}boards
1478
						SET child_level = {int:new_child_level}
1479
						WHERE id_board = {int:selected_board}',
1480
						array(
1481
							'new_child_level' => $boards[$row['id_parent']]['tree']['node']['level'] + 1,
1482
							'selected_board' => $row['id_board'],
1483
						)
1484
					);
1485
1486
				$boards[$row['id_parent']]['tree']['children'][$row['id_board']] = array(
1487
					'node' => &$boards[$row['id_board']],
1488
					'is_first' => empty($boards[$row['id_parent']]['tree']['children']),
1489
					'children' => array()
1490
				);
1491
				$boards[$row['id_board']]['tree'] = &$boards[$row['id_parent']]['tree']['children'][$row['id_board']];
1492
			}
1493
		}
1494
1495
		// If mods want to do anything with this board before we move on, now's the time
1496
		call_integration_hook('integrate_boardtree_board', array($row));
1497
	}
1498
	$smcFunc['db_free_result']($request);
1499
1500
	// Get a list of all the boards in each category (using recursion).
1501
	$boardList = array();
1502
	foreach ($cat_tree as $catID => $node)
1503
	{
1504
		$boardList[$catID] = array();
1505
		recursiveBoards($boardList[$catID], $node);
1506
	}
1507
}
1508
1509
/**
1510
 * Recursively get a list of boards.
1511
 * Used by getBoardTree
1512
 *
1513
 * @param array &$_boardList The board list
1514
 * @param array &$_tree The board tree
1515
 */
1516
function recursiveBoards(&$_boardList, &$_tree)
1517
{
1518
	if (empty($_tree['children']))
1519
		return;
1520
1521
	foreach ($_tree['children'] as $id => $node)
1522
	{
1523
		$_boardList[] = $id;
1524
		recursiveBoards($_boardList, $node);
1525
	}
1526
}
1527
1528
/**
1529
 * Returns whether the child board id is actually a child of the parent (recursive).
1530
 *
1531
 * @param int $child The ID of the child board
1532
 * @param int $parent The ID of a parent board
1533
 * @return boolean Whether the specified child board is actually a child of the specified parent board.
1534
 */
1535
function isChildOf($child, $parent)
1536
{
1537
	global $boards;
1538
1539
	if (empty($boards[$child]['parent']))
1540
		return false;
1541
1542
	if ($boards[$child]['parent'] == $parent)
1543
		return true;
1544
1545
	return isChildOf($boards[$child]['parent'], $parent);
1546
}
1547
1548
?>