Issues (1014)

Sources/Stats.php (8 issues)

1
<?php
2
3
/**
4
 * Provide a display for forum statistics
5
 *
6
 * Simple Machines Forum (SMF)
7
 *
8
 * @package SMF
9
 * @author Simple Machines https://www.simplemachines.org
10
 * @copyright 2022 Simple Machines and individual contributors
11
 * @license https://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1.0
14
 */
15
16
if (!defined('SMF'))
17
	die('No direct access...');
18
19
/**
20
 * Display some useful/interesting board statistics.
21
 *
22
 * gets all the statistics in order and puts them in.
23
 * uses the Stats template and language file. (and main sub template.)
24
 * requires the view_stats permission.
25
 * accessed from ?action=stats.
26
 */
27
function DisplayStats()
28
{
29
	global $txt, $scripturl, $modSettings, $context, $smcFunc;
30
31
	isAllowedTo('view_stats');
32
	// Page disabled - redirect them out
33
	if (empty($modSettings['trackStats']))
34
		fatal_lang_error('feature_disabled', true);
35
36
	if (!empty($_REQUEST['expand']))
37
	{
38
		$context['robot_no_index'] = true;
39
40
		$month = (int) substr($_REQUEST['expand'], 4);
41
		$year = (int) substr($_REQUEST['expand'], 0, 4);
42
		if ($year > 1900 && $year < 2200 && $month >= 1 && $month <= 12)
43
			$_SESSION['expanded_stats'][$year][] = $month;
44
	}
45
	elseif (!empty($_REQUEST['collapse']))
46
	{
47
		$context['robot_no_index'] = true;
48
49
		$month = (int) substr($_REQUEST['collapse'], 4);
50
		$year = (int) substr($_REQUEST['collapse'], 0, 4);
51
		if (!empty($_SESSION['expanded_stats'][$year]))
52
			$_SESSION['expanded_stats'][$year] = array_diff($_SESSION['expanded_stats'][$year], array($month));
53
	}
54
55
	// Handle the XMLHttpRequest.
56
	if (isset($_REQUEST['xml']))
57
	{
58
		// Collapsing stats only needs adjustments of the session variables.
59
		if (!empty($_REQUEST['collapse']))
60
			obExit(false);
61
62
		$context['sub_template'] = 'stats';
63
		$context['yearly'] = array();
64
65
		if (empty($month) || empty($year))
66
			return;
67
68
		getDailyStats('YEAR(date) = {int:year} AND MONTH(date) = {int:month}', array('year' => $year, 'month' => $month));
69
		$context['yearly'][$year]['months'][$month]['date'] = array(
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $year does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $month does not seem to be defined for all execution paths leading up to this point.
Loading history...
70
			'month' => sprintf('%02d', $month),
71
			'year' => $year,
72
		);
73
		return;
74
	}
75
76
	loadLanguage('Stats');
77
	loadTemplate('Stats');
78
	loadJavaScriptFile('stats.js', array('default_theme' => true, 'defer' => false, 'minimize' => true), 'smf_stats');
79
80
	// Build the link tree......
81
	$context['linktree'][] = array(
82
		'url' => $scripturl . '?action=stats',
83
		'name' => $txt['stats_center']
84
	);
85
	$context['page_title'] = $context['forum_name'] . ' - ' . $txt['stats_center'];
86
87
	$context['show_member_list'] = allowedTo('view_mlist');
88
89
	// Get averages...
90
	$result = $smcFunc['db_query']('', '
91
		SELECT
92
			SUM(posts) AS posts, SUM(topics) AS topics, SUM(registers) AS registers,
93
			SUM(most_on) AS most_on, MIN(date) AS date, SUM(hits) AS hits
94
		FROM {db_prefix}log_activity',
95
		array(
96
		)
97
	);
98
	$row = $smcFunc['db_fetch_assoc']($result);
99
	$smcFunc['db_free_result']($result);
100
101
	// This would be the amount of time the forum has been up... in days...
102
	$total_days_up = ceil((time() - strtotime($row['date'])) / (60 * 60 * 24));
103
104
	$context['average_posts'] = comma_format(round($row['posts'] / $total_days_up, 2));
105
	$context['average_topics'] = comma_format(round($row['topics'] / $total_days_up, 2));
106
	$context['average_members'] = comma_format(round($row['registers'] / $total_days_up, 2));
107
	$context['average_online'] = comma_format(round($row['most_on'] / $total_days_up, 2));
108
	$context['average_hits'] = comma_format(round($row['hits'] / $total_days_up, 2));
109
110
	$context['num_hits'] = comma_format($row['hits'], 0);
111
112
	// How many users are online now.
113
	$result = $smcFunc['db_query']('', '
114
		SELECT COUNT(*)
115
		FROM {db_prefix}log_online',
116
		array(
117
		)
118
	);
119
	list ($context['users_online']) = $smcFunc['db_fetch_row']($result);
120
	$smcFunc['db_free_result']($result);
121
122
	// Statistics such as number of boards, categories, etc.
123
	$result = $smcFunc['db_query']('', '
124
		SELECT COUNT(*)
125
		FROM {db_prefix}boards AS b
126
		WHERE b.redirect = {string:blank_redirect}',
127
		array(
128
			'blank_redirect' => '',
129
		)
130
	);
131
	list ($context['num_boards']) = $smcFunc['db_fetch_row']($result);
132
	$smcFunc['db_free_result']($result);
133
134
	$result = $smcFunc['db_query']('', '
135
		SELECT COUNT(*)
136
		FROM {db_prefix}categories AS c',
137
		array(
138
		)
139
	);
140
	list ($context['num_categories']) = $smcFunc['db_fetch_row']($result);
141
	$smcFunc['db_free_result']($result);
142
143
	// Format the numbers nicely.
144
	$context['users_online'] = comma_format($context['users_online']);
145
	$context['num_boards'] = comma_format($context['num_boards']);
146
	$context['num_categories'] = comma_format($context['num_categories']);
147
148
	$context['num_members'] = comma_format($modSettings['totalMembers']);
149
	$context['num_posts'] = comma_format($modSettings['totalMessages']);
150
	$context['num_topics'] = comma_format($modSettings['totalTopics']);
151
	$context['most_members_online'] = array(
152
		'number' => comma_format($modSettings['mostOnline']),
153
		'date' => timeformat($modSettings['mostDate'])
154
	);
155
	$context['latest_member'] = &$context['common_stats']['latest_member'];
156
157
	// Let's calculate gender stats only every four minutes.
158
	$disabled_fields = isset($modSettings['disabled_profile_fields']) ? explode(',', $modSettings['disabled_profile_fields']) : array();
159
	if (!in_array('gender', $disabled_fields))
160
	{
161
		if (($context['gender'] = cache_get_data('stats_gender', 240)) == null)
162
		{
163
			$result = $smcFunc['db_query']('', '
164
				SELECT default_value
165
				FROM {db_prefix}custom_fields
166
				WHERE col_name= {string:gender_var}',
167
				array(
168
					'gender_var' => 'cust_gender',
169
				)
170
			);
171
			$row = $smcFunc['db_fetch_assoc']($result);
172
			$default_gender = !empty($row['default_value']) ? $row['default_value'] : '{gender_0}';
173
			$smcFunc['db_free_result']($result);
174
175
			$result = $smcFunc['db_query']('', '
176
				SELECT COUNT(*) AS total_members, value AS gender
177
				FROM {db_prefix}members AS mem
178
				INNER JOIN {db_prefix}themes AS t ON (
179
					t.id_member = mem.id_member
180
					AND t.variable = {string:gender_var}
181
					AND t.id_theme = {int:default_theme}
182
				)
183
				WHERE is_activated = {int:is_activated}
184
				GROUP BY value',
185
				array(
186
					'gender_var' => 'cust_gender',
187
					'default_theme' => 1,
188
					'is_activated' => 1,
189
					'default_gender' => $default_gender,
190
				)
191
			);
192
			$context['gender'] = array($default_gender => 0);
193
			while ($row = $smcFunc['db_fetch_assoc']($result))
194
			{
195
				$context['gender'][$row['gender']] = $row['total_members'];
196
			}
197
			$smcFunc['db_free_result']($result);
198
199
			$context['gender'][$default_gender] += $modSettings['totalMembers'] - array_sum($context['gender']);
200
201
			cache_put_data('stats_gender', $context['gender'], 240);
202
		}
203
	}
204
205
	$date = smf_strftime('%Y-%m-%d', time());
206
207
	// Members online so far today.
208
	$result = $smcFunc['db_query']('', '
209
		SELECT most_on
210
		FROM {db_prefix}log_activity
211
		WHERE date = {date:today_date}
212
		LIMIT 1',
213
		array(
214
			'today_date' => $date,
215
		)
216
	);
217
	list ($context['online_today']) = $smcFunc['db_fetch_row']($result);
218
	$smcFunc['db_free_result']($result);
219
220
	$context['online_today'] = comma_format((int) $context['online_today']);
221
222
	// Poster top 10.
223
	$members_result = $smcFunc['db_query']('', '
224
		SELECT id_member, real_name, posts
225
		FROM {db_prefix}members
226
		WHERE posts > {int:no_posts}
227
		ORDER BY posts DESC
228
		LIMIT 10',
229
		array(
230
			'no_posts' => 0,
231
		)
232
	);
233
	$context['stats_blocks']['posters'] = array();
234
	$max_num_posts = 1;
235
	while ($row_members = $smcFunc['db_fetch_assoc']($members_result))
236
	{
237
		$context['stats_blocks']['posters'][] = array(
238
			'name' => $row_members['real_name'],
239
			'id' => $row_members['id_member'],
240
			'num' => $row_members['posts'],
241
			'href' => $scripturl . '?action=profile;u=' . $row_members['id_member'],
242
			'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row_members['id_member'] . '">' . $row_members['real_name'] . '</a>'
243
		);
244
245
		if ($max_num_posts < $row_members['posts'])
246
			$max_num_posts = $row_members['posts'];
247
	}
248
	$smcFunc['db_free_result']($members_result);
249
250
	foreach ($context['stats_blocks']['posters'] as $i => $poster)
251
	{
252
		$context['stats_blocks']['posters'][$i]['percent'] = round(($poster['num'] * 100) / $max_num_posts);
253
		$context['stats_blocks']['posters'][$i]['num'] = comma_format($context['stats_blocks']['posters'][$i]['num']);
254
	}
255
256
	// Board top 10.
257
	$boards_result = $smcFunc['db_query']('', '
258
		SELECT id_board, name, num_posts
259
		FROM {db_prefix}boards AS b
260
		WHERE {query_see_board}' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
261
			AND b.id_board != {int:recycle_board}' : '') . '
262
			AND b.redirect = {string:blank_redirect}
263
		ORDER BY num_posts DESC
264
		LIMIT 10',
265
		array(
266
			'recycle_board' => $modSettings['recycle_board'],
267
			'blank_redirect' => '',
268
		)
269
	);
270
	$context['stats_blocks']['boards'] = array();
271
	$max_num_posts = 1;
272
	while ($row_board = $smcFunc['db_fetch_assoc']($boards_result))
273
	{
274
		$context['stats_blocks']['boards'][] = array(
275
			'id' => $row_board['id_board'],
276
			'name' => $row_board['name'],
277
			'num' => $row_board['num_posts'],
278
			'href' => $scripturl . '?board=' . $row_board['id_board'] . '.0',
279
			'link' => '<a href="' . $scripturl . '?board=' . $row_board['id_board'] . '.0">' . $row_board['name'] . '</a>'
280
		);
281
282
		if ($max_num_posts < $row_board['num_posts'])
283
			$max_num_posts = $row_board['num_posts'];
284
	}
285
	$smcFunc['db_free_result']($boards_result);
286
287
	foreach ($context['stats_blocks']['boards'] as $i => $board)
288
	{
289
		$context['stats_blocks']['boards'][$i]['percent'] = round(($board['num'] * 100) / $max_num_posts);
290
		$context['stats_blocks']['boards'][$i]['num'] = comma_format($context['stats_blocks']['boards'][$i]['num']);
291
	}
292
293
	// Are you on a larger forum?  If so, let's try to limit the number of topics we search through.
294
	if ($modSettings['totalMessages'] > 100000)
295
	{
296
		$request = $smcFunc['db_query']('', '
297
			SELECT id_topic
298
			FROM {db_prefix}topics
299
			WHERE num_replies != {int:no_replies}' . ($modSettings['postmod_active'] ? '
300
				AND approved = {int:is_approved}' : '') . '
301
			ORDER BY num_replies DESC
302
			LIMIT 100',
303
			array(
304
				'no_replies' => 0,
305
				'is_approved' => 1,
306
			)
307
		);
308
		$topic_ids = array();
309
		while ($row = $smcFunc['db_fetch_assoc']($request))
310
			$topic_ids[] = $row['id_topic'];
311
		$smcFunc['db_free_result']($request);
312
	}
313
	else
314
		$topic_ids = array();
315
316
	// Topic replies top 10.
317
	$topic_reply_result = $smcFunc['db_query']('', '
318
		SELECT m.subject, t.num_replies, t.id_board, t.id_topic, b.name
319
		FROM {db_prefix}topics AS t
320
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
321
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
322
			AND b.id_board != {int:recycle_board}' : '') . ')
323
		WHERE {query_see_board}' . (!empty($topic_ids) ? '
324
			AND t.id_topic IN ({array_int:topic_list})' : ($modSettings['postmod_active'] ? '
325
			AND t.approved = {int:is_approved}' : '')) . '
326
		ORDER BY t.num_replies DESC
327
		LIMIT 10',
328
		array(
329
			'topic_list' => $topic_ids,
330
			'recycle_board' => $modSettings['recycle_board'],
331
			'is_approved' => 1,
332
		)
333
	);
334
	$context['stats_blocks']['topics_replies'] = array();
335
	$max_num_replies = 1;
336
337
	while ($row_topic_reply = $smcFunc['db_fetch_assoc']($topic_reply_result))
338
	{
339
		censorText($row_topic_reply['subject']);
340
341
		$context['stats_blocks']['topics_replies'][] = array(
342
			'id' => $row_topic_reply['id_topic'],
343
			'board' => array(
344
				'id' => $row_topic_reply['id_board'],
345
				'name' => $row_topic_reply['name'],
346
				'href' => $scripturl . '?board=' . $row_topic_reply['id_board'] . '.0',
347
				'link' => '<a href="' . $scripturl . '?board=' . $row_topic_reply['id_board'] . '.0">' . $row_topic_reply['name'] . '</a>'
348
			),
349
			'subject' => $row_topic_reply['subject'],
350
			'num' => $row_topic_reply['num_replies'],
351
			'href' => $scripturl . '?topic=' . $row_topic_reply['id_topic'] . '.0',
352
			'link' => '<a href="' . $scripturl . '?topic=' . $row_topic_reply['id_topic'] . '.0">' . $row_topic_reply['subject'] . '</a>'
353
		);
354
355
		if ($max_num_replies < $row_topic_reply['num_replies'])
356
			$max_num_replies = $row_topic_reply['num_replies'];
357
	}
358
	$smcFunc['db_free_result']($topic_reply_result);
359
360
	foreach ($context['stats_blocks']['topics_replies'] as $i => $topic)
361
	{
362
		$context['stats_blocks']['topics_replies'][$i]['percent'] = round(($topic['num'] * 100) / $max_num_replies);
363
		$context['stats_blocks']['topics_replies'][$i]['num'] = comma_format($context['stats_blocks']['topics_replies'][$i]['num']);
364
	}
365
366
	// Large forums may need a bit more prodding...
367
	if ($modSettings['totalMessages'] > 100000)
368
	{
369
		$request = $smcFunc['db_query']('', '
370
			SELECT id_topic
371
			FROM {db_prefix}topics
372
			WHERE num_views != {int:no_views}
373
			ORDER BY num_views DESC
374
			LIMIT 100',
375
			array(
376
				'no_views' => 0,
377
			)
378
		);
379
		$topic_ids = array();
380
		while ($row = $smcFunc['db_fetch_assoc']($request))
381
			$topic_ids[] = $row['id_topic'];
382
		$smcFunc['db_free_result']($request);
383
	}
384
	else
385
		$topic_ids = array();
386
387
	// Topic views top 10.
388
	$topic_view_result = $smcFunc['db_query']('', '
389
		SELECT m.subject, t.num_views, t.id_board, t.id_topic, b.name
390
		FROM {db_prefix}topics AS t
391
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
392
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
393
			AND b.id_board != {int:recycle_board}' : '') . ')
394
		WHERE {query_see_board}' . (!empty($topic_ids) ? '
395
			AND t.id_topic IN ({array_int:topic_list})' : ($modSettings['postmod_active'] ? '
396
			AND t.approved = {int:is_approved}' : '')) . '
397
		ORDER BY t.num_views DESC
398
		LIMIT 10',
399
		array(
400
			'topic_list' => $topic_ids,
401
			'recycle_board' => $modSettings['recycle_board'],
402
			'is_approved' => 1,
403
		)
404
	);
405
	$context['stats_blocks']['topics_views'] = array();
406
	$max_num = 1;
407
	while ($row_topic_views = $smcFunc['db_fetch_assoc']($topic_view_result))
408
	{
409
		censorText($row_topic_views['subject']);
410
411
		$context['stats_blocks']['topics_views'][] = array(
412
			'id' => $row_topic_views['id_topic'],
413
			'board' => array(
414
				'id' => $row_topic_views['id_board'],
415
				'name' => $row_topic_views['name'],
416
				'href' => $scripturl . '?board=' . $row_topic_views['id_board'] . '.0',
417
				'link' => '<a href="' . $scripturl . '?board=' . $row_topic_views['id_board'] . '.0">' . $row_topic_views['name'] . '</a>'
418
			),
419
			'subject' => $row_topic_views['subject'],
420
			'num' => $row_topic_views['num_views'],
421
			'href' => $scripturl . '?topic=' . $row_topic_views['id_topic'] . '.0',
422
			'link' => '<a href="' . $scripturl . '?topic=' . $row_topic_views['id_topic'] . '.0">' . $row_topic_views['subject'] . '</a>'
423
		);
424
425
		if ($max_num < $row_topic_views['num_views'])
426
			$max_num = $row_topic_views['num_views'];
427
	}
428
	$smcFunc['db_free_result']($topic_view_result);
429
430
	foreach ($context['stats_blocks']['topics_views'] as $i => $topic)
431
	{
432
		$context['stats_blocks']['topics_views'][$i]['percent'] = round(($topic['num'] * 100) / $max_num);
433
		$context['stats_blocks']['topics_views'][$i]['num'] = comma_format($context['stats_blocks']['topics_views'][$i]['num']);
434
	}
435
436
	// Try to cache this when possible, because it's a little unavoidably slow.
437
	if (($members = cache_get_data('stats_top_starters', 360)) == null)
438
	{
439
		$request = $smcFunc['db_query']('', '
440
			SELECT id_member_started, COUNT(*) AS hits
441
			FROM {db_prefix}topics' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
442
			WHERE id_board != {int:recycle_board}' : '') . '
443
			GROUP BY id_member_started
444
			ORDER BY hits DESC
445
			LIMIT 20',
446
			array(
447
				'recycle_board' => $modSettings['recycle_board'],
448
			)
449
		);
450
		$members = array();
451
		while ($row = $smcFunc['db_fetch_assoc']($request))
452
			$members[$row['id_member_started']] = $row['hits'];
453
		$smcFunc['db_free_result']($request);
454
455
		cache_put_data('stats_top_starters', $members, 360);
456
	}
457
458
	if (empty($members))
459
		$members = array(0 => 0);
460
461
	// Topic poster top 10.
462
	$members_result = $smcFunc['db_query']('', '
463
		SELECT id_member, real_name
464
		FROM {db_prefix}members
465
		WHERE id_member IN ({array_int:member_list})',
466
		array(
467
			'member_list' => array_keys($members),
468
		)
469
	);
470
	$context['stats_blocks']['starters'] = array();
471
	$max_num = 1;
472
	while ($row_members = $smcFunc['db_fetch_assoc']($members_result))
473
	{
474
		$i = array_search($row_members['id_member'], array_keys($members));
475
		// skip all not top 10
476
		if ($i > 10)
477
			continue;
478
479
		$context['stats_blocks']['starters'][$i] = array(
480
			'name' => $row_members['real_name'],
481
			'id' => $row_members['id_member'],
482
			'num' => $members[$row_members['id_member']],
483
			'href' => $scripturl . '?action=profile;u=' . $row_members['id_member'],
484
			'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row_members['id_member'] . '">' . $row_members['real_name'] . '</a>'
485
		);
486
487
		if ($max_num < $members[$row_members['id_member']])
488
			$max_num = $members[$row_members['id_member']];
489
	}
490
	ksort($context['stats_blocks']['starters']);
491
	$smcFunc['db_free_result']($members_result);
492
493
	foreach ($context['stats_blocks']['starters'] as $i => $topic)
494
	{
495
		$context['stats_blocks']['starters'][$i]['percent'] = round(($topic['num'] * 100) / $max_num);
496
		$context['stats_blocks']['starters'][$i]['num'] = comma_format($context['stats_blocks']['starters'][$i]['num']);
497
	}
498
499
	// Time online top 10.
500
	$temp = cache_get_data('stats_total_time_members', 600);
501
	$members_result = $smcFunc['db_query']('', '
502
		SELECT id_member, real_name, total_time_logged_in
503
		FROM {db_prefix}members
504
		WHERE is_activated = {int:is_activated}' .
505
		(!empty($temp) ? ' AND id_member IN ({array_int:member_list_cached})' : '') . '
506
		ORDER BY total_time_logged_in DESC
507
		LIMIT 20',
508
		array(
509
			'member_list_cached' => $temp,
510
			'is_activated' => 1,
511
		)
512
	);
513
	$context['stats_blocks']['time_online'] = array();
514
	$temp2 = array();
515
	$max_time_online = 1;
516
	while ($row_members = $smcFunc['db_fetch_assoc']($members_result))
517
	{
518
		$temp2[] = (int) $row_members['id_member'];
519
		if (count($context['stats_blocks']['time_online']) >= 10)
520
			continue;
521
522
		// Figure out the days, hours and minutes.
523
		$timeDays = floor($row_members['total_time_logged_in'] / 86400);
524
		$timeHours = floor(($row_members['total_time_logged_in'] % 86400) / 3600);
525
526
		// Figure out which things to show... (days, hours, minutes, etc.)
527
		$timelogged = '';
528
		if ($timeDays > 0)
529
			$timelogged .= $timeDays . $txt['total_time_logged_d'];
530
		if ($timeHours > 0)
531
			$timelogged .= $timeHours . $txt['total_time_logged_h'];
532
		$timelogged .= floor(($row_members['total_time_logged_in'] % 3600) / 60) . $txt['total_time_logged_m'];
533
534
		$context['stats_blocks']['time_online'][] = array(
535
			'id' => $row_members['id_member'],
536
			'name' => $row_members['real_name'],
537
			'num' => $timelogged,
538
			'seconds_online' => $row_members['total_time_logged_in'],
539
			'href' => $scripturl . '?action=profile;u=' . $row_members['id_member'],
540
			'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row_members['id_member'] . '">' . $row_members['real_name'] . '</a>'
541
		);
542
543
		if ($max_time_online < $row_members['total_time_logged_in'])
544
			$max_time_online = $row_members['total_time_logged_in'];
545
	}
546
	$smcFunc['db_free_result']($members_result);
547
548
	foreach ($context['stats_blocks']['time_online'] as $i => $member)
549
		$context['stats_blocks']['time_online'][$i]['percent'] = round(($member['seconds_online'] * 100) / $max_time_online);
550
551
	// Cache the ones we found for a bit, just so we don't have to look again.
552
	if ($temp !== $temp2)
553
		cache_put_data('stats_total_time_members', $temp2, 480);
554
555
	// Likes.
556
	if (!empty($modSettings['enable_likes']))
557
	{
558
		// Liked messages top 10.
559
		$context['stats_blocks']['liked_messages'] = array();
560
		$max_liked_message = 1;
561
		$liked_messages = $smcFunc['db_query']('', '
562
			SELECT m.id_msg, m.subject, m.likes, m.id_board, m.id_topic, t.approved
563
			FROM (
564
				SELECT n.id_msg, n.subject, n.likes, n.id_board, n.id_topic
565
				FROM {db_prefix}messages as n
566
				ORDER BY n.likes DESC
567
				LIMIT 1000
568
			) AS m
569
				INNER JOIN {db_prefix}topics AS t ON (m.id_topic = t.id_topic)
570
				INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
571
					AND b.id_board != {int:recycle_board}' : '') . ')
572
			WHERE m.likes > 0 AND {query_see_board}' . ($modSettings['postmod_active'] ? '
573
				AND t.approved = {int:is_approved}' : '') . '
574
			ORDER BY m.likes DESC
575
			LIMIT 10',
576
			array(
577
				'recycle_board' => $modSettings['recycle_board'],
578
				'is_approved' => 1,
579
			)
580
		);
581
582
		while ($row_liked_message = $smcFunc['db_fetch_assoc']($liked_messages))
583
		{
584
			censorText($row_liked_message['subject']);
585
586
			$context['stats_blocks']['liked_messages'][] = array(
587
				'id' => $row_liked_message['id_topic'],
588
				'subject' => $row_liked_message['subject'],
589
				'num' => $row_liked_message['likes'],
590
				'href' => $scripturl . '?msg=' . $row_liked_message['id_msg'],
591
				'link' => '<a href="' . $scripturl . '?msg=' . $row_liked_message['id_msg'] . '">' . $row_liked_message['subject'] . '</a>'
592
			);
593
594
			if ($max_liked_message < $row_liked_message['likes'])
595
				$max_liked_message = $row_liked_message['likes'];
596
		}
597
		$smcFunc['db_free_result']($liked_messages);
598
599
		foreach ($context['stats_blocks']['liked_messages'] as $i => $liked_messages)
600
			$context['stats_blocks']['liked_messages'][$i]['percent'] = round(($liked_messages['num'] * 100) / $max_liked_message);
601
602
		// Liked users top 10.
603
		$context['stats_blocks']['liked_users'] = array();
604
		$max_liked_users = 1;
605
		$liked_users = $smcFunc['db_query']('', '
606
			SELECT m.id_member AS liked_user, COUNT(l.content_id) AS count, mem.real_name
607
			FROM {db_prefix}user_likes AS l
608
				INNER JOIN {db_prefix}messages AS m ON (l.content_id = m.id_msg)
609
				INNER JOIN {db_prefix}members AS mem ON (m.id_member = mem.id_member)
610
			WHERE content_type = {literal:msg}
611
				AND m.id_member > {int:zero}
612
			GROUP BY m.id_member, mem.real_name
613
			ORDER BY count DESC
614
			LIMIT 10',
615
			array(
616
				'no_posts' => 0,
617
				'zero' => 0,
618
			)
619
		);
620
621
		while ($row_liked_users = $smcFunc['db_fetch_assoc']($liked_users))
622
		{
623
			$context['stats_blocks']['liked_users'][] = array(
624
				'id' => $row_liked_users['liked_user'],
625
				'num' => $row_liked_users['count'],
626
				'href' => $scripturl . '?action=profile;u=' . $row_liked_users['liked_user'],
627
				'name' => $row_liked_users['real_name'],
628
				'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row_liked_users['liked_user'] . '">' . $row_liked_users['real_name'] . '</a>',
629
			);
630
631
			if ($max_liked_users < $row_liked_users['count'])
632
				$max_liked_users = $row_liked_users['count'];
633
		}
634
635
		$smcFunc['db_free_result']($liked_users);
636
637
		foreach ($context['stats_blocks']['liked_users'] as $i => $liked_users)
638
			$context['stats_blocks']['liked_users'][$i]['percent'] = round(($liked_users['num'] * 100) / $max_liked_users);
639
	}
640
641
	// Activity by month.
642
	$months_result = $smcFunc['db_query']('', '
643
		SELECT
644
			YEAR(date) AS stats_year, MONTH(date) AS stats_month, SUM(hits) AS hits, SUM(registers) AS registers, SUM(topics) AS topics, SUM(posts) AS posts, MAX(most_on) AS most_on, COUNT(*) AS num_days
645
		FROM {db_prefix}log_activity
646
		GROUP BY stats_year, stats_month',
647
		array()
648
	);
649
650
	$context['yearly'] = array();
651
	while ($row_months = $smcFunc['db_fetch_assoc']($months_result))
652
	{
653
		$ID_MONTH = $row_months['stats_year'] . sprintf('%02d', $row_months['stats_month']);
654
		$expanded = !empty($_SESSION['expanded_stats'][$row_months['stats_year']]) && in_array($row_months['stats_month'], $_SESSION['expanded_stats'][$row_months['stats_year']]);
655
656
		if (!isset($context['yearly'][$row_months['stats_year']]))
657
			$context['yearly'][$row_months['stats_year']] = array(
658
				'year' => $row_months['stats_year'],
659
				'new_topics' => 0,
660
				'new_posts' => 0,
661
				'new_members' => 0,
662
				'most_members_online' => 0,
663
				'hits' => 0,
664
				'num_months' => 0,
665
				'months' => array(),
666
				'expanded' => false,
667
				'current_year' => $row_months['stats_year'] == date('Y'),
668
			);
669
670
		$context['yearly'][$row_months['stats_year']]['months'][(int) $row_months['stats_month']] = array(
671
			'id' => $ID_MONTH,
672
			'date' => array(
673
				'month' => sprintf('%02d', $row_months['stats_month']),
674
				'year' => $row_months['stats_year']
675
			),
676
			'href' => $scripturl . '?action=stats;' . ($expanded ? 'collapse' : 'expand') . '=' . $ID_MONTH . '#m' . $ID_MONTH,
677
			'link' => '<a href="' . $scripturl . '?action=stats;' . ($expanded ? 'collapse' : 'expand') . '=' . $ID_MONTH . '#m' . $ID_MONTH . '">' . $txt['months_titles'][(int) $row_months['stats_month']] . ' ' . $row_months['stats_year'] . '</a>',
678
			'month' => $txt['months_titles'][(int) $row_months['stats_month']],
679
			'year' => $row_months['stats_year'],
680
			'new_topics' => comma_format($row_months['topics']),
681
			'new_posts' => comma_format($row_months['posts']),
682
			'new_members' => comma_format($row_months['registers']),
683
			'most_members_online' => comma_format($row_months['most_on']),
684
			'hits' => comma_format($row_months['hits']),
685
			'num_days' => $row_months['num_days'],
686
			'days' => array(),
687
			'expanded' => $expanded
688
		);
689
690
		$context['yearly'][$row_months['stats_year']]['new_topics'] += $row_months['topics'];
691
		$context['yearly'][$row_months['stats_year']]['new_posts'] += $row_months['posts'];
692
		$context['yearly'][$row_months['stats_year']]['new_members'] += $row_months['registers'];
693
		$context['yearly'][$row_months['stats_year']]['hits'] += $row_months['hits'];
694
		$context['yearly'][$row_months['stats_year']]['num_months']++;
695
		$context['yearly'][$row_months['stats_year']]['expanded'] |= $expanded;
696
		$context['yearly'][$row_months['stats_year']]['most_members_online'] = max($context['yearly'][$row_months['stats_year']]['most_members_online'], $row_months['most_on']);
697
	}
698
699
	krsort($context['yearly']);
700
701
	$context['collapsed_years'] = array();
702
	foreach ($context['yearly'] as $year => $data)
703
	{
704
		// This gets rid of the filesort on the query ;).
705
		krsort($context['yearly'][$year]['months']);
706
707
		$context['yearly'][$year]['new_topics'] = comma_format($data['new_topics']);
708
		$context['yearly'][$year]['new_posts'] = comma_format($data['new_posts']);
709
		$context['yearly'][$year]['new_members'] = comma_format($data['new_members']);
710
		$context['yearly'][$year]['most_members_online'] = comma_format($data['most_members_online']);
711
		$context['yearly'][$year]['hits'] = comma_format($data['hits']);
712
713
		// Keep a list of collapsed years.
714
		if (!$data['expanded'] && !$data['current_year'])
715
			$context['collapsed_years'][] = $year;
716
	}
717
718
	// Custom stats (just add a template_layer to add it to the template!)
719
	call_integration_hook('integrate_forum_stats');
720
721
	if (empty($_SESSION['expanded_stats']))
722
		return;
723
724
	$condition_text = array();
725
	$condition_params = array();
726
	foreach ($_SESSION['expanded_stats'] as $year => $months)
727
		if (!empty($months))
728
		{
729
			$condition_text[] = 'YEAR(date) = {int:year_' . $year . '} AND MONTH(date) IN ({array_int:months_' . $year . '})';
730
			$condition_params['year_' . $year] = $year;
731
			$condition_params['months_' . $year] = $months;
732
		}
733
734
	// No daily stats to even look at?
735
	if (empty($condition_text))
736
		return;
737
738
	getDailyStats(implode(' OR ', $condition_text), $condition_params);
739
}
740
741
/**
742
 * Loads the statistics on a daily basis in $context.
743
 * called by DisplayStats().
744
 *
745
 * @param string $condition_string An SQL condition string
746
 * @param array $condition_parameters Parameters for $condition_string
747
 */
748
function getDailyStats($condition_string, $condition_parameters = array())
749
{
750
	global $context, $smcFunc;
751
752
	// Activity by day.
753
	$days_result = $smcFunc['db_query']('', '
754
		SELECT YEAR(date) AS stats_year, MONTH(date) AS stats_month, DAYOFMONTH(date) AS stats_day, topics, posts, registers, most_on, hits
755
		FROM {db_prefix}log_activity
756
		WHERE ' . $condition_string . '
757
		ORDER BY stats_day ASC',
758
		$condition_parameters
759
	);
760
	while ($row_days = $smcFunc['db_fetch_assoc']($days_result))
761
		$context['yearly'][$row_days['stats_year']]['months'][(int) $row_days['stats_month']]['days'][] = array(
762
			'day' => sprintf('%02d', $row_days['stats_day']),
763
			'month' => sprintf('%02d', $row_days['stats_month']),
764
			'year' => $row_days['stats_year'],
765
			'new_topics' => comma_format($row_days['topics']),
766
			'new_posts' => comma_format($row_days['posts']),
767
			'new_members' => comma_format($row_days['registers']),
768
			'most_members_online' => comma_format($row_days['most_on']),
769
			'hits' => comma_format($row_days['hits'])
770
		);
771
	$smcFunc['db_free_result']($days_result);
772
}
773
774
/**
775
 * This is the function which returns stats to simplemachines.org IF enabled!
776
 * called by simplemachines.org.
777
 * only returns anything if stats was enabled during installation.
778
 * can also be accessed by the admin, to show what stats sm.org collects.
779
 * does not return any data directly to sm.org, instead starts a new request for security.
780
 *
781
 * @link https://www.simplemachines.org/about/stats.php for more info.
782
 */
783
function SMStats()
784
{
785
	global $modSettings, $user_info, $sourcedir;
786
787
	// First, is it disabled?
788
	if (empty($modSettings['enable_sm_stats']) || empty($modSettings['sm_stats_key']))
789
		die();
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
790
791
	// Are we saying who we are, and are we right? (OR an admin)
792
	if (!$user_info['is_admin'] && (!isset($_GET['sid']) || $_GET['sid'] != $modSettings['sm_stats_key']))
793
		die();
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
794
795
	// Verify the referer...
796
	if (!$user_info['is_admin'] && (!isset($_SERVER['HTTP_REFERER']) || md5($_SERVER['HTTP_REFERER']) != '746cb59a1a0d5cf4bd240e5a67c73085'))
797
		die();
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
798
799
	// Get some server versions.
800
	require_once($sourcedir . '/Subs-Admin.php');
801
	$checkFor = array(
802
		'php',
803
		'db_server',
804
	);
805
	$serverVersions = getServerVersions($checkFor);
806
807
	// Get the actual stats.
808
	$stats_to_send = array(
809
		'UID' => $modSettings['sm_stats_key'],
810
		'time_added' => time(),
811
		'members' => $modSettings['totalMembers'],
812
		'messages' => $modSettings['totalMessages'],
813
		'topics' => $modSettings['totalTopics'],
814
		'boards' => 0,
815
		'php_version' => $serverVersions['php']['version'],
816
		'database_type' => strtolower($serverVersions['db_engine']['version']),
817
		'database_version' => $serverVersions['db_server']['version'],
818
		'smf_version' => SMF_FULL_VERSION,
819
		'smfd_version' => $modSettings['smfVersion'],
820
	);
821
822
	// Encode all the data, for security.
823
	foreach ($stats_to_send as $k => $v)
824
		$stats_to_send[$k] = urlencode($k) . '=' . urlencode($v);
825
826
	// Turn this into the query string!
827
	$stats_to_send = implode('&', $stats_to_send);
828
829
	// If we're an admin, just plonk them out.
830
	if ($user_info['is_admin'])
831
		echo $stats_to_send;
832
	else
833
	{
834
		// Connect to the collection script.
835
		$fp = @fsockopen('www.simplemachines.org', 443, $errno, $errstr);
836
		if (!$fp)
0 ignored issues
show
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
837
			$fp = @fsockopen('www.simplemachines.org', 80, $errno, $errstr);
838
		if ($fp)
0 ignored issues
show
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
839
		{
840
			$length = strlen($stats_to_send);
841
842
			$out = 'POST /smf/stats/collect_stats.php HTTP/1.1' . "\r\n";
843
			$out .= 'Host: www.simplemachines.org' . "\r\n";
844
			$out .= 'user-agent: '. SMF_USER_AGENT . "\r\n";
845
			$out .= 'content-type: application/x-www-form-urlencoded' . "\r\n";
846
			$out .= 'connection: Close' . "\r\n";
847
			$out .= 'content-length: ' . $length . "\r\n\r\n";
848
			$out .= $stats_to_send . "\r\n";
849
			fwrite($fp, $out);
850
			fclose($fp);
851
		}
852
	}
853
854
	// Die.
855
	die('OK');
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
856
}
857
858
?>