Passed
Push — release-2.1 ( 0c2197...207d2d )
by Jeremy
05:47
created

Subs-Boards.php ➔ MarkRead()   F

Complexity

Conditions 41
Paths 9249

Size

Total Lines 274

Duplication

Lines 76
Ratio 27.74 %

Importance

Changes 0
Metric Value
cc 41
nc 9249
nop 0
dl 76
loc 274
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * 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 http://www.simplemachines.org
11
 * @copyright 2018 Simple Machines and individual contributors
12
 * @license http://www.simplemachines.org/about/smf/license.php BSD
13
 *
14
 * @version 2.1 Beta 4
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
				',
322
				array(
323
					'no_parents' => 0,
324
					'board_list' => $boards,
325
				)
326
			);
327
			while ($row = $smcFunc['db_fetch_assoc']($request))
328
				if (in_array($row['id_parent'], $boards))
329
					$boards[] = $row['id_board'];
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
 * @param int $messageID The ID of the message
418
 * @return int The ID of the member associated with that post
419
 */
420
function getMsgMemberID($messageID)
421
{
422
	global $smcFunc;
423
424
	// Find the topic and make sure the member still exists.
425
	$result = $smcFunc['db_query']('', '
426
		SELECT COALESCE(mem.id_member, 0)
427
		FROM {db_prefix}messages AS m
428
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
429
		WHERE m.id_msg = {int:selected_message}
430
		LIMIT 1',
431
		array(
432
			'selected_message' => (int) $messageID,
433
		)
434
	);
435
	if ($smcFunc['db_num_rows']($result) > 0)
436
		list ($memberID) = $smcFunc['db_fetch_row']($result);
437
	// The message doesn't even exist.
438
	else
439
		$memberID = 0;
440
	$smcFunc['db_free_result']($result);
441
442
	return (int) $memberID;
443
}
444
445
/**
446
 * Modify the settings and position of a board.
447
 * Used by ManageBoards.php to change the settings of a board.
448
 *
449
 * @param int $board_id The ID of the board
450
 * @param array &$boardOptions An array of options related to the board
451
 */
452
function modifyBoard($board_id, &$boardOptions)
453
{
454
	global $cat_tree, $boards, $smcFunc;
455
456
	// Get some basic information about all boards and categories.
457
	getBoardTree();
458
459
	// Make sure given boards and categories exist.
460
	if (!isset($boards[$board_id]) || (isset($boardOptions['target_board']) && !isset($boards[$boardOptions['target_board']])) || (isset($boardOptions['target_category']) && !isset($cat_tree[$boardOptions['target_category']])))
461
		fatal_lang_error('no_board');
462
463
	$id = $board_id;
464
	call_integration_hook('integrate_pre_modify_board', array($id, &$boardOptions));
465
466
	// All things that will be updated in the database will be in $boardUpdates.
467
	$boardUpdates = array();
468
	$boardUpdateParameters = array();
469
470
	// In case the board has to be moved
471
	if (isset($boardOptions['move_to']))
472
	{
473
		// Move the board to the top of a given category.
474
		if ($boardOptions['move_to'] == 'top')
475
		{
476
			$id_cat = $boardOptions['target_category'];
477
			$child_level = 0;
478
			$id_parent = 0;
479
			$after = $cat_tree[$id_cat]['last_board_order'];
480
		}
481
482
		// Move the board to the bottom of a given category.
483
		elseif ($boardOptions['move_to'] == 'bottom')
484
		{
485
			$id_cat = $boardOptions['target_category'];
486
			$child_level = 0;
487
			$id_parent = 0;
488
			$after = 0;
489
			foreach ($cat_tree[$id_cat]['children'] as $id_board => $dummy)
490
				$after = max($after, $boards[$id_board]['order']);
491
		}
492
493
		// Make the board a child of a given board.
494
		elseif ($boardOptions['move_to'] == 'child')
495
		{
496
			$id_cat = $boards[$boardOptions['target_board']]['category'];
497
			$child_level = $boards[$boardOptions['target_board']]['level'] + 1;
498
			$id_parent = $boardOptions['target_board'];
499
500
			// People can be creative, in many ways...
501
			if (isChildOf($id_parent, $board_id))
502
				fatal_lang_error('mboards_parent_own_child_error', false);
503
			elseif ($id_parent == $board_id)
504
				fatal_lang_error('mboards_board_own_child_error', false);
505
506
			$after = $boards[$boardOptions['target_board']]['order'];
507
508
			// Check if there are already children and (if so) get the max board order.
509
			if (!empty($boards[$id_parent]['tree']['children']) && empty($boardOptions['move_first_child']))
510
				foreach ($boards[$id_parent]['tree']['children'] as $childBoard_id => $dummy)
511
					$after = max($after, $boards[$childBoard_id]['order']);
512
		}
513
514
		// Place a board before or after another board, on the same child level.
515
		elseif (in_array($boardOptions['move_to'], array('before', 'after')))
516
		{
517
			$id_cat = $boards[$boardOptions['target_board']]['category'];
518
			$child_level = $boards[$boardOptions['target_board']]['level'];
519
			$id_parent = $boards[$boardOptions['target_board']]['parent'];
520
			$after = $boards[$boardOptions['target_board']]['order'] - ($boardOptions['move_to'] == 'before' ? 1 : 0);
521
		}
522
523
		// Oops...?
524
		else
525
			trigger_error('modifyBoard(): The move_to value \'' . $boardOptions['move_to'] . '\' is incorrect', E_USER_ERROR);
526
527
		// Get a list of children of this board.
528
		$childList = array();
529
		recursiveBoards($childList, $boards[$board_id]['tree']);
530
531
		// See if there are changes that affect children.
532
		$childUpdates = array();
533
		$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...
534
		if ($levelDiff != 0)
535
			$childUpdates[] = 'child_level = child_level ' . ($levelDiff > 0 ? '+ ' : '') . '{int:level_diff}';
536
		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...
537
			$childUpdates[] = 'id_cat = {int:category}';
538
539
		// Fix the children of this board.
540
		if (!empty($childList) && !empty($childUpdates))
541
			$smcFunc['db_query']('', '
542
				UPDATE {db_prefix}boards
543
				SET ' . implode(',
544
					', $childUpdates) . '
545
				WHERE id_board IN ({array_int:board_list})',
546
				array(
547
					'board_list' => $childList,
548
					'category' => $id_cat,
549
					'level_diff' => $levelDiff,
550
				)
551
			);
552
553
		// Make some room for this spot.
554
		$smcFunc['db_query']('', '
555
			UPDATE {db_prefix}boards
556
			SET board_order = board_order + {int:new_order}
557
			WHERE board_order > {int:insert_after}
558
				AND id_board != {int:selected_board}',
559
			array(
560
				'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...
561
				'selected_board' => $board_id,
562
				'new_order' => 1 + count($childList),
563
			)
564
		);
565
566
		$boardUpdates[] = 'id_cat = {int:id_cat}';
567
		$boardUpdates[] = 'id_parent = {int:id_parent}';
568
		$boardUpdates[] = 'child_level = {int:child_level}';
569
		$boardUpdates[] = 'board_order = {int:board_order}';
570
		$boardUpdateParameters += array(
571
			'id_cat' => $id_cat,
572
			'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...
573
			'child_level' => $child_level,
574
			'board_order' => $after + 1,
575
		);
576
	}
577
578
	// This setting is a little twisted in the database...
579
	if (isset($boardOptions['posts_count']))
580
	{
581
		$boardUpdates[] = 'count_posts = {int:count_posts}';
582
		$boardUpdateParameters['count_posts'] = $boardOptions['posts_count'] ? 0 : 1;
583
	}
584
585
	// Set the theme for this board.
586
	if (isset($boardOptions['board_theme']))
587
	{
588
		$boardUpdates[] = 'id_theme = {int:id_theme}';
589
		$boardUpdateParameters['id_theme'] = (int) $boardOptions['board_theme'];
590
	}
591
592
	// Should the board theme override the user preferred theme?
593
	if (isset($boardOptions['override_theme']))
594
	{
595
		$boardUpdates[] = 'override_theme = {int:override_theme}';
596
		$boardUpdateParameters['override_theme'] = $boardOptions['override_theme'] ? 1 : 0;
597
	}
598
599
	// Who's allowed to access this board.
600
	if (isset($boardOptions['access_groups']))
601
	{
602
		$boardUpdates[] = 'member_groups = {string:member_groups}';
603
		$boardUpdateParameters['member_groups'] = implode(',', $boardOptions['access_groups']);
604
	}
605
606
	// And who isn't.
607
	if (isset($boardOptions['deny_groups']))
608
	{
609
		$boardUpdates[] = 'deny_member_groups = {string:deny_groups}';
610
		$boardUpdateParameters['deny_groups'] = implode(',', $boardOptions['deny_groups']);
611
	}
612
613
	if (isset($boardOptions['board_name']))
614
	{
615
		$boardUpdates[] = 'name = {string:board_name}';
616
		$boardUpdateParameters['board_name'] = $boardOptions['board_name'];
617
	}
618
619
	if (isset($boardOptions['board_description']))
620
	{
621
		$boardUpdates[] = 'description = {string:board_description}';
622
		$boardUpdateParameters['board_description'] = $boardOptions['board_description'];
623
	}
624
625
	if (isset($boardOptions['profile']))
626
	{
627
		$boardUpdates[] = 'id_profile = {int:profile}';
628
		$boardUpdateParameters['profile'] = (int) $boardOptions['profile'];
629
	}
630
631
	if (isset($boardOptions['redirect']))
632
	{
633
		$boardUpdates[] = 'redirect = {string:redirect}';
634
		$boardUpdateParameters['redirect'] = $boardOptions['redirect'];
635
	}
636
637
	if (isset($boardOptions['num_posts']))
638
	{
639
		$boardUpdates[] = 'num_posts = {int:num_posts}';
640
		$boardUpdateParameters['num_posts'] = (int) $boardOptions['num_posts'];
641
	}
642
643
	$id = $board_id;
644
	call_integration_hook('integrate_modify_board', array($id, $boardOptions, &$boardUpdates, &$boardUpdateParameters));
645
646
	// Do the updates (if any).
647
	if (!empty($boardUpdates))
648
		$smcFunc['db_query']('', '
649
			UPDATE {db_prefix}boards
650
			SET
651
				' . implode(',
652
				', $boardUpdates) . '
653
			WHERE id_board = {int:selected_board}',
654
			array_merge($boardUpdateParameters, array(
655
				'selected_board' => $board_id,
656
			))
657
		);
658
	
659
	// Do permission sync
660
	if (!empty($boardUpdateParameters['deny_groups']))
661
	{
662
		$insert = array();
663
		foreach($boardOptions['deny_groups'] as $value)
664
			$insert[] = array($value, $board_id, 1);
665
666
		$smcFunc['db_query']('', '
667
			DELETE FROM {db_prefix}board_permissions_view
668
			WHERE id_board = {int:selected_board} AND deny = 1',
669
			array(
670
				'selected_board' => $board_id,
671
			)
672
		);
673
		$smcFunc['db_insert']('insert',
674
				'{db_prefix}board_permissions_view',
675
				array('id_group' => 'int', 'id_board' => 'int', 'deny' => 'int'),
676
				$insert,
677
				array('id_group','id_board','deny')
678
				);
679
	}
680
681
	if (!empty($boardUpdateParameters['member_groups']))
682
	{
683
		$insert = array();
684
		foreach($boardOptions['access_groups'] as $value)
685
			$insert[] = array($value, $board_id, 0);
686
		$smcFunc['db_query']('', '
687
			DELETE FROM {db_prefix}board_permissions_view
688
			WHERE id_board = {int:selected_board} AND deny = 0',
689
			array(
690
				'selected_board' => $board_id,
691
			)
692
		);
693
		$smcFunc['db_insert']('insert',
694
				'{db_prefix}board_permissions_view',
695
				array('id_group' => 'int', 'id_board' => 'int', 'deny' => 'int'),
696
				$insert,
697
				array('id_group','id_board','deny')
698
				);
699
	}
700
701
702
	// Set moderators of this board.
703
	if (isset($boardOptions['moderators']) || isset($boardOptions['moderator_string']) || isset($boardOptions['moderator_groups']) || isset($boardOptions['moderator_group_string']))
704
	{
705
		// Reset current moderators for this board - if there are any!
706
		$smcFunc['db_query']('', '
707
			DELETE FROM {db_prefix}moderators
708
			WHERE id_board = {int:board_list}',
709
			array(
710
				'board_list' => $board_id,
711
			)
712
		);
713
714
		// Validate and get the IDs of the new moderators.
715
		if (isset($boardOptions['moderator_string']) && trim($boardOptions['moderator_string']) != '')
716
		{
717
			// Divvy out the usernames, remove extra space.
718
			$moderator_string = strtr($smcFunc['htmlspecialchars']($boardOptions['moderator_string'], ENT_QUOTES), array('&quot;' => '"'));
719
			preg_match_all('~"([^"]+)"~', $moderator_string, $matches);
720
			$moderators = array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $moderator_string)));
721
			for ($k = 0, $n = count($moderators); $k < $n; $k++)
722
			{
723
				$moderators[$k] = trim($moderators[$k]);
724
725
				if (strlen($moderators[$k]) == 0)
726
					unset($moderators[$k]);
727
			}
728
729
			// Find all the id_member's for the member_name's in the list.
730
			if (empty($boardOptions['moderators']))
731
				$boardOptions['moderators'] = array();
732
			if (!empty($moderators))
733
			{
734
				$request = $smcFunc['db_query']('', '
735
					SELECT id_member
736
					FROM {db_prefix}members
737
					WHERE member_name IN ({array_string:moderator_list}) OR real_name IN ({array_string:moderator_list})
738
					LIMIT {int:limit}',
739
					array(
740
						'moderator_list' => $moderators,
741
						'limit' => count($moderators),
742
					)
743
				);
744
				while ($row = $smcFunc['db_fetch_assoc']($request))
745
					$boardOptions['moderators'][] = $row['id_member'];
746
				$smcFunc['db_free_result']($request);
747
			}
748
		}
749
750
		// Add the moderators to the board.
751
		if (!empty($boardOptions['moderators']))
752
		{
753
			$inserts = array();
754
			foreach ($boardOptions['moderators'] as $moderator)
755
				$inserts[] = array($board_id, $moderator);
756
757
			$smcFunc['db_insert']('insert',
758
				'{db_prefix}moderators',
759
				array('id_board' => 'int', 'id_member' => 'int'),
760
				$inserts,
761
				array('id_board', 'id_member')
762
			);
763
		}
764
765
		// Reset current moderator groups for this board - if there are any!
766
		$smcFunc['db_query']('', '
767
			DELETE FROM {db_prefix}moderator_groups
768
			WHERE id_board = {int:board_list}',
769
			array(
770
				'board_list' => $board_id,
771
			)
772
		);
773
774
		// Validate and get the IDs of the new moderator groups.
775
		if (isset($boardOptions['moderator_group_string']) && trim($boardOptions['moderator_group_string']) != '')
776
		{
777
			// Divvy out the group names, remove extra space.
778
			$moderator_group_string = strtr($smcFunc['htmlspecialchars']($boardOptions['moderator_group_string'], ENT_QUOTES), array('&quot;' => '"'));
779
			preg_match_all('~"([^"]+)"~', $moderator_group_string, $matches);
780
			$moderator_groups = array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $moderator_group_string)));
781
			for ($k = 0, $n = count($moderator_groups); $k < $n; $k++)
782
			{
783
				$moderator_groups[$k] = trim($moderator_groups[$k]);
784
785
				if (strlen($moderator_groups[$k]) == 0)
786
					unset($moderator_groups[$k]);
787
			}
788
789
			/* 	Find all the id_group's for all the group names in the list
790
				But skip any invalid ones (invisible/post groups/Administrator/Moderator) */
791
			if (empty($boardOptions['moderator_groups']))
792
				$boardOptions['moderator_groups'] = array();
793
			if (!empty($moderator_groups))
794
			{
795
				$request = $smcFunc['db_query']('', '
796
					SELECT id_group
797
					FROM {db_prefix}membergroups
798
					WHERE group_name IN ({array_string:moderator_group_list})
799
						AND hidden = {int:visible}
800
						AND min_posts = {int:negative_one}
801
						AND id_group NOT IN ({array_int:invalid_groups})
802
					LIMIT {int:limit}',
803
					array(
804
						'visible' => 0,
805
						'negative_one' => -1,
806
						'invalid_groups' => array(1, 3),
807
						'moderator_group_list' => $moderator_groups,
808
						'limit' => count($moderator_groups),
809
					)
810
				);
811
				while ($row = $smcFunc['db_fetch_assoc']($request))
812
				{
813
					$boardOptions['moderator_groups'][] = $row['id_group'];
814
				}
815
				$smcFunc['db_free_result']($request);
816
			}
817
		}
818
819
		// Add the moderator groups to the board.
820
		if (!empty($boardOptions['moderator_groups']))
821
		{
822
			$inserts = array();
823
			foreach ($boardOptions['moderator_groups'] as $moderator_group)
824
				$inserts[] = array($board_id, $moderator_group);
825
826
			$smcFunc['db_insert']('insert',
827
				'{db_prefix}moderator_groups',
828
				array('id_board' => 'int', 'id_group' => 'int'),
829
				$inserts,
830
				array('id_board', 'id_group')
831
			);
832
		}
833
834
		// Note that caches can now be wrong!
835
		updateSettings(array('settings_updated' => time()));
836
	}
837
838
	if (isset($boardOptions['move_to']))
839
		reorderBoards();
840
841
	clean_cache('data');
842
843
	if (empty($boardOptions['dont_log']))
844
		logAction('edit_board', array('board' => $board_id), 'admin');
845
}
846
847
/**
848
 * Create a new board and set its properties and position.
849
 * Allows (almost) the same options as the modifyBoard() function.
850
 * With the option inherit_permissions set, the parent board permissions
851
 * will be inherited.
852
 *
853
 * @param array $boardOptions An array of information for the new board
854
 * @return int The ID of the new board
855
 */
856
function createBoard($boardOptions)
857
{
858
	global $boards, $smcFunc;
859
860
	// Trigger an error if one of the required values is not set.
861
	if (!isset($boardOptions['board_name']) || trim($boardOptions['board_name']) == '' || !isset($boardOptions['move_to']) || !isset($boardOptions['target_category']))
862
		trigger_error('createBoard(): One or more of the required options is not set', E_USER_ERROR);
863
864
	if (in_array($boardOptions['move_to'], array('child', 'before', 'after')) && !isset($boardOptions['target_board']))
865
		trigger_error('createBoard(): Target board is not set', E_USER_ERROR);
866
867
	// Set every optional value to its default value.
868
	$boardOptions += array(
869
		'posts_count' => true,
870
		'override_theme' => false,
871
		'board_theme' => 0,
872
		'access_groups' => array(),
873
		'board_description' => '',
874
		'profile' => 1,
875
		'moderators' => '',
876
		'inherit_permissions' => true,
877
		'dont_log' => true,
878
	);
879
	
880
	$default_memgrps = '-1,0';
881
	
882
	$board_columns = array(
883
		'id_cat' => 'int', 'name' => 'string-255', 'description' => 'string', 'board_order' => 'int',
884
		'member_groups' => 'string', 'redirect' => 'string',
885
	);
886
	$board_parameters = array(
887
		$boardOptions['target_category'], $boardOptions['board_name'], '', 0,
888
		$default_memgrps, '',
889
	);
890
891
	call_integration_hook('integrate_create_board', array(&$boardOptions, &$board_columns, &$board_parameters));
892
893
	// Insert a board, the settings are dealt with later.
894
	$board_id = $smcFunc['db_insert']('',
895
		'{db_prefix}boards',
896
		$board_columns,
897
		$board_parameters,
898
		array('id_board'),
899
		1
900
	);
901
902
	$insert = array();
903
904
	foreach(explode(',', $default_memgrps) as $value)
905
			$insert[] = array($value, $board_id, 0);
906
907
	$smcFunc['db_insert']('',
908
		'{db_prefix}board_permissions_view',
909
		array('id_group' => 'int', 'id_board' => 'int', 'deny' => 'int'),
910
		$insert,
911
		array('id_group','id_board','deny'),
912
		1
913
	);
914
915
	if (empty($board_id))
916
		return 0;
917
918
	// Change the board according to the given specifications.
919
	modifyBoard($board_id, $boardOptions);
920
921
	// Do we want the parent permissions to be inherited?
922
	if ($boardOptions['inherit_permissions'])
923
	{
924
		getBoardTree();
925
926
		if (!empty($boards[$board_id]['parent']))
927
		{
928
			$request = $smcFunc['db_query']('', '
929
				SELECT id_profile
930
				FROM {db_prefix}boards
931
				WHERE id_board = {int:board_parent}
932
				LIMIT 1',
933
				array(
934
					'board_parent' => (int) $boards[$board_id]['parent'],
935
				)
936
			);
937
			list ($boardOptions['profile']) = $smcFunc['db_fetch_row']($request);
938
			$smcFunc['db_free_result']($request);
939
940
			$smcFunc['db_query']('', '
941
				UPDATE {db_prefix}boards
942
				SET id_profile = {int:new_profile}
943
				WHERE id_board = {int:current_board}',
944
				array(
945
					'new_profile' => $boardOptions['profile'],
946
					'current_board' => $board_id,
947
				)
948
			);
949
		}
950
	}
951
952
	// Clean the data cache.
953
	clean_cache('data');
954
955
	// Created it.
956
	logAction('add_board', array('board' => $board_id), 'admin');
957
958
	// Here you are, a new board, ready to be spammed.
959
	return $board_id;
960
}
961
962
/**
963
 * Remove one or more boards.
964
 * Allows to move the children of the board before deleting it
965
 * if moveChildrenTo is set to null, the child boards will be deleted.
966
 * Deletes:
967
 *   - all topics that are on the given boards;
968
 *   - all information that's associated with the given boards;
969
 * updates the statistics to reflect the new situation.
970
 *
971
 * @param array $boards_to_remove The boards to remove
972
 * @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)
973
 */
974
function deleteBoards($boards_to_remove, $moveChildrenTo = null)
975
{
976
	global $sourcedir, $boards, $smcFunc;
977
978
	// No boards to delete? Return!
979
	if (empty($boards_to_remove))
980
		return;
981
982
	getBoardTree();
983
984
	call_integration_hook('integrate_delete_board', array($boards_to_remove, &$moveChildrenTo));
985
986
	// If $moveChildrenTo is set to null, include the children in the removal.
987
	if ($moveChildrenTo === null)
988
	{
989
		// Get a list of the child boards that will also be removed.
990
		$child_boards_to_remove = array();
991
		foreach ($boards_to_remove as $board_to_remove)
992
			recursiveBoards($child_boards_to_remove, $boards[$board_to_remove]['tree']);
993
994
		// Merge the children with their parents.
995
		if (!empty($child_boards_to_remove))
996
			$boards_to_remove = array_unique(array_merge($boards_to_remove, $child_boards_to_remove));
997
	}
998
	// Move the children to a safe home.
999
	else
1000
	{
1001
		foreach ($boards_to_remove as $id_board)
1002
		{
1003
			// @todo Separate category?
1004
			if ($moveChildrenTo === 0)
1005
				fixChildren($id_board, 0, 0);
1006
			else
1007
				fixChildren($id_board, $boards[$moveChildrenTo]['level'] + 1, $moveChildrenTo);
1008
		}
1009
	}
1010
1011
	// Delete ALL topics in the selected boards (done first so topics can't be marooned.)
1012
	$request = $smcFunc['db_query']('', '
1013
		SELECT id_topic
1014
		FROM {db_prefix}topics
1015
		WHERE id_board IN ({array_int:boards_to_remove})',
1016
		array(
1017
			'boards_to_remove' => $boards_to_remove,
1018
		)
1019
	);
1020
	$topics = array();
1021
	while ($row = $smcFunc['db_fetch_assoc']($request))
1022
		$topics[] = $row['id_topic'];
1023
	$smcFunc['db_free_result']($request);
1024
1025
	require_once($sourcedir . '/RemoveTopic.php');
1026
	removeTopics($topics, false);
1027
1028
	// Delete the board's logs.
1029
	$smcFunc['db_query']('', '
1030
		DELETE FROM {db_prefix}log_mark_read
1031
		WHERE id_board IN ({array_int:boards_to_remove})',
1032
		array(
1033
			'boards_to_remove' => $boards_to_remove,
1034
		)
1035
	);
1036
	$smcFunc['db_query']('', '
1037
		DELETE FROM {db_prefix}log_boards
1038
		WHERE id_board IN ({array_int:boards_to_remove})',
1039
		array(
1040
			'boards_to_remove' => $boards_to_remove,
1041
		)
1042
	);
1043
	$smcFunc['db_query']('', '
1044
		DELETE FROM {db_prefix}log_notify
1045
		WHERE id_board IN ({array_int:boards_to_remove})',
1046
		array(
1047
			'boards_to_remove' => $boards_to_remove,
1048
		)
1049
	);
1050
1051
	// Delete this board's moderators.
1052
	$smcFunc['db_query']('', '
1053
		DELETE FROM {db_prefix}moderators
1054
		WHERE id_board IN ({array_int:boards_to_remove})',
1055
		array(
1056
			'boards_to_remove' => $boards_to_remove,
1057
		)
1058
	);
1059
1060
	// Delete this board's moderator groups.
1061
	$smcFunc['db_query']('', '
1062
		DELETE FROM {db_prefix}moderator_groups
1063
		WHERE id_board IN ({array_int:boards_to_remove})',
1064
		array(
1065
			'boards_to_remove' => $boards_to_remove,
1066
		)
1067
	);
1068
1069
	// Delete any extra events in the calendar.
1070
	$smcFunc['db_query']('', '
1071
		DELETE FROM {db_prefix}calendar
1072
		WHERE id_board IN ({array_int:boards_to_remove})',
1073
		array(
1074
			'boards_to_remove' => $boards_to_remove,
1075
		)
1076
	);
1077
1078
	// Delete any message icons that only appear on these boards.
1079
	$smcFunc['db_query']('', '
1080
		DELETE FROM {db_prefix}message_icons
1081
		WHERE id_board IN ({array_int:boards_to_remove})',
1082
		array(
1083
			'boards_to_remove' => $boards_to_remove,
1084
		)
1085
	);
1086
1087
	// Delete the boards.
1088
	$smcFunc['db_query']('', '
1089
		DELETE FROM {db_prefix}boards
1090
		WHERE id_board IN ({array_int:boards_to_remove})',
1091
		array(
1092
			'boards_to_remove' => $boards_to_remove,
1093
		)
1094
	);
1095
1096
	// Delete permissions
1097
	$smcFunc['db_query']('', '
1098
		DELETE FROM {db_prefix}board_permissions_view
1099
		WHERE id_board IN ({array_int:boards_to_remove})',
1100
		array(
1101
			'boards_to_remove' => $boards_to_remove,
1102
		)
1103
	);
1104
1105
	// Latest message/topic might not be there anymore.
1106
	updateStats('message');
1107
	updateStats('topic');
1108
	updateSettings(array(
1109
		'calendar_updated' => time(),
1110
	));
1111
1112
	// Plus reset the cache to stop people getting odd results.
1113
	updateSettings(array('settings_updated' => time()));
1114
1115
	// Clean the cache as well.
1116
	clean_cache('data');
1117
1118
	// Let's do some serious logging.
1119
	foreach ($boards_to_remove as $id_board)
1120
		logAction('delete_board', array('boardname' => $boards[$id_board]['name']), 'admin');
1121
1122
	reorderBoards();
1123
}
1124
1125
/**
1126
 * Put all boards in the right order and sorts the records of the boards table.
1127
 * Used by modifyBoard(), deleteBoards(), modifyCategory(), and deleteCategories() functions
1128
 */
1129
function reorderBoards()
1130
{
1131
	global $cat_tree, $boardList, $boards, $smcFunc;
1132
1133
	getBoardTree();
1134
1135
	// Set the board order for each category.
1136
	$board_order = 0;
1137
	foreach ($cat_tree as $catID => $dummy)
1138
	{
1139
		foreach ($boardList[$catID] as $boardID)
1140
			if ($boards[$boardID]['order'] != ++$board_order)
1141
				$smcFunc['db_query']('', '
1142
					UPDATE {db_prefix}boards
1143
					SET board_order = {int:new_order}
1144
					WHERE id_board = {int:selected_board}',
1145
					array(
1146
						'new_order' => $board_order,
1147
						'selected_board' => $boardID,
1148
					)
1149
				);
1150
	}
1151
1152
	// Empty the board order cache
1153
	cache_put_data('board_order', null, -3600);
1154
}
1155
1156
/**
1157
 * Fixes the children of a board by setting their child_levels to new values.
1158
 * Used when a board is deleted or moved, to affect its children.
1159
 *
1160
 * @param int $parent The ID of the parent board
1161
 * @param int $newLevel The new child level for each of the child boards
1162
 * @param int $newParent The ID of the new parent board
1163
 */
1164
function fixChildren($parent, $newLevel, $newParent)
1165
{
1166
	global $smcFunc;
1167
1168
	// Grab all children of $parent...
1169
	$result = $smcFunc['db_query']('', '
1170
		SELECT id_board
1171
		FROM {db_prefix}boards
1172
		WHERE id_parent = {int:parent_board}',
1173
		array(
1174
			'parent_board' => $parent,
1175
		)
1176
	);
1177
	$children = array();
1178
	while ($row = $smcFunc['db_fetch_assoc']($result))
1179
		$children[] = $row['id_board'];
1180
	$smcFunc['db_free_result']($result);
1181
1182
	// ...and set it to a new parent and child_level.
1183
	$smcFunc['db_query']('', '
1184
		UPDATE {db_prefix}boards
1185
		SET id_parent = {int:new_parent}, child_level = {int:new_child_level}
1186
		WHERE id_parent = {int:parent_board}',
1187
		array(
1188
			'new_parent' => $newParent,
1189
			'new_child_level' => $newLevel,
1190
			'parent_board' => $parent,
1191
		)
1192
	);
1193
1194
	// Recursively fix the children of the children.
1195
	foreach ($children as $child)
1196
		fixChildren($child, $newLevel + 1, $child);
1197
}
1198
1199
/**
1200
 * Tries to load up the entire board order and category very very quickly
1201
 * Returns an array with two elements, cats and boards
1202
 *
1203
 * @return array An array of categories and boards
1204
 */
1205
function getTreeOrder()
1206
{
1207
	global $smcFunc;
1208
1209
	static $tree_order = array(
1210
		'cats' => array(),
1211
		'boards' => array(),
1212
	);
1213
1214
	if (!empty($tree_order['boards']))
1215
		return $tree_order;
1216
1217
	if (($cached = cache_get_data('board_order', 86400)) !== null)
0 ignored issues
show
introduced by
The condition $cached = cache_get_data...order', 86400) !== null is always true.
Loading history...
1218
	{
1219
		$tree_order = $cached;
1220
		return $cached;
1221
	}
1222
1223
	$request = $smcFunc['db_query']('', '
1224
		SELECT b.id_board, b.id_cat
1225
		FROM {db_prefix}boards AS b
1226
		ORDER BY b.board_order',
1227
		array()
1228
	);
1229
	while ($row = $smcFunc['db_fetch_assoc']($request))
1230
	{
1231
		if (!in_array($row['id_cat'], $tree_order['cats']))
1232
			$tree_order['cats'][] = $row['id_cat'];
1233
		$tree_order['boards'][] = $row['id_board'];
1234
	}
1235
	$smcFunc['db_free_result']($request);
1236
1237
	cache_put_data('board_order', $tree_order, 86400);
1238
1239
	return $tree_order;
1240
}
1241
1242
/**
1243
 * Takes a board array and sorts it
1244
 *
1245
 * @param array &$boards The boards
1246
 */
1247
function sortBoards(array &$boards)
1248
{
1249
	$tree = getTreeOrder();
1250
1251
	$ordered = array();
1252
	foreach ($tree['boards'] as $board)
1253
		if (!empty($boards[$board]))
1254
		{
1255
			$ordered[$board] = $boards[$board];
1256
1257
			if (is_array($ordered[$board]) && !empty($ordered[$board]['boards']))
1258
				sortBoards($ordered[$board]['boards']);
1259
1260
			if (is_array($ordered[$board]) && !empty($ordered[$board]['children']))
1261
				sortBoards($ordered[$board]['children']);
1262
		}
1263
1264
	$boards = $ordered;
1265
}
1266
1267
/**
1268
 * Takes a category array and sorts it
1269
 *
1270
 * @param array &$categories The categories
1271
 */
1272
function sortCategories(array &$categories)
1273
{
1274
	$tree = getTreeOrder();
1275
1276
	$ordered = array();
1277
	foreach ($tree['cats'] as $cat)
1278
		if (!empty($categories[$cat]))
1279
		{
1280
			$ordered[$cat] = $categories[$cat];
1281
			if (!empty($ordered[$cat]['boards']))
1282
				sortBoards($ordered[$cat]['boards']);
1283
		}
1284
1285
	$categories = $ordered;
1286
}
1287
1288
/**
1289
 * Returns the given board's moderators, with their names and links
1290
 *
1291
 * @param array $boards The boards to get moderators of
1292
 * @return array An array containing information about the moderators of each board
1293
 */
1294
function getBoardModerators(array $boards)
1295
{
1296
	global $smcFunc, $scripturl, $txt;
1297
1298
	if (empty($boards))
1299
		return array();
1300
1301
	$request = $smcFunc['db_query']('', '
1302
		SELECT mem.id_member, mem.real_name, mo.id_board
1303
		FROM {db_prefix}moderators AS mo
1304
		  INNER JOIN {db_prefix}members AS mem ON (mem.id_member = mo.id_member)
1305
		WHERE mo.id_board IN ({array_int:boards})',
1306
		array(
1307
			'boards' => $boards,
1308
		)
1309
	);
1310
	$moderators = array();
1311
	while ($row = $smcFunc['db_fetch_assoc']($request))
1312
	{
1313
		if (empty($moderators[$row['id_board']]))
1314
			$moderators[$row['id_board']] = array();
1315
1316
		$moderators[$row['id_board']][] = array(
1317
			'id' => $row['id_member'],
1318
			'name' => $row['real_name'],
1319
			'href' => $scripturl . '?action=profile;u=' . $row['id_member'],
1320
			'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '" title="' . $txt['board_moderator'] . '">' . $row['real_name'] . '</a>',
1321
		);
1322
	}
1323
	$smcFunc['db_free_result']($request);
1324
1325
	return $moderators;
1326
}
1327
1328
/**
1329
 * Returns board's moderator groups with their names and link
1330
 *
1331
 * @param array $boards The boards to get moderator groups of
1332
 * @return array An array containing information about the groups assigned to moderate each board
1333
 */
1334
function getBoardModeratorGroups(array $boards)
1335
{
1336
	global $smcFunc, $scripturl, $txt;
1337
1338
	if (empty($boards))
1339
		return array();
1340
1341
	$request = $smcFunc['db_query']('', '
1342
		SELECT mg.id_group, mg.group_name, bg.id_board
1343
		FROM {db_prefix}moderator_groups AS bg
1344
		  INNER JOIN {db_prefix}membergroups AS mg ON (mg.id_group = bg.id_group)
1345
		WHERE bg.id_board IN ({array_int:boards})',
1346
		array(
1347
			'boards' => $boards,
1348
		)
1349
	);
1350
	$groups = array();
1351
	while ($row = $smcFunc['db_fetch_assoc']($request))
1352
	{
1353
		if (empty($groups[$row['id_board']]))
1354
			$groups[$row['id_board']] = array();
1355
1356
		$groups[$row['id_board']][] = array(
1357
			'id' => $row['id_group'],
1358
			'name' => $row['group_name'],
1359
			'href' => $scripturl . '?action=groups;sa=members;group=' . $row['id_group'],
1360
			'link' => '<a href="' . $scripturl . '?action=groups;sa=members;group=' . $row['id_group'] . '" title="' . $txt['board_moderator'] . '">' . $row['group_name'] . '</a>',
1361
		);
1362
	}
1363
1364
	return $groups;
1365
}
1366
1367
/**
1368
 * Load a lot of useful information regarding the boards and categories.
1369
 * The information retrieved is stored in globals:
1370
 *  $boards		properties of each board.
1371
 *  $boardList	a list of boards grouped by category ID.
1372
 *  $cat_tree	properties of each category.
1373
 */
1374
function getBoardTree()
1375
{
1376
	global $cat_tree, $boards, $boardList, $smcFunc;
1377
1378
	$boardColumns = array(
1379
		'COALESCE(b.id_board, 0) AS id_board', 'b.id_parent', 'b.name AS board_name',
1380
		'b.description', 'b.child_level', 'b.board_order', 'b.count_posts', 'b.member_groups',
1381
		'b.id_theme', 'b.override_theme', 'b.id_profile', 'b.redirect', 'b.num_posts',
1382
		'b.num_topics', 'b.deny_member_groups', 'c.id_cat', 'c.name AS cat_name',
1383
		'c.description AS cat_desc', 'c.cat_order', 'c.can_collapse',
1384
	);
1385
1386
	// Let mods add extra columns and parameters to the SELECT query
1387
	$extraBoardColumns = array();
1388
	$extraBoardParameters = array();
1389
	call_integration_hook('integrate_pre_boardtree', array(&$extraBoardColumns, &$extraBoardParameters));
1390
1391
	$boardColumns = array_unique(array_merge($boardColumns, $extraBoardColumns));
1392
	$boardParameters = array_unique($extraBoardParameters);
1393
1394
	// Getting all the board and category information you'd ever wanted.
1395
	$request = $smcFunc['db_query']('', '
1396
		SELECT
1397
			' . implode(', ', $boardColumns) . '
1398
		FROM {db_prefix}categories AS c
1399
			LEFT JOIN {db_prefix}boards AS b ON (b.id_cat = c.id_cat)
1400
		WHERE {query_see_board}
1401
		ORDER BY c.cat_order, b.child_level, b.board_order',
1402
		$boardParameters
1403
	);
1404
	$cat_tree = array();
1405
	$boards = array();
1406
	$last_board_order = 0;
1407
	while ($row = $smcFunc['db_fetch_assoc']($request))
1408
	{
1409
		if (!isset($cat_tree[$row['id_cat']]))
1410
		{
1411
			$cat_tree[$row['id_cat']] = array(
1412
				'node' => array(
1413
					'id' => $row['id_cat'],
1414
					'name' => $row['cat_name'],
1415
					'description' => $row['cat_desc'],
1416
					'order' => $row['cat_order'],
1417
					'can_collapse' => $row['can_collapse']
1418
				),
1419
				'is_first' => empty($cat_tree),
1420
				'last_board_order' => $last_board_order,
1421
				'children' => array()
1422
			);
1423
			$prevBoard = 0;
1424
			$curLevel = 0;
1425
		}
1426
1427
		if (!empty($row['id_board']))
1428
		{
1429
			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...
1430
				$prevBoard = 0;
1431
1432
			$boards[$row['id_board']] = array(
1433
				'id' => $row['id_board'],
1434
				'category' => $row['id_cat'],
1435
				'parent' => $row['id_parent'],
1436
				'level' => $row['child_level'],
1437
				'order' => $row['board_order'],
1438
				'name' => $row['board_name'],
1439
				'member_groups' => explode(',', $row['member_groups']),
1440
				'deny_groups' => explode(',', $row['deny_member_groups']),
1441
				'description' => $row['description'],
1442
				'count_posts' => empty($row['count_posts']),
1443
				'posts' => $row['num_posts'],
1444
				'topics' => $row['num_topics'],
1445
				'theme' => $row['id_theme'],
1446
				'override_theme' => $row['override_theme'],
1447
				'profile' => $row['id_profile'],
1448
				'redirect' => $row['redirect'],
1449
				'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...
1450
			);
1451
			$prevBoard = $row['id_board'];
1452
			$last_board_order = $row['board_order'];
1453
1454
			if (empty($row['child_level']))
1455
			{
1456
				$cat_tree[$row['id_cat']]['children'][$row['id_board']] = array(
1457
					'node' => &$boards[$row['id_board']],
1458
					'is_first' => empty($cat_tree[$row['id_cat']]['children']),
1459
					'children' => array()
1460
				);
1461
				$boards[$row['id_board']]['tree'] = &$cat_tree[$row['id_cat']]['children'][$row['id_board']];
1462
			}
1463
			else
1464
			{
1465
				// Parent doesn't exist!
1466
				if (!isset($boards[$row['id_parent']]['tree']))
1467
					fatal_lang_error('no_valid_parent', false, array($row['board_name']));
1468
1469
				// Wrong childlevel...we can silently fix this...
1470
				if ($boards[$row['id_parent']]['tree']['node']['level'] != $row['child_level'] - 1)
1471
					$smcFunc['db_query']('', '
1472
						UPDATE {db_prefix}boards
1473
						SET child_level = {int:new_child_level}
1474
						WHERE id_board = {int:selected_board}',
1475
						array(
1476
							'new_child_level' => $boards[$row['id_parent']]['tree']['node']['level'] + 1,
1477
							'selected_board' => $row['id_board'],
1478
						)
1479
					);
1480
1481
				$boards[$row['id_parent']]['tree']['children'][$row['id_board']] = array(
1482
					'node' => &$boards[$row['id_board']],
1483
					'is_first' => empty($boards[$row['id_parent']]['tree']['children']),
1484
					'children' => array()
1485
				);
1486
				$boards[$row['id_board']]['tree'] = &$boards[$row['id_parent']]['tree']['children'][$row['id_board']];
1487
			}
1488
		}
1489
1490
		// If mods want to do anything with this board before we move on, now's the time
1491
		call_integration_hook('integrate_boardtree_board', array($row));
1492
	}
1493
	$smcFunc['db_free_result']($request);
1494
1495
	// Get a list of all the boards in each category (using recursion).
1496
	$boardList = array();
1497
	foreach ($cat_tree as $catID => $node)
1498
	{
1499
		$boardList[$catID] = array();
1500
		recursiveBoards($boardList[$catID], $node);
1501
	}
1502
}
1503
1504
/**
1505
 * Recursively get a list of boards.
1506
 * Used by getBoardTree
1507
 *
1508
 * @param array &$_boardList The board list
1509
 * @param array &$_tree The board tree
1510
 */
1511
function recursiveBoards(&$_boardList, &$_tree)
1512
{
1513
	if (empty($_tree['children']))
1514
		return;
1515
1516
	foreach ($_tree['children'] as $id => $node)
1517
	{
1518
		$_boardList[] = $id;
1519
		recursiveBoards($_boardList, $node);
1520
	}
1521
}
1522
1523
/**
1524
 * Returns whether the child board id is actually a child of the parent (recursive).
1525
 * @param int $child The ID of the child board
1526
 * @param int $parent The ID of a parent board
1527
 * @return boolean Whether the specified child board is actually a child of the specified parent board.
1528
 */
1529
function isChildOf($child, $parent)
1530
{
1531
	global $boards;
1532
1533
	if (empty($boards[$child]['parent']))
1534
		return false;
1535
1536
	if ($boards[$child]['parent'] == $parent)
1537
		return true;
1538
1539
	return isChildOf($boards[$child]['parent'], $parent);
1540
}
1541
1542
?>