Issues (1061)

Sources/Profile-Actions.php (1 issue)

1
<?php
2
3
/**
4
 * This file handles actions made on a user's profile.
5
 *
6
 * Simple Machines Forum (SMF)
7
 *
8
 * @package SMF
9
 * @author Simple Machines https://www.simplemachines.org
10
 * @copyright 2020 Simple Machines and individual contributors
11
 * @license https://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1 RC2
14
 */
15
16
if (!defined('SMF'))
17
	die('No direct access...');
18
19
/**
20
 * Activate an account.
21
 *
22
 * @param int $memID The ID of the member whose account we're activating
23
 */
24
function activateAccount($memID)
25
{
26
	global $sourcedir, $context, $user_profile, $modSettings;
27
28
	isAllowedTo('moderate_forum');
29
30
	if (isset($_REQUEST['save']) && isset($user_profile[$memID]['is_activated']) && $user_profile[$memID]['is_activated'] != 1)
31
	{
32
		// If we are approving the deletion of an account, we do something special ;)
33
		if ($user_profile[$memID]['is_activated'] == 4)
34
		{
35
			require_once($sourcedir . '/Subs-Members.php');
36
			deleteMembers($context['id_member']);
37
			redirectexit();
38
		}
39
40
		// Let the integrations know of the activation.
41
		call_integration_hook('integrate_activate', array($user_profile[$memID]['member_name']));
42
43
		// Actually update this member now, as it guarantees the unapproved count can't get corrupted.
44
		updateMemberData($context['id_member'], array('is_activated' => $user_profile[$memID]['is_activated'] >= 10 ? 11 : 1, 'validation_code' => ''));
45
46
		// Log what we did?
47
		require_once($sourcedir . '/Logging.php');
48
		logAction('approve_member', array('member' => $memID), 'admin');
49
50
		// If we are doing approval, update the stats for the member just in case.
51
		if (in_array($user_profile[$memID]['is_activated'], array(3, 4, 5, 13, 14, 15)))
52
			updateSettings(array('unapprovedMembers' => ($modSettings['unapprovedMembers'] > 1 ? $modSettings['unapprovedMembers'] - 1 : 0)));
53
54
		// Make sure we update the stats too.
55
		updateStats('member', false);
56
	}
57
58
	// Leave it be...
59
	redirectexit('action=profile;u=' . $memID . ';area=summary');
60
}
61
62
/**
63
 * Issue/manage an user's warning status.
64
 *
65
 * @param int $memID The ID of the user
66
 */
67
function issueWarning($memID)
68
{
69
	global $txt, $scripturl, $modSettings, $user_info, $mbname;
70
	global $context, $cur_profile, $smcFunc, $sourcedir;
71
72
	// Get all the actual settings.
73
	list ($modSettings['warning_enable'], $modSettings['user_limit']) = explode(',', $modSettings['warning_settings']);
74
75
	// This stores any legitimate errors.
76
	$issueErrors = array();
77
78
	// Doesn't hurt to be overly cautious.
79
	if (empty($modSettings['warning_enable']) || ($context['user']['is_owner'] && !$cur_profile['warning']) || !allowedTo('issue_warning'))
80
		fatal_lang_error('no_access', false);
81
82
	// Get the base (errors related) stuff done.
83
	loadLanguage('Errors');
84
	$context['custom_error_title'] = $txt['profile_warning_errors_occured'];
85
86
	// Make sure things which are disabled stay disabled.
87
	$modSettings['warning_watch'] = !empty($modSettings['warning_watch']) ? $modSettings['warning_watch'] : 110;
88
	$modSettings['warning_moderate'] = !empty($modSettings['warning_moderate']) && !empty($modSettings['postmod_active']) ? $modSettings['warning_moderate'] : 110;
89
	$modSettings['warning_mute'] = !empty($modSettings['warning_mute']) ? $modSettings['warning_mute'] : 110;
90
91
	$context['warning_limit'] = allowedTo('admin_forum') ? 0 : $modSettings['user_limit'];
92
	$context['member']['warning'] = $cur_profile['warning'];
93
	$context['member']['name'] = $cur_profile['real_name'];
94
95
	// What are the limits we can apply?
96
	$context['min_allowed'] = 0;
97
	$context['max_allowed'] = 100;
98
	if ($context['warning_limit'] > 0)
99
	{
100
		// Make sure we cannot go outside of our limit for the day.
101
		$request = $smcFunc['db_query']('', '
102
			SELECT SUM(counter)
103
			FROM {db_prefix}log_comments
104
			WHERE id_recipient = {int:selected_member}
105
				AND id_member = {int:current_member}
106
				AND comment_type = {string:warning}
107
				AND log_time > {int:day_time_period}',
108
			array(
109
				'current_member' => $user_info['id'],
110
				'selected_member' => $memID,
111
				'day_time_period' => time() - 86400,
112
				'warning' => 'warning',
113
			)
114
		);
115
		list ($current_applied) = $smcFunc['db_fetch_row']($request);
116
		$smcFunc['db_free_result']($request);
117
118
		$context['min_allowed'] = max(0, $cur_profile['warning'] - $current_applied - $context['warning_limit']);
119
		$context['max_allowed'] = min(100, $cur_profile['warning'] - $current_applied + $context['warning_limit']);
120
	}
121
122
	// Defaults.
123
	$context['warning_data'] = array(
124
		'reason' => '',
125
		'notify' => '',
126
		'notify_subject' => '',
127
		'notify_body' => '',
128
	);
129
130
	// Are we saving?
131
	if (isset($_POST['save']))
132
	{
133
		// Security is good here.
134
		checkSession();
135
136
		// This cannot be empty!
137
		$_POST['warn_reason'] = isset($_POST['warn_reason']) ? trim($_POST['warn_reason']) : '';
138
		if ($_POST['warn_reason'] == '' && !$context['user']['is_owner'])
139
			$issueErrors[] = 'warning_no_reason';
140
		$_POST['warn_reason'] = $smcFunc['htmlspecialchars']($_POST['warn_reason']);
141
142
		$_POST['warning_level'] = (int) $_POST['warning_level'];
143
		$_POST['warning_level'] = max(0, min(100, $_POST['warning_level']));
144
		if ($_POST['warning_level'] < $context['min_allowed'])
145
			$_POST['warning_level'] = $context['min_allowed'];
146
		elseif ($_POST['warning_level'] > $context['max_allowed'])
147
			$_POST['warning_level'] = $context['max_allowed'];
148
149
		// Do we actually have to issue them with a PM?
150
		$id_notice = 0;
151
		if (!empty($_POST['warn_notify']) && empty($issueErrors))
152
		{
153
			$_POST['warn_sub'] = trim($_POST['warn_sub']);
154
			$_POST['warn_body'] = trim($_POST['warn_body']);
155
			if (empty($_POST['warn_sub']) || empty($_POST['warn_body']))
156
				$issueErrors[] = 'warning_notify_blank';
157
			// Send the PM?
158
			else
159
			{
160
				require_once($sourcedir . '/Subs-Post.php');
161
				$from = array(
162
					'id' => 0,
163
					'name' => $context['forum_name_html_safe'],
164
					'username' => $context['forum_name_html_safe'],
165
				);
166
				sendpm(array('to' => array($memID), 'bcc' => array()), $_POST['warn_sub'], $_POST['warn_body'], false, $from);
167
168
				// Log the notice!
169
				$id_notice = $smcFunc['db_insert']('',
170
					'{db_prefix}log_member_notices',
171
					array(
172
						'subject' => 'string-255', 'body' => 'string-65534',
173
					),
174
					array(
175
						$smcFunc['htmlspecialchars']($_POST['warn_sub']), $smcFunc['htmlspecialchars']($_POST['warn_body']),
176
					),
177
					array('id_notice'),
178
					1
179
				);
180
			}
181
		}
182
183
		// Just in case - make sure notice is valid!
184
		$id_notice = (int) $id_notice;
185
186
		// What have we changed?
187
		$level_change = $_POST['warning_level'] - $cur_profile['warning'];
188
189
		// No errors? Proceed! Only log if you're not the owner.
190
		if (empty($issueErrors))
191
		{
192
			// Log what we've done!
193
			if (!$context['user']['is_owner'])
194
				$smcFunc['db_insert']('',
195
					'{db_prefix}log_comments',
196
					array(
197
						'id_member' => 'int', 'member_name' => 'string', 'comment_type' => 'string', 'id_recipient' => 'int', 'recipient_name' => 'string-255',
198
						'log_time' => 'int', 'id_notice' => 'int', 'counter' => 'int', 'body' => 'string-65534',
199
					),
200
					array(
201
						$user_info['id'], $user_info['name'], 'warning', $memID, $cur_profile['real_name'],
202
						time(), $id_notice, $level_change, $_POST['warn_reason'],
203
					),
204
					array('id_comment')
205
				);
206
207
			// Make the change.
208
			updateMemberData($memID, array('warning' => $_POST['warning_level']));
209
210
			// Leave a lovely message.
211
			$context['profile_updated'] = $context['user']['is_owner'] ? $txt['profile_updated_own'] : $txt['profile_warning_success'];
212
		}
213
		else
214
		{
215
			// Try to remember some bits.
216
			$context['warning_data'] = array(
217
				'reason' => $_POST['warn_reason'],
218
				'notify' => !empty($_POST['warn_notify']),
219
				'notify_subject' => isset($_POST['warn_sub']) ? $_POST['warn_sub'] : '',
220
				'notify_body' => isset($_POST['warn_body']) ? $_POST['warn_body'] : '',
221
			);
222
		}
223
224
		// Show the new improved warning level.
225
		$context['member']['warning'] = $_POST['warning_level'];
226
	}
227
228
	if (isset($_POST['preview']))
229
	{
230
		$warning_body = !empty($_POST['warn_body']) ? trim(censorText($_POST['warn_body'])) : '';
231
		$context['preview_subject'] = !empty($_POST['warn_sub']) ? trim($smcFunc['htmlspecialchars']($_POST['warn_sub'])) : '';
232
		if (empty($_POST['warn_sub']) || empty($_POST['warn_body']))
233
			$issueErrors[] = 'warning_notify_blank';
234
235
		if (!empty($_POST['warn_body']))
236
		{
237
			require_once($sourcedir . '/Subs-Post.php');
238
239
			preparsecode($warning_body);
240
			$warning_body = parse_bbc($warning_body, true);
241
		}
242
243
		// Try to remember some bits.
244
		$context['warning_data'] = array(
245
			'reason' => $_POST['warn_reason'],
246
			'notify' => !empty($_POST['warn_notify']),
247
			'notify_subject' => isset($_POST['warn_sub']) ? $_POST['warn_sub'] : '',
248
			'notify_body' => isset($_POST['warn_body']) ? $_POST['warn_body'] : '',
249
			'body_preview' => $warning_body,
250
		);
251
	}
252
253
	if (!empty($issueErrors))
254
	{
255
		// Fill in the suite of errors.
256
		$context['post_errors'] = array();
257
		foreach ($issueErrors as $error)
258
			$context['post_errors'][] = $txt[$error];
259
	}
260
261
	$context['page_title'] = $txt['profile_issue_warning'];
262
263
	// Let's use a generic list to get all the current warnings
264
	require_once($sourcedir . '/Subs-List.php');
265
266
	// Work our the various levels.
267
	$context['level_effects'] = array(
268
		0 => $txt['profile_warning_effect_none'],
269
		$modSettings['warning_watch'] => $txt['profile_warning_effect_watch'],
270
		$modSettings['warning_moderate'] => $txt['profile_warning_effect_moderation'],
271
		$modSettings['warning_mute'] => $txt['profile_warning_effect_mute'],
272
	);
273
	$context['current_level'] = 0;
274
	foreach ($context['level_effects'] as $limit => $dummy)
275
		if ($context['member']['warning'] >= $limit)
276
			$context['current_level'] = $limit;
277
278
	$listOptions = array(
279
		'id' => 'view_warnings',
280
		'title' => $txt['profile_viewwarning_previous_warnings'],
281
		'items_per_page' => $modSettings['defaultMaxListItems'],
282
		'no_items_label' => $txt['profile_viewwarning_no_warnings'],
283
		'base_href' => $scripturl . '?action=profile;area=issuewarning;sa=user;u=' . $memID,
284
		'default_sort_col' => 'log_time',
285
		'get_items' => array(
286
			'function' => 'list_getUserWarnings',
287
			'params' => array(
288
				$memID,
289
			),
290
		),
291
		'get_count' => array(
292
			'function' => 'list_getUserWarningCount',
293
			'params' => array(
294
				$memID,
295
			),
296
		),
297
		'columns' => array(
298
			'issued_by' => array(
299
				'header' => array(
300
					'value' => $txt['profile_warning_previous_issued'],
301
					'style' => 'width: 20%;',
302
				),
303
				'data' => array(
304
					'function' => function($warning)
305
					{
306
						return $warning['issuer']['link'];
307
					},
308
				),
309
				'sort' => array(
310
					'default' => 'lc.member_name DESC',
311
					'reverse' => 'lc.member_name',
312
				),
313
			),
314
			'log_time' => array(
315
				'header' => array(
316
					'value' => $txt['profile_warning_previous_time'],
317
					'style' => 'width: 30%;',
318
				),
319
				'data' => array(
320
					'db' => 'time',
321
				),
322
				'sort' => array(
323
					'default' => 'lc.log_time DESC',
324
					'reverse' => 'lc.log_time',
325
				),
326
			),
327
			'reason' => array(
328
				'header' => array(
329
					'value' => $txt['profile_warning_previous_reason'],
330
				),
331
				'data' => array(
332
					'function' => function($warning) use ($scripturl, $txt)
333
					{
334
						$ret = '
335
						<div class="floatleft">
336
							' . $warning['reason'] . '
337
						</div>';
338
339
						if (!empty($warning['id_notice']))
340
							$ret .= '
341
						<div class="floatright">
342
							<a href="' . $scripturl . '?action=moderate;area=notice;nid=' . $warning['id_notice'] . '" onclick="window.open(this.href, \'\', \'scrollbars=yes,resizable=yes,width=400,height=250\');return false;" target="_blank" rel="noopener" title="' . $txt['profile_warning_previous_notice'] . '"><span class="main_icons filter centericon"></span></a>
343
						</div>';
344
345
						return $ret;
346
					},
347
				),
348
			),
349
			'level' => array(
350
				'header' => array(
351
					'value' => $txt['profile_warning_previous_level'],
352
					'style' => 'width: 6%;',
353
				),
354
				'data' => array(
355
					'db' => 'counter',
356
				),
357
				'sort' => array(
358
					'default' => 'lc.counter DESC',
359
					'reverse' => 'lc.counter',
360
				),
361
			),
362
		),
363
	);
364
365
	// Create the list for viewing.
366
	require_once($sourcedir . '/Subs-List.php');
367
	createList($listOptions);
368
369
	// Are they warning because of a message?
370
	if (isset($_REQUEST['msg']) && 0 < (int) $_REQUEST['msg'])
371
	{
372
		$request = $smcFunc['db_query']('', '
373
			SELECT m.subject
374
			FROM {db_prefix}messages AS m
375
			WHERE m.id_msg = {int:message}
376
				AND {query_see_message_board}
377
			LIMIT 1',
378
			array(
379
				'message' => (int) $_REQUEST['msg'],
380
			)
381
		);
382
		if ($smcFunc['db_num_rows']($request) != 0)
383
		{
384
			$context['warning_for_message'] = (int) $_REQUEST['msg'];
385
			list ($context['warned_message_subject']) = $smcFunc['db_fetch_row']($request);
386
		}
387
		$smcFunc['db_free_result']($request);
388
	}
389
390
	// Didn't find the message?
391
	if (empty($context['warning_for_message']))
392
	{
393
		$context['warning_for_message'] = 0;
394
		$context['warned_message_subject'] = '';
395
	}
396
397
	// Any custom templates?
398
	$context['notification_templates'] = array();
399
400
	$request = $smcFunc['db_query']('', '
401
		SELECT recipient_name AS template_title, body
402
		FROM {db_prefix}log_comments
403
		WHERE comment_type = {literal:warntpl}
404
			AND (id_recipient = {int:generic} OR id_recipient = {int:current_member})',
405
		array(
406
			'generic' => 0,
407
			'current_member' => $user_info['id'],
408
		)
409
	);
410
	while ($row = $smcFunc['db_fetch_assoc']($request))
411
	{
412
		// If we're not warning for a message skip any that are.
413
		if (!$context['warning_for_message'] && strpos($row['body'], '{MESSAGE}') !== false)
414
			continue;
415
416
		$context['notification_templates'][] = array(
417
			'title' => $row['template_title'],
418
			'body' => $row['body'],
419
		);
420
	}
421
	$smcFunc['db_free_result']($request);
422
423
	// Setup the "default" templates.
424
	foreach (array('spamming', 'offence', 'insulting') as $type)
425
		$context['notification_templates'][] = array(
426
			'title' => $txt['profile_warning_notify_title_' . $type],
427
			'body' => sprintf($txt['profile_warning_notify_template_outline' . (!empty($context['warning_for_message']) ? '_post' : '')], $txt['profile_warning_notify_for_' . $type]),
428
		);
429
430
	// Replace all the common variables in the templates.
431
	foreach ($context['notification_templates'] as $k => $name)
432
		$context['notification_templates'][$k]['body'] = strtr($name['body'], array('{MEMBER}' => un_htmlspecialchars($context['member']['name']), '{MESSAGE}' => '[url=' . $scripturl . '?msg=' . $context['warning_for_message'] . ']' . un_htmlspecialchars($context['warned_message_subject']) . '[/url]', '{SCRIPTURL}' => $scripturl, '{FORUMNAME}' => $mbname, '{REGARDS}' => $txt['regards_team']));
433
}
434
435
/**
436
 * Get the number of warnings a user has. Callback for $listOptions['get_count'] in issueWarning()
437
 *
438
 * @param int $memID The ID of the user
439
 * @return int Total number of warnings for the user
440
 */
441
function list_getUserWarningCount($memID)
442
{
443
	global $smcFunc;
444
445
	$request = $smcFunc['db_query']('', '
446
		SELECT COUNT(*)
447
		FROM {db_prefix}log_comments
448
		WHERE id_recipient = {int:selected_member}
449
			AND comment_type = {literal:warning}',
450
		array(
451
			'selected_member' => $memID,
452
		)
453
	);
454
	list ($total_warnings) = $smcFunc['db_fetch_row']($request);
455
	$smcFunc['db_free_result']($request);
456
457
	return $total_warnings;
458
}
459
460
/**
461
 * Get the data about a user's warnings. Callback function for the list in issueWarning()
462
 *
463
 * @param int $start The item to start with (for pagination purposes)
464
 * @param int $items_per_page How many items to show on each page
465
 * @param string $sort A string indicating how to sort the results
466
 * @param int $memID The member ID
467
 * @return array An array of information about the user's warnings
468
 */
469
function list_getUserWarnings($start, $items_per_page, $sort, $memID)
470
{
471
	global $smcFunc, $scripturl;
472
473
	$request = $smcFunc['db_query']('', '
474
		SELECT COALESCE(mem.id_member, 0) AS id_member, COALESCE(mem.real_name, lc.member_name) AS member_name,
475
			lc.log_time, lc.body, lc.counter, lc.id_notice
476
		FROM {db_prefix}log_comments AS lc
477
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lc.id_member)
478
		WHERE lc.id_recipient = {int:selected_member}
479
			AND lc.comment_type = {literal:warning}
480
		ORDER BY {raw:sort}
481
		LIMIT {int:start}, {int:max}',
482
		array(
483
			'selected_member' => $memID,
484
			'sort' => $sort,
485
			'start' => $start,
486
			'max' => $items_per_page,
487
		)
488
	);
489
	$previous_warnings = array();
490
	while ($row = $smcFunc['db_fetch_assoc']($request))
491
	{
492
		$previous_warnings[] = array(
493
			'issuer' => array(
494
				'id' => $row['id_member'],
495
				'link' => $row['id_member'] ? ('<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['member_name'] . '</a>') : $row['member_name'],
496
			),
497
			'time' => timeformat($row['log_time']),
498
			'reason' => $row['body'],
499
			'counter' => $row['counter'] > 0 ? '+' . $row['counter'] : $row['counter'],
500
			'id_notice' => $row['id_notice'],
501
		);
502
	}
503
	$smcFunc['db_free_result']($request);
504
505
	return $previous_warnings;
506
}
507
508
/**
509
 * Present a screen to make sure the user wants to be deleted
510
 *
511
 * @param int $memID The member ID
512
 */
513
function deleteAccount($memID)
514
{
515
	global $txt, $context, $modSettings, $cur_profile;
516
517
	if (!$context['user']['is_owner'])
518
		isAllowedTo('profile_remove_any');
519
	elseif (!allowedTo('profile_remove_any'))
520
		isAllowedTo('profile_remove_own');
521
522
	// Permissions for removing stuff...
523
	$context['can_delete_posts'] = !$context['user']['is_owner'] && allowedTo('moderate_forum');
524
525
	// Show an extra option if recycling is enabled...
526
	$context['show_perma_delete'] = !empty($modSettings['recycle_enable']) && !empty($modSettings['recycle_board']);
527
528
	// Can they do this, or will they need approval?
529
	$context['needs_approval'] = $context['user']['is_owner'] && !empty($modSettings['approveAccountDeletion']) && !allowedTo('moderate_forum');
530
	$context['page_title'] = $txt['deleteAccount'] . ': ' . $cur_profile['real_name'];
531
}
532
533
/**
534
 * Actually delete an account.
535
 *
536
 * @param int $memID The member ID
537
 */
538
function deleteAccount2($memID)
539
{
540
	global $user_info, $sourcedir, $context, $cur_profile, $modSettings, $smcFunc;
541
542
	// Try get more time...
543
	@set_time_limit(600);
544
545
	// @todo Add a way to delete pms as well?
546
547
	if (!$context['user']['is_owner'])
548
		isAllowedTo('profile_remove_any');
549
	elseif (!allowedTo('profile_remove_any'))
550
		isAllowedTo('profile_remove_own');
551
552
	checkSession();
553
554
	$old_profile = &$cur_profile;
555
556
	// Too often, people remove/delete their own only account.
557
	if (in_array(1, explode(',', $old_profile['additional_groups'])) || $old_profile['id_group'] == 1)
558
	{
559
		// Are you allowed to administrate the forum, as they are?
560
		isAllowedTo('admin_forum');
561
562
		$request = $smcFunc['db_query']('', '
563
			SELECT id_member
564
			FROM {db_prefix}members
565
			WHERE (id_group = {int:admin_group} OR FIND_IN_SET({int:admin_group}, additional_groups) != 0)
566
				AND id_member != {int:selected_member}
567
			LIMIT 1',
568
			array(
569
				'admin_group' => 1,
570
				'selected_member' => $memID,
571
			)
572
		);
573
		list ($another) = $smcFunc['db_fetch_row']($request);
574
		$smcFunc['db_free_result']($request);
575
576
		if (empty($another))
577
			fatal_lang_error('at_least_one_admin', 'critical');
578
	}
579
580
	// This file is needed for the deleteMembers function.
581
	require_once($sourcedir . '/Subs-Members.php');
582
583
	// Do you have permission to delete others profiles, or is that your profile you wanna delete?
584
	if ($memID != $user_info['id'])
585
	{
586
		isAllowedTo('profile_remove_any');
587
588
		// Before we go any further, handle possible poll vote deletion as well
589
		if (!empty($_POST['deleteVotes']) && allowedTo('moderate_forum'))
590
		{
591
			// First we find any polls that this user has voted in...
592
			$get_voted_polls = $smcFunc['db_query']('', '
593
				SELECT DISTINCT id_poll
594
				FROM {db_prefix}log_polls
595
				WHERE id_member = {int:selected_member}',
596
				array(
597
					'selected_member' => $memID,
598
				)
599
			);
600
601
			$polls_to_update = array();
602
603
			while ($row = $smcFunc['db_fetch_assoc']($get_voted_polls))
604
			{
605
				$polls_to_update[] = $row['id_poll'];
606
			}
607
608
			$smcFunc['db_free_result']($get_voted_polls);
609
610
			// Now we delete the votes and update the polls
611
			if (!empty($polls_to_update))
612
			{
613
				$smcFunc['db_query']('', '
614
					DELETE FROM {db_prefix}log_polls
615
					WHERE id_member = {int:selected_member}',
616
					array(
617
						'selected_member' => $memID,
618
					)
619
				);
620
621
				$smcFunc['db_query']('', '
622
					UPDATE {db_prefix}polls
623
					SET votes = votes - 1
624
					WHERE id_poll IN {array_int:polls_to_update}',
625
					array(
626
						'polls_to_update' => $polls_to_update
627
					)
628
				);
629
			}
630
		}
631
632
		// Now, have you been naughty and need your posts deleting?
633
		// @todo Should this check board permissions?
634
		if (!empty($_POST['deletePosts']) && in_array($_POST['remove_type'], array('posts', 'topics')) && allowedTo('moderate_forum'))
635
		{
636
			// Include RemoveTopics - essential for this type of work!
637
			require_once($sourcedir . '/RemoveTopic.php');
638
639
			$extra = empty($_POST['perma_delete']) ? ' AND t.id_board != {int:recycle_board}' : '';
640
			$recycle_board = empty($modSettings['recycle_board']) ? 0 : $modSettings['recycle_board'];
641
642
			// First off we delete any topics the member has started - if they wanted topics being done.
643
			if ($_POST['remove_type'] == 'topics')
644
			{
645
				// Fetch all topics started by this user within the time period.
646
				$request = $smcFunc['db_query']('', '
647
					SELECT t.id_topic
648
					FROM {db_prefix}topics AS t
649
					WHERE t.id_member_started = {int:selected_member}' . $extra,
650
					array(
651
						'selected_member' => $memID,
652
						'recycle_board' => $recycle_board,
653
					)
654
				);
655
				$topicIDs = array();
656
				while ($row = $smcFunc['db_fetch_assoc']($request))
657
					$topicIDs[] = $row['id_topic'];
658
				$smcFunc['db_free_result']($request);
659
660
				// Actually remove the topics. Ignore recycling if we want to perma-delete things...
661
				// @todo This needs to check permissions, but we'll let it slide for now because of moderate_forum already being had.
662
				removeTopics($topicIDs, true, !empty($extra));
663
			}
664
665
			// Now delete the remaining messages.
666
			$request = $smcFunc['db_query']('', '
667
				SELECT m.id_msg
668
				FROM {db_prefix}messages AS m
669
					INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic
670
						AND t.id_first_msg != m.id_msg)
671
				WHERE m.id_member = {int:selected_member}' . $extra,
672
				array(
673
					'selected_member' => $memID,
674
					'recycle_board' => $recycle_board,
675
				)
676
			);
677
			// This could take a while... but ya know it's gonna be worth it in the end.
678
			while ($row = $smcFunc['db_fetch_assoc']($request))
679
			{
680
				if (function_exists('apache_reset_timeout'))
681
					@apache_reset_timeout();
682
683
				removeMessage($row['id_msg']);
684
			}
685
			$smcFunc['db_free_result']($request);
686
		}
687
688
		// Only delete this poor members account if they are actually being booted out of camp.
689
		if (isset($_POST['deleteAccount']))
690
			deleteMembers($memID);
691
	}
692
	// Do they need approval to delete?
693
	elseif (!empty($modSettings['approveAccountDeletion']) && !allowedTo('moderate_forum'))
694
	{
695
		// Setup their account for deletion ;)
696
		updateMemberData($memID, array('is_activated' => 4));
697
		// Another account needs approval...
698
		updateSettings(array('unapprovedMembers' => true), true);
699
	}
700
	// Also check if you typed your password correctly.
701
	else
702
	{
703
		deleteMembers($memID);
704
705
		require_once($sourcedir . '/LogInOut.php');
706
		LogOut(true);
707
708
		redirectexit();
709
	}
710
}
711
712
/**
713
 * Function for doing all the paid subscription stuff - kinda.
714
 *
715
 * @param int $memID The ID of the user whose subscriptions we're viewing
716
 */
717
function subscriptions($memID)
718
{
719
	global $context, $txt, $sourcedir, $modSettings, $smcFunc, $scripturl;
720
721
	// Load the paid template anyway.
722
	loadTemplate('ManagePaid');
723
	loadLanguage('ManagePaid');
724
725
	// Load all of the subscriptions.
726
	require_once($sourcedir . '/ManagePaid.php');
727
	loadSubscriptions();
728
	$context['member']['id'] = $memID;
729
730
	// Remove any invalid ones.
731
	foreach ($context['subscriptions'] as $id => $sub)
732
	{
733
		// Work out the costs.
734
		$costs = $smcFunc['json_decode']($sub['real_cost'], true);
735
736
		$cost_array = array();
737
		if ($sub['real_length'] == 'F')
738
		{
739
			foreach ($costs as $duration => $cost)
740
			{
741
				if ($cost != 0)
742
					$cost_array[$duration] = $cost;
743
			}
744
		}
745
		else
746
		{
747
			$cost_array['fixed'] = $costs['fixed'];
748
		}
749
750
		if (empty($cost_array))
751
			unset($context['subscriptions'][$id]);
752
		else
753
		{
754
			$context['subscriptions'][$id]['member'] = 0;
755
			$context['subscriptions'][$id]['subscribed'] = false;
756
			$context['subscriptions'][$id]['costs'] = $cost_array;
757
		}
758
	}
759
760
	// Work out what gateways are enabled.
761
	$gateways = loadPaymentGateways();
762
	foreach ($gateways as $id => $gateway)
763
	{
764
		$gateways[$id] = new $gateway['display_class']();
765
		if (!$gateways[$id]->gatewayEnabled())
766
			unset($gateways[$id]);
767
	}
768
769
	// No gateways yet?
770
	if (empty($gateways))
771
		fatal_error($txt['paid_admin_not_setup_gateway']);
772
773
	// Get the current subscriptions.
774
	$request = $smcFunc['db_query']('', '
775
		SELECT id_sublog, id_subscribe, start_time, end_time, status, payments_pending, pending_details
776
		FROM {db_prefix}log_subscribed
777
		WHERE id_member = {int:selected_member}',
778
		array(
779
			'selected_member' => $memID,
780
		)
781
	);
782
	$context['current'] = array();
783
	while ($row = $smcFunc['db_fetch_assoc']($request))
784
	{
785
		// The subscription must exist!
786
		if (!isset($context['subscriptions'][$row['id_subscribe']]))
787
			continue;
788
789
		$context['current'][$row['id_subscribe']] = array(
790
			'id' => $row['id_sublog'],
791
			'sub_id' => $row['id_subscribe'],
792
			'hide' => $row['status'] == 0 && $row['end_time'] == 0 && $row['payments_pending'] == 0,
793
			'name' => $context['subscriptions'][$row['id_subscribe']]['name'],
794
			'start' => timeformat($row['start_time'], false),
795
			'end' => $row['end_time'] == 0 ? $txt['not_applicable'] : timeformat($row['end_time'], false),
796
			'pending_details' => $row['pending_details'],
797
			'status' => $row['status'],
798
			'status_text' => $row['status'] == 0 ? ($row['payments_pending'] ? $txt['paid_pending'] : $txt['paid_finished']) : $txt['paid_active'],
799
		);
800
801
		if ($row['status'] == 1)
802
			$context['subscriptions'][$row['id_subscribe']]['subscribed'] = true;
803
	}
804
	$smcFunc['db_free_result']($request);
805
806
	// Simple "done"?
807
	if (isset($_GET['done']))
808
	{
809
		$_GET['sub_id'] = (int) $_GET['sub_id'];
810
811
		// Must exist but let's be sure...
812
		if (isset($context['current'][$_GET['sub_id']]))
813
		{
814
			// What are the details like?
815
			$current_pending = $smcFunc['json_decode']($context['current'][$_GET['sub_id']]['pending_details'], true);
816
			if (!empty($current_pending))
817
			{
818
				$current_pending = array_reverse($current_pending);
819
				foreach ($current_pending as $id => $sub)
820
				{
821
					// Just find one and change it.
822
					if ($sub[0] == $_GET['sub_id'] && $sub[3] == 'prepay')
823
					{
824
						$current_pending[$id][3] = 'payback';
825
						break;
826
					}
827
				}
828
829
				// Save the details back.
830
				$pending_details = $smcFunc['json_encode']($current_pending);
831
832
				$smcFunc['db_query']('', '
833
					UPDATE {db_prefix}log_subscribed
834
					SET payments_pending = payments_pending + 1, pending_details = {string:pending_details}
835
					WHERE id_sublog = {int:current_subscription_id}
836
						AND id_member = {int:selected_member}',
837
					array(
838
						'current_subscription_id' => $context['current'][$_GET['sub_id']]['id'],
839
						'selected_member' => $memID,
840
						'pending_details' => $pending_details,
841
					)
842
				);
843
			}
844
		}
845
846
		$context['sub_template'] = 'paid_done';
847
		return;
848
	}
849
	// If this is confirmation then it's simpler...
850
	if (isset($_GET['confirm']) && isset($_POST['sub_id']) && is_array($_POST['sub_id']))
851
	{
852
		// Hopefully just one.
853
		foreach ($_POST['sub_id'] as $k => $v)
854
			$ID_SUB = (int) $k;
855
856
		if (!isset($context['subscriptions'][$ID_SUB]) || $context['subscriptions'][$ID_SUB]['active'] == 0)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $ID_SUB seems to be defined by a foreach iteration on line 853. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
857
			fatal_lang_error('paid_sub_not_active');
858
859
		// Simplify...
860
		$context['sub'] = $context['subscriptions'][$ID_SUB];
861
		$period = 'xx';
862
		if ($context['sub']['flexible'])
863
			$period = isset($_POST['cur'][$ID_SUB]) && isset($context['sub']['costs'][$_POST['cur'][$ID_SUB]]) ? $_POST['cur'][$ID_SUB] : 'xx';
864
865
		// Check we have a valid cost.
866
		if ($context['sub']['flexible'] && $period == 'xx')
867
			fatal_lang_error('paid_sub_not_active');
868
869
		// Sort out the cost/currency.
870
		$context['currency'] = $modSettings['paid_currency_code'];
871
		$context['recur'] = $context['sub']['repeatable'];
872
873
		if ($context['sub']['flexible'])
874
		{
875
			// Real cost...
876
			$context['value'] = $context['sub']['costs'][$_POST['cur'][$ID_SUB]];
877
			$context['cost'] = sprintf($modSettings['paid_currency_symbol'], $context['value']) . '/' . $txt[$_POST['cur'][$ID_SUB]];
878
			// The period value for paypal.
879
			$context['paypal_period'] = strtoupper(substr($_POST['cur'][$ID_SUB], 0, 1));
880
		}
881
		else
882
		{
883
			// Real cost...
884
			$context['value'] = $context['sub']['costs']['fixed'];
885
			$context['cost'] = sprintf($modSettings['paid_currency_symbol'], $context['value']);
886
887
			// Recur?
888
			preg_match('~(\d*)(\w)~', $context['sub']['real_length'], $match);
889
			$context['paypal_unit'] = $match[1];
890
			$context['paypal_period'] = $match[2];
891
		}
892
893
		// Setup the gateway context.
894
		$context['gateways'] = array();
895
		foreach ($gateways as $id => $gateway)
896
		{
897
			$fields = $gateways[$id]->fetchGatewayFields($context['sub']['id'] . '+' . $memID, $context['sub'], $context['value'], $period, $scripturl . '?action=profile&u=' . $memID . '&area=subscriptions&sub_id=' . $context['sub']['id'] . '&done');
898
			if (!empty($fields['form']))
899
				$context['gateways'][] = $fields;
900
		}
901
902
		// Bugger?!
903
		if (empty($context['gateways']))
904
			fatal_error($txt['paid_admin_not_setup_gateway']);
905
906
		// Now we are going to assume they want to take this out ;)
907
		$new_data = array($context['sub']['id'], $context['value'], $period, 'prepay');
908
		if (isset($context['current'][$context['sub']['id']]))
909
		{
910
			// What are the details like?
911
			$current_pending = array();
912
			if ($context['current'][$context['sub']['id']]['pending_details'] != '')
913
				$current_pending = $smcFunc['json_decode']($context['current'][$context['sub']['id']]['pending_details'], true);
914
			// Don't get silly.
915
			if (count($current_pending) > 9)
916
				$current_pending = array();
917
			$pending_count = 0;
918
			// Only record real pending payments as will otherwise confuse the admin!
919
			foreach ($current_pending as $pending)
920
				if ($pending[3] == 'payback')
921
					$pending_count++;
922
923
			if (!in_array($new_data, $current_pending))
924
			{
925
				$current_pending[] = $new_data;
926
				$pending_details = $smcFunc['json_encode']($current_pending);
927
928
				$smcFunc['db_query']('', '
929
					UPDATE {db_prefix}log_subscribed
930
					SET payments_pending = {int:pending_count}, pending_details = {string:pending_details}
931
					WHERE id_sublog = {int:current_subscription_item}
932
						AND id_member = {int:selected_member}',
933
					array(
934
						'pending_count' => $pending_count,
935
						'current_subscription_item' => $context['current'][$context['sub']['id']]['id'],
936
						'selected_member' => $memID,
937
						'pending_details' => $pending_details,
938
					)
939
				);
940
			}
941
		}
942
		// Never had this before, lovely.
943
		else
944
		{
945
			$pending_details = $smcFunc['json_encode'](array($new_data));
946
			$smcFunc['db_insert']('',
947
				'{db_prefix}log_subscribed',
948
				array(
949
					'id_subscribe' => 'int', 'id_member' => 'int', 'status' => 'int', 'payments_pending' => 'int', 'pending_details' => 'string-65534',
950
					'start_time' => 'int', 'vendor_ref' => 'string-255',
951
				),
952
				array(
953
					$context['sub']['id'], $memID, 0, 0, $pending_details,
954
					time(), '',
955
				),
956
				array('id_sublog')
957
			);
958
		}
959
960
		// Change the template.
961
		$context['sub_template'] = 'choose_payment';
962
963
		// Quit.
964
		return;
965
	}
966
	else
967
		$context['sub_template'] = 'user_subscription';
968
}
969
970
/**
971
 * Exports a member's profile, posts, and personal messages to a file.
972
 *
973
 * @todo Add HTML, CSV, JSON as other possible export formats besides XML?
974
 *
975
 * @param int $memID The ID of the member whose data we're exporting.
976
 */
977
function export_profile_data($memID)
978
{
979
	global $context, $smcFunc, $txt, $modSettings, $sourcedir, $scripturl;
980
	global $query_this_board;
981
982
	if (!isset($context['token_check']))
983
		$context['token_check'] = 'profile-ex' . $memID;
984
985
	$context['export_formats'] = get_export_formats();
986
987
	// This lists the types of data we can export and info for doing so.
988
	$context['export_datatypes'] = array(
989
		'profile' => array(
990
			'label' => $txt['export_include_profile'],
991
			'total' => 1,
992
			'latest' => 1,
993
			// Instructions to pass to ExportProfileData background task:
994
			'XML' => array(
995
				'func' => 'getXmlProfile',
996
				'langfile' => 'Profile',
997
			),
998
		),
999
		'posts' => array(
1000
			'label' => $txt['export_include_posts'],
1001
			'total' => $context['member']['real_posts'],
1002
			'latest' => function($memID)
1003
			{
1004
				global $smcFunc, $modSettings;
1005
1006
				static $latest_post;
1007
1008
				if (isset($latest_post))
1009
					return $latest_post;
1010
1011
				$query_this_board = !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? 'b.id_board != ' . $modSettings['recycle_board'] : '1=1';
1012
1013
				$request = $smcFunc['db_query']('', '
1014
					SELECT m.id_msg
1015
					FROM {db_prefix}messages as m
1016
						INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
1017
					WHERE id_member = {int:uid}
1018
						AND ' . $query_this_board . '
1019
					ORDER BY id_msg DESC
1020
					LIMIT {int:limit}',
1021
					array(
1022
						'limit' => 1,
1023
						'uid' => $memID,
1024
					)
1025
				);
1026
				list($latest_post) = $smcFunc['db_fetch_row']($request);
1027
				$smcFunc['db_free_result']($request);
1028
1029
				return $latest_post;
1030
			},
1031
			// Instructions to pass to ExportProfileData background task:
1032
			'XML' => array(
1033
				'func' => 'getXmlPosts',
1034
				'langfile' => 'Post',
1035
			),
1036
		),
1037
		'personal_messages' => array(
1038
			'label' => $txt['export_include_personal_messages'],
1039
			'total' => function($memID)
1040
			{
1041
				global $smcFunc;
1042
1043
				static $total_pms;
1044
1045
				if (isset($total_pms))
1046
					return $total_pms;
1047
1048
				$request = $smcFunc['db_query']('', '
1049
					SELECT COUNT(*)
1050
					FROM {db_prefix}personal_messages AS pm
1051
						INNER JOIN {db_prefix}pm_recipients AS pmr ON (pm.id_pm = pmr.id_pm)
1052
					WHERE (pm.id_member_from = {int:uid} AND pm.deleted_by_sender = {int:not_deleted})
1053
						OR (pmr.id_member = {int:uid} AND pmr.deleted = {int:not_deleted})',
1054
					array(
1055
						'uid' => $memID,
1056
						'not_deleted' => 0,
1057
					)
1058
				);
1059
				list($total_pms) = $smcFunc['db_fetch_row']($request);
1060
				$smcFunc['db_free_result']($request);
1061
1062
				return $total_pms;
1063
			},
1064
			'latest' => function($memID)
1065
			{
1066
				global $smcFunc;
1067
1068
				static $latest_pm;
1069
1070
				if (isset($latest_pm))
1071
					return $latest_pm;
1072
1073
				$request = $smcFunc['db_query']('', '
1074
					SELECT pm.id_pm
1075
					FROM {db_prefix}personal_messages AS pm
1076
						INNER JOIN {db_prefix}pm_recipients AS pmr ON (pm.id_pm = pmr.id_pm)
1077
					WHERE (pm.id_member_from = {int:uid} AND pm.deleted_by_sender = {int:not_deleted})
1078
						OR (pmr.id_member = {int:uid} AND pmr.deleted = {int:not_deleted})
1079
					ORDER BY pm.id_pm DESC
1080
					LIMIT {int:limit}',
1081
					array(
1082
						'limit' => 1,
1083
						'uid' => $memID,
1084
						'not_deleted' => 0,
1085
					)
1086
				);
1087
				list($latest_pm) = $smcFunc['db_fetch_row']($request);
1088
				$smcFunc['db_free_result']($request);
1089
1090
				return $latest_pm;
1091
			},
1092
			// Instructions to pass to ExportProfileData background task:
1093
			'XML' => array(
1094
				'func' => 'getXmlPMs',
1095
				'langfile' => 'PersonalMessage',
1096
			),
1097
		),
1098
	);
1099
1100
	if (empty($modSettings['export_dir']) || !file_exists($modSettings['export_dir']))
1101
		create_export_dir();
1102
1103
	$export_dir_slash = $modSettings['export_dir'] . DIRECTORY_SEPARATOR;
1104
1105
	$idhash = hash_hmac('sha1', $memID, get_auth_secret());
1106
	$dltoken = hash_hmac('sha1', $idhash, get_auth_secret());
1107
1108
	$query_this_board = !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? 'b.id_board != ' . $modSettings['recycle_board'] : '1=1';
1109
1110
	$context['completed_exports'] = array();
1111
	$context['active_exports'] = array();
1112
	$latest = array();
1113
1114
	foreach ($context['export_formats'] as $format => $format_settings)
1115
	{
1116
		$done = null;
1117
1118
		$idhash_ext = $idhash . '.' . $format_settings['extension'];
1119
1120
		// $realfile needs to be the highest numbered one, or 1_*** if none exist.
1121
		$filenum = 1;
1122
		$realfile = $export_dir_slash . $filenum . '_' . $idhash_ext;
1123
		while (file_exists($export_dir_slash . ($filenum + 1) . '_' . $idhash_ext))
1124
			$realfile = $export_dir_slash . ++$filenum . '_' . $idhash_ext;
1125
1126
		$tempfile = $export_dir_slash . $idhash_ext . '.tmp';
1127
		$progressfile = $export_dir_slash . $idhash_ext . '.progress.json';
1128
1129
		// If requested by the user, delete any existing export files and background tasks.
1130
		if (isset($_POST['delete']) && isset($_POST['format']) && $_POST['format'] === $format && isset($_POST['t']) && $_POST['t'] === $dltoken)
1131
		{
1132
			$smcFunc['db_query']('', '
1133
				DELETE FROM {db_prefix}background_tasks
1134
				WHERE task_class = {string:class}
1135
					AND task_data LIKE {string:details}',
1136
				array(
1137
					'class' => 'ExportProfileData_Background',
1138
					'details' => substr($smcFunc['json_encode'](array('format' => $format, 'uid' => $memID)), 0, -1) . ',%',
1139
				)
1140
			);
1141
1142
			foreach (array_merge(array($tempfile, $progressfile), glob($export_dir_slash . '*_' . $idhash_ext)) as $fpath)
1143
				@unlink($fpath);
1144
1145
			if (empty($_POST['export_begin']))
1146
				redirectexit('action=profile;area=getprofiledata;u=' . $memID);
1147
		}
1148
1149
		$progress = file_exists($progressfile) ? $smcFunc['json_decode'](file_get_contents($progressfile), true) : array();
1150
1151
		if (!empty($progress))
1152
			$included = array_keys($progress);
1153
		else
1154
			$included = array_intersect(array_keys($context['export_datatypes']), array_keys($_POST));
1155
1156
		// If we're starting a new export in this format, we're done here.
1157
		if (!empty($_POST['export_begin']) && $_POST['format'] === $format)
1158
			break;
1159
1160
		// The rest of this loop deals with current exports, if any.
1161
1162
		$included_desc = array();
1163
		foreach ($included as $datatype)
1164
			$included_desc[] = $txt[$datatype];
1165
1166
		$dlfilename = array_merge(array($context['forum_name'], $context['member']['username']), $included_desc);
1167
		$dlfilename = preg_replace('/[^\p{L}\p{M}\p{N}_]+/u', '-', str_replace('"', '', un_htmlspecialchars(strip_tags(implode('_', $dlfilename)))));
1168
1169
		if (file_exists($tempfile) && file_exists($progressfile))
1170
		{
1171
			$done = false;
1172
		}
1173
		elseif (file_exists($realfile))
1174
		{
1175
			// It looks like we're done.
1176
			$done = true;
1177
1178
			// But let's check whether any recently created content should be added.
1179
			foreach ($context['export_datatypes'] as $datatype => $datatype_settings)
1180
			{
1181
				if (!isset($progress[$datatype]))
1182
					continue;
1183
1184
				if (!isset($latest[$datatype]))
1185
					$latest[$datatype] = is_callable($datatype_settings['latest']) ? $datatype_settings['latest']($memID) : $datatype_settings['latest'];
1186
1187
				if ($latest[$datatype] > $progress[$datatype])
1188
				{
1189
					$done = false;
1190
					$_POST[$datatype] = true;
1191
					$start[$datatype] = $progress[$datatype];
1192
1193
					if (!isset($current_datatype))
1194
						$current_datatype = $datatype;
1195
				}
1196
			}
1197
			if ($done === false)
1198
			{
1199
				$_POST['export_begin'] = true;
1200
				$_POST['format'] = $format;
1201
				createToken('profile-ex' . $memID, 'post');
1202
1203
				@unlink($tempfile);
1204
				rename($realfile, $tempfile);
1205
			}
1206
		}
1207
1208
		if ($done === true)
1209
		{
1210
			$exportfilepaths = glob($export_dir_slash . '*_' . $idhash_ext);
1211
1212
			foreach ($exportfilepaths as $exportfilepath)
1213
			{
1214
				$exportbasename = basename($exportfilepath);
1215
1216
				$part = substr($exportbasename, 0, strcspn($exportbasename, '_'));
1217
				$suffix = count($exportfilepaths) == 1 ? '' : '_' . $part;
1218
1219
				$size = filesize($exportfilepath) / 1024;
1220
				$units = array('KB', 'MB', 'GB', 'TB');
1221
				$unitkey = 0;
1222
				while ($size > 1024)
1223
				{
1224
					$size = $size / 1024;
1225
					$unitkey++;
1226
				}
1227
				$size = round($size, 2) . $units[$unitkey];
1228
1229
				$context['completed_exports'][$idhash_ext][$part] = array(
1230
					'realname' => $exportbasename,
1231
					'dlbasename' => $dlfilename . $suffix . '.' . $format_settings['extension'],
1232
					'dltoken' => $dltoken,
1233
					'included' => sentence_list($included_desc),
1234
					'format' => $format,
1235
					'mtime' => timeformat(filemtime($exportfilepath)),
1236
					'size' => $size,
1237
				);
1238
			}
1239
1240
			ksort($context['completed_exports'][$idhash_ext], SORT_NUMERIC);
1241
		}
1242
		elseif ($done === false)
1243
		{
1244
			$context['active_exports'][$idhash_ext] = array(
1245
				'dltoken' => $dltoken,
1246
				'included' => sentence_list($included_desc),
1247
				'format' => $format,
1248
			);
1249
		}
1250
	}
1251
1252
	if (isset($_POST['export_begin']))
1253
	{
1254
		checkSession();
1255
		validateToken($context['token_check'], 'post');
1256
1257
		$format = isset($_POST['format']) ? $_POST['format'] : 'XML';
1258
1259
		$included = array();
1260
		foreach ($context['export_datatypes'] as $datatype => $datatype_settings)
1261
		{
1262
			if (!empty($_POST[$datatype]))
1263
			{
1264
				$included[$datatype] = $datatype_settings[$format];
1265
				$start[$datatype] = !empty($start[$datatype]) ? $start[$datatype] : 0;
1266
1267
				if (!isset($latest[$datatype]))
1268
					$latest[$datatype] = is_callable($datatype_settings['latest']) ? $datatype_settings['latest']($memID) : $datatype_settings['latest'];
1269
			}
1270
		}
1271
1272
		if (empty($included))
1273
			unset($context['active_exports'][$idhash . '.' . $context['export_formats'][$format]['extension']]);
1274
		else
1275
		{
1276
			$data = $smcFunc['json_encode'](array(
1277
				'format' => $format,
1278
				'uid' => $memID,
1279
				'lang' => $context['member']['language'],
1280
				'included' => $included,
1281
				'start' => $start,
1282
				'latest' => $latest,
1283
				'datatype' => isset($current_datatype) ? $current_datatype : key($included),
1284
			));
1285
1286
			$smcFunc['db_insert']('insert', '{db_prefix}background_tasks',
1287
				array('task_file' => 'string-255', 'task_class' => 'string-255', 'task_data' => 'string', 'claimed_time' => 'int'),
1288
				array('$sourcedir/tasks/ExportProfileData.php', 'ExportProfileData_Background', $data, 0),
1289
				array()
1290
			);
1291
1292
			// So the user can see that we've started.
1293
			if (!file_exists($realfile) && !file_exists($tempfile) && !file_exists($progressfile))
1294
			{
1295
				require_once($sourcedir . '/News.php');
1296
1297
				$desc = array();
1298
				foreach (array_keys($included) as $datatype)
1299
					$desc[] = $txt[$datatype];
1300
1301
				$feed_meta = array(
1302
					'title' => sprintf($txt['profile_of_username'], $context['member']['username']),
1303
					'desc' => sentence_list($desc),
1304
					'author' => $context['forum_name'],
1305
					'source' => $scripturl . '?action=profile;u=' . $memID,
1306
					'self' => $scripturl . '?action=profile;area=download;u=' . $memID . ';t=' . $dltoken,
1307
				);
1308
1309
				buildXmlFeed('smf', array(), $feed_meta, 'profile');
1310
				file_put_contents($tempfile, implode('', array($context['feed']['header'], $context['feed']['footer'])));
1311
1312
				file_put_contents($progressfile, $smcFunc['json_encode'](array_fill_keys(array_keys($included), 0)));
1313
			}
1314
1315
			redirectexit('action=profile;area=getprofiledata;u=' . $memID);
1316
		}
1317
	}
1318
1319
	createToken($context['token_check'], 'post');
1320
1321
	$context['page_title'] = $txt['export_profile_data'];
1322
1323
	if (empty($modSettings['export_expiry']))
1324
		unset($txt['export_profile_data_desc_list']['expiry']);
1325
	else
1326
		$txt['export_profile_data_desc_list']['expiry'] = sprintf($txt['export_profile_data_desc_list']['expiry'], $modSettings['export_expiry']);
1327
1328
	$context['export_profile_data_desc'] = sprintf($txt['export_profile_data_desc'], '<li>' . implode('</li><li>', $txt['export_profile_data_desc_list']) . '</li>');
1329
}
1330
1331
/**
1332
 * Downloads exported profile data file.
1333
 */
1334
function download_export_file($memID)
1335
{
1336
	global $modSettings, $maintenance, $context, $txt, $smcFunc;
1337
1338
	$export_formats = get_export_formats();
1339
1340
	// This is done to clear any output that was made before now.
1341
	ob_end_clean();
1342
1343
	if (!empty($modSettings['enableCompressedOutput']) && !headers_sent() && ob_get_length() == 0)
1344
	{
1345
		if (@ini_get('zlib.output_compression') == '1' || @ini_get('output_handler') == 'ob_gzhandler')
1346
			$modSettings['enableCompressedOutput'] = 0;
1347
1348
		else
1349
			ob_start('ob_gzhandler');
1350
	}
1351
1352
	if (empty($modSettings['enableCompressedOutput']))
1353
	{
1354
		ob_start();
1355
		header('content-encoding: none');
1356
	}
1357
1358
	// No access in strict maintenance mode.
1359
	if (!empty($maintenance) && $maintenance == 2)
1360
	{
1361
		send_http_status(404);
1362
		exit;
1363
	}
1364
1365
	// We can't give them anything without these.
1366
	if (empty($_GET['t']) || empty($_GET['format']) || !isset($export_formats[$_GET['format']]))
1367
	{
1368
		send_http_status(400);
1369
		exit;
1370
	}
1371
1372
	$export_dir_slash = $modSettings['export_dir'] . DIRECTORY_SEPARATOR;
1373
1374
	$idhash = hash_hmac('sha1', $memID, get_auth_secret());
1375
	$part = isset($_GET['part']) ? (int) $_GET['part'] : 1;
1376
	$extension = $export_formats[$_GET['format']]['extension'];
1377
1378
	$filepath = $export_dir_slash . $part . '_' . $idhash . '.' . $extension;
1379
	$progressfile = $export_dir_slash . $idhash . '.' . $extension . '.progress.json';
1380
1381
	// Make sure they gave the correct authentication token.
1382
	// We use these tokens so the user can download without logging in, as required by the GDPR.
1383
	$dltoken = hash_hmac('sha1', $idhash, get_auth_secret());
1384
	if ($_GET['t'] !== $dltoken)
1385
	{
1386
		send_http_status(403);
1387
		exit;
1388
	}
1389
1390
	// Obviously we can't give what we don't have.
1391
	if (empty($modSettings['export_dir']) || !file_exists($filepath))
1392
	{
1393
		send_http_status(404);
1394
		exit;
1395
	}
1396
1397
	// Figure out the filename we'll tell the browser.
1398
	$datatypes = file_exists($progressfile) ? array_keys($smcFunc['json_decode'](file_get_contents($progressfile), true)) : array('profile');
1399
	$included_desc = array_map(function ($datatype) use ($txt) { return $txt[$datatype]; }, $datatypes);
1400
1401
	$dlfilename = array_merge(array($context['forum_name'], $context['member']['username']), $included_desc);
1402
	$dlfilename = preg_replace('/[^\p{L}\p{M}\p{N}_]+/u', '-', str_replace('"', '', un_htmlspecialchars(strip_tags(implode('_', $dlfilename)))));
1403
1404
	$suffix = ($part > 1 || file_exists($export_dir_slash . '2_' . $idhash . '.' . $extension)) ? '_' . $part : '';
1405
1406
	$dlbasename = $dlfilename . $suffix . '.' . $extension;
1407
1408
	$mtime = filemtime($filepath);
1409
	$size = filesize($filepath);
1410
1411
	// If it hasn't been modified since the last time it was retrieved, there's no need to serve it again.
1412
	if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']))
1413
	{
1414
		list($modified_since) = explode(';', $_SERVER['HTTP_IF_MODIFIED_SINCE']);
1415
		if (strtotime($modified_since) >= $mtime)
1416
		{
1417
			ob_end_clean();
1418
1419
			// Answer the question - no, it hasn't been modified ;).
1420
			send_http_status(304);
1421
			exit;
1422
		}
1423
	}
1424
1425
	// Check whether the ETag was sent back, and cache based on that...
1426
	$eTag = md5(implode(' ', array($dlbasename, $size, $mtime)));
1427
	if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) && strpos($_SERVER['HTTP_IF_NONE_MATCH'], $eTag) !== false)
1428
	{
1429
		ob_end_clean();
1430
1431
		send_http_status(304);
1432
		exit;
1433
	}
1434
1435
	// If this is a partial download, we need to determine what data range to send
1436
	$range = 0;
1437
	if (isset($_SERVER['HTTP_RANGE']))
1438
	{
1439
		list($a, $range) = explode("=", $_SERVER['HTTP_RANGE'], 2);
1440
		list($range) = explode(",", $range, 2);
1441
		list($range, $range_end) = explode("-", $range);
1442
		$range = intval($range);
1443
		$range_end = !$range_end ? $size - 1 : intval($range_end);
1444
		$new_length = $range_end - $range + 1;
1445
	}
1446
1447
	header('pragma: ');
1448
1449
	if (!isBrowser('gecko'))
1450
		header('content-transfer-encoding: binary');
1451
1452
	header('expires: ' . gmdate('D, d M Y H:i:s', time() + 525600 * 60) . ' GMT');
1453
	header('last-modified: ' . gmdate('D, d M Y H:i:s', $mtime) . ' GMT');
1454
	header('accept-ranges: bytes');
1455
	header('connection: close');
1456
	header('etag: ' . $eTag);
1457
	header('content-type: ' . $export_formats[$_GET['format']]['mime']);
1458
1459
	// Convert the file to UTF-8, cuz most browsers dig that.
1460
	$utf8name = !$context['utf8'] && function_exists('iconv') ? iconv($context['character_set'], 'UTF-8', $dlbasename) : (!$context['utf8'] && function_exists('mb_convert_encoding') ? mb_convert_encoding($dlbasename, 'UTF-8', $context['character_set']) : $dlbasename);
1461
1462
	// Different browsers like different standards...
1463
	if (isBrowser('firefox'))
1464
		header('content-disposition: attachment; filename*=UTF-8\'\'' . rawurlencode(preg_replace_callback('~&#(\d{3,8});~', 'fixchar__callback', $utf8name)));
1465
1466
	elseif (isBrowser('opera'))
1467
		header('content-disposition: attachment; filename="' . preg_replace_callback('~&#(\d{3,8});~', 'fixchar__callback', $utf8name) . '"');
1468
1469
	elseif (isBrowser('ie'))
1470
		header('content-disposition: attachment; filename="' . urlencode(preg_replace_callback('~&#(\d{3,8});~', 'fixchar__callback', $utf8name)) . '"');
1471
1472
	else
1473
		header('content-disposition: attachment; filename="' . $utf8name . '"');
1474
1475
	header('cache-control: max-age=' . (525600 * 60) . ', private');
1476
1477
	// Multipart and resuming support
1478
	if (isset($_SERVER['HTTP_RANGE']))
1479
	{
1480
		send_http_status(206);
1481
		header("content-length: $new_length");
1482
		header("content-range: bytes $range-$range_end/$size");
1483
	}
1484
	else
1485
		header("content-length: $size");
1486
1487
	// Try to buy some time...
1488
	@set_time_limit(600);
1489
1490
	// For multipart/resumable downloads, send the requested chunk(s) of the file
1491
	if (isset($_SERVER['HTTP_RANGE']))
1492
	{
1493
		while (@ob_get_level() > 0)
1494
			@ob_end_clean();
1495
1496
		// 40 kilobytes is a good-ish amount
1497
		$chunksize = 40 * 1024;
1498
		$bytes_sent = 0;
1499
1500
		$fp = fopen($filepath, 'rb');
1501
1502
		fseek($fp, $range);
1503
1504
		while (!feof($fp) && (!connection_aborted()) && ($bytes_sent < $new_length))
1505
		{
1506
			$buffer = fread($fp, $chunksize);
1507
			echo($buffer);
1508
			flush();
1509
			$bytes_sent += strlen($buffer);
1510
		}
1511
		fclose($fp);
1512
	}
1513
1514
	// Since we don't do output compression for files this large...
1515
	elseif ($size > 4194304)
1516
	{
1517
		// Forcibly end any output buffering going on.
1518
		while (@ob_get_level() > 0)
1519
			@ob_end_clean();
1520
1521
		$fp = fopen($filepath, 'rb');
1522
		while (!feof($fp))
1523
		{
1524
			echo fread($fp, 8192);
1525
			flush();
1526
		}
1527
		fclose($fp);
1528
	}
1529
1530
	// On some of the less-bright hosts, readfile() is disabled.  It's just a faster, more byte safe, version of what's in the if.
1531
	elseif (@readfile($filepath) === null)
1532
		echo file_get_contents($filepath);
1533
1534
	exit;
1535
}
1536
1537
/**
1538
 * Helper function that defines data export formats in a single location.
1539
 *
1540
 * @return array Information about supported data formats for profile exports.
1541
 */
1542
function get_export_formats()
1543
{
1544
	return array(
1545
		'XML' => array('extension' => 'xml', 'mime' => 'application/xml'),
1546
		// 'HTML' => array('extension' => 'html', 'mime' => 'text/html'),
1547
		// 'CSV' => array('extension' => 'csv', 'mime' => 'text/csv'),
1548
		// 'JSON' => array('extension' => 'json', 'mime' => 'application/json'),
1549
	);
1550
}
1551
1552
/**
1553
 * Returns the path to a secure directory for storing exported profile data.
1554
 *
1555
 * The directory is created if it does not yet exist, and is secured using the
1556
 * same method that we use to secure attachment directories. Files in this
1557
 * directory can only be downloaded via the download_export_file() function.
1558
 *
1559
 * @return string|bool The path to the directory, or false on error.
1560
 */
1561
function create_export_dir($fallback = '')
1562
{
1563
	global $boarddir, $modSettings;
1564
1565
	// No supplied fallback, so use the default location.
1566
	if (empty($fallback))
1567
		$fallback = $boarddir . DIRECTORY_SEPARATOR . 'exports';
1568
1569
	// Automatically set it to the fallback if it is missing.
1570
	if (empty($modSettings['export_dir']))
1571
		updateSettings(array('export_dir' => $fallback));
1572
1573
	// Make sure the directory exists.
1574
	if (!file_exists($modSettings['export_dir']))
1575
		@mkdir($modSettings['export_dir'], null, true);
1576
1577
	// Make sure the directory has the correct permissions.
1578
	if (!is_dir($modSettings['export_dir']) || !smf_chmod($modSettings['export_dir']))
1579
	{
1580
		loadLanguage('Errors');
1581
1582
		// Try again at the fallback location.
1583
		if ($modSettings['export_dir'] != $fallback)
1584
		{
1585
			log_error($txt['export_dir_forced_change'], $modSettings['export_dir'], $fallback);
1586
			updateSettings(array('export_dir' => $fallback));
1587
1588
			// Secondary fallback will be the default location, so no parameter this time.
1589
			create_export_dir();
1590
		}
1591
		// Uh-oh. Even the default location failed.
1592
		else
1593
		{
1594
			log_error($txt['export_dir_not_writable']);
1595
			return false;
1596
		}
1597
	}
1598
1599
	return secureDirectory(array($modSettings['export_dir']), true);
1600
}
1601
1602
?>