Issues (1065)

Sources/Subs-Auth.php (1 issue)

1
<?php
2
3
/**
4
 * This file has functions in it to do with authentication, user handling, and the like.
5
 *
6
 * Simple Machines Forum (SMF)
7
 *
8
 * @package SMF
9
 * @author Simple Machines https://www.simplemachines.org
10
 * @copyright 2025 Simple Machines and individual contributors
11
 * @license https://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1.5
14
 */
15
16
if (!defined('SMF'))
17
	die('No direct access...');
18
19
/**
20
 * Sets the SMF-style login cookie and session based on the id_member and password passed.
21
 * - password should be already encrypted with the cookie salt.
22
 * - logs the user out if id_member is zero.
23
 * - sets the cookie and session to last the number of seconds specified by cookie_length, or
24
 *   ends them if cookie_length is less than 0.
25
 * - when logging out, if the globalCookies setting is enabled, attempts to clear the subdomain's
26
 *   cookie too.
27
 *
28
 * @param int $cookie_length How many seconds the cookie should last. If negative, forces logout.
29
 * @param int $id The ID of the member to set the cookie for
30
 * @param string $password The hashed password
31
 */
32
function setLoginCookie($cookie_length, $id, $password = '')
33
{
34
	global $smcFunc, $cookiename, $boardurl, $modSettings, $sourcedir;
35
36
	$id = (int) $id;
37
38
	$expiry_time = ($cookie_length >= 0 ? time() + $cookie_length : 1);
39
40
	// If changing state force them to re-address some permission caching.
41
	$_SESSION['mc']['time'] = 0;
42
43
	// Extract our cookie domain and path from $boardurl
44
	$cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
45
46
	// The cookie may already exist, and have been set with different options.
47
	if (isset($_COOKIE[$cookiename]))
48
	{
49
		// First check for 2.1 json-format cookie
50
		if (preg_match('~^{"0":\d+,"1":"[0-9a-f]*","2":\d+,"3":"[^"]+","4":"[^"]+"~', $_COOKIE[$cookiename]) === 1)
51
			list(,,, $old_domain, $old_path) = $smcFunc['json_decode']($_COOKIE[$cookiename], true);
52
53
		// Legacy format (for recent 2.0 --> 2.1 upgrades)
54
		elseif (preg_match('~^a:[34]:\{i:0;i:\d+;i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\d+;(i:3;i:\d;)?~', $_COOKIE[$cookiename]) === 1)
55
		{
56
			list(,,, $old_state) = safe_unserialize($_COOKIE[$cookiename]);
57
58
			$cookie_state = (empty($modSettings['localCookies']) ? 0 : 1) | (empty($modSettings['globalCookies']) ? 0 : 2);
59
60
			// Maybe we need to temporarily pretend to be using local cookies
61
			if ($cookie_state == 0 && $old_state == 1)
62
				list($old_domain, $old_path) = url_parts(true, false);
63
			else
64
				list($old_domain, $old_path) = url_parts($old_state & 1 > 0, $old_state & 2 > 0);
65
		}
66
67
		// Out with the old, in with the new!
68
		if (isset($old_domain) && $old_domain != $cookie_url[0] || isset($old_path) && $old_path != $cookie_url[1])
69
			smf_setcookie($cookiename, $smcFunc['json_encode'](array(0, '', 0, $old_domain, $old_path), JSON_FORCE_OBJECT), 1, $old_path, $old_domain);
70
	}
71
72
	// Get the data and path to set it on.
73
	$data = empty($id) ? array(0, '', 0, $cookie_url[0], $cookie_url[1]) : array($id, $password, $expiry_time, $cookie_url[0], $cookie_url[1]);
74
75
	// Allow mods to add custom info to the cookie
76
	$custom_data = array();
77
	call_integration_hook('integrate_cookie_data', array($data, &$custom_data));
78
79
	$data = $smcFunc['json_encode'](array_merge($data, $custom_data), JSON_FORCE_OBJECT);
80
81
	// Set the cookie, $_COOKIE, and session variable.
82
	smf_setcookie($cookiename, $data, $expiry_time, $cookie_url[1], $cookie_url[0]);
83
84
	// If subdomain-independent cookies are on, unset the subdomain-dependent cookie too.
85
	if (empty($id) && !empty($modSettings['globalCookies']))
86
		smf_setcookie($cookiename, $data, $expiry_time, $cookie_url[1], '');
87
88
	// Any alias URLs?  This is mainly for use with frames, etc.
89
	if (!empty($modSettings['forum_alias_urls']))
90
	{
91
		$aliases = explode(',', $modSettings['forum_alias_urls']);
92
93
		$temp = $boardurl;
94
		foreach ($aliases as $alias)
95
		{
96
			// Fake the $boardurl so we can set a different cookie.
97
			$alias = strtr(trim($alias), array('http://' => '', 'https://' => ''));
98
			$boardurl = 'http://' . $alias;
99
100
			$cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
101
102
			if ($cookie_url[0] == '')
103
				$cookie_url[0] = strtok($alias, '/');
104
105
			$alias_data = $smcFunc['json_decode']($data, true);
106
			$alias_data[3] = $cookie_url[0];
107
			$alias_data[4] = $cookie_url[1];
108
			$alias_data = $smcFunc['json_encode']($alias_data, JSON_FORCE_OBJECT);
109
110
			smf_setcookie($cookiename, $alias_data, $expiry_time, $cookie_url[1], $cookie_url[0]);
111
		}
112
113
		$boardurl = $temp;
114
	}
115
116
	$_COOKIE[$cookiename] = $data;
117
118
	// Make sure the user logs in with a new session ID.
119
	if (!isset($_SESSION['login_' . $cookiename]) || $_SESSION['login_' . $cookiename] !== $data)
120
	{
121
		// We need to meddle with the session.
122
		require_once($sourcedir . '/Session.php');
123
124
		// Backup and remove the old session.
125
		$oldSessionData = $_SESSION;
126
		$_SESSION = array();
127
		session_destroy();
128
129
		// Recreate and restore the new session.
130
		loadSession();
131
		// @todo should we use session_regenerate_id(true); now that we are 5.1+
132
		session_regenerate_id();
133
		$_SESSION = $oldSessionData;
134
135
		$_SESSION['login_' . $cookiename] = $data;
136
	}
137
}
138
139
/**
140
 * Sets Two Factor Auth cookie
141
 *
142
 * @param int $cookie_length How long the cookie should last, in seconds
143
 * @param int $id The ID of the member
144
 * @param string $secret Should be a salted secret using hash_salt
145
 */
146
function setTFACookie($cookie_length, $id, $secret)
147
{
148
	global $smcFunc, $modSettings, $cookiename;
149
150
	$expiry_time = ($cookie_length >= 0 ? time() + $cookie_length : 1);
151
152
	$identifier = $cookiename . '_tfa';
153
	$cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
154
155
	// Get the data and path to set it on.
156
	$data = $smcFunc['json_encode'](empty($id) ? array(0, '', 0, $cookie_url[0], $cookie_url[1], false) : array($id, $secret, $expiry_time, $cookie_url[0], $cookie_url[1]), JSON_FORCE_OBJECT);
157
158
	// Set the cookie, $_COOKIE, and session variable.
159
	smf_setcookie($identifier, $data, $expiry_time, $cookie_url[1], $cookie_url[0]);
160
161
	// If subdomain-independent cookies are on, unset the subdomain-dependent cookie too.
162
	if (empty($id) && !empty($modSettings['globalCookies']))
163
		smf_setcookie($identifier, $data, $expiry_time, $cookie_url[1], '');
164
165
	$_COOKIE[$identifier] = $data;
166
}
167
168
/**
169
 * Get the domain and path for the cookie
170
 * - normally, local and global should be the localCookies and globalCookies settings, respectively.
171
 * - uses boardurl to determine these two things.
172
 *
173
 * @param bool $local Whether we want local cookies
174
 * @param bool $global Whether we want global cookies
175
 * @return array An array to set the cookie on with domain and path in it, in that order
176
 */
177
function url_parts($local, $global)
178
{
179
	global $boardurl, $modSettings;
180
181
	// Parse the URL with PHP to make life easier.
182
	$parsed_url = parse_iri($boardurl);
183
184
	// Is local cookies off?
185
	if (empty($parsed_url['path']) || !$local)
186
		$parsed_url['path'] = '';
187
188
	if (!empty($modSettings['globalCookiesDomain']) && strpos($boardurl, $modSettings['globalCookiesDomain']) !== false)
189
		$parsed_url['host'] = $modSettings['globalCookiesDomain'];
190
191
	// Globalize cookies across domains (filter out IP-addresses)?
192
	elseif ($global && preg_match('~^\d{1,3}(\.\d{1,3}){3}$~', $parsed_url['host']) == 0 && preg_match('~(?:[^\.]+\.)?([^\.]{2,}\..+)\z~i', $parsed_url['host'], $parts) == 1)
193
		$parsed_url['host'] = '.' . $parts[1];
194
195
	// We shouldn't use a host at all if both options are off.
196
	elseif (!$local && !$global)
197
		$parsed_url['host'] = '';
198
199
	// The host also shouldn't be set if there aren't any dots in it.
200
	elseif (!isset($parsed_url['host']) || strpos($parsed_url['host'], '.') === false)
201
		$parsed_url['host'] = '';
202
203
	return array($parsed_url['host'], $parsed_url['path'] . '/');
204
}
205
206
/**
207
 * Throws guests out to the login screen when guest access is off.
208
 * - sets $_SESSION['login_url'] to $_SERVER['REQUEST_URL'].
209
 * - uses the 'kick_guest' sub template found in Login.template.php.
210
 */
211
function KickGuest()
212
{
213
	global $txt, $context;
214
215
	loadTheme();
216
	loadLanguage('Login');
217
	loadTemplate('Login');
218
	createToken('login');
219
220
	// Never redirect to an attachment
221
	if (strpos($_SERVER['REQUEST_URL'], 'dlattach') === false)
222
		$_SESSION['login_url'] = $_SERVER['REQUEST_URL'];
223
224
	$context['sub_template'] = 'kick_guest';
225
	$context['page_title'] = $txt['login'];
226
}
227
228
/**
229
 * Display a message about the forum being in maintenance mode.
230
 * - display a login screen with sub template 'maintenance'.
231
 * - sends a 503 header, so search engines don't bother indexing while we're in maintenance mode.
232
 */
233
function InMaintenance()
234
{
235
	global $txt, $mtitle, $mmessage, $context, $smcFunc;
236
237
	loadLanguage('Login');
238
	loadTemplate('Login');
239
	createToken('login');
240
241
	// Send a 503 header, so search engines don't bother indexing while we're in maintenance mode.
242
	send_http_status(503, 'Service Temporarily Unavailable');
243
244
	// Basic template stuff..
245
	$context['sub_template'] = 'maintenance';
246
	$context['title'] = $smcFunc['htmlspecialchars']($mtitle);
247
	$context['description'] = &$mmessage;
248
	$context['page_title'] = $txt['maintain_mode'];
249
}
250
251
/**
252
 * Question the verity of the admin by asking for his or her password.
253
 * - loads Login.template.php and uses the admin_login sub template.
254
 * - sends data to template so the admin is sent on to the page they
255
 *   wanted if their password is correct, otherwise they can try again.
256
 *
257
 * @param string $type What login type is this - can be 'admin' or 'moderate'
258
 */
259
function adminLogin($type = 'admin')
260
{
261
	global $context, $txt, $user_info;
262
263
	loadLanguage('Admin');
264
	loadTemplate('Login');
265
266
	// Validate what type of session check this is.
267
	$types = array();
268
	call_integration_hook('integrate_validateSession', array(&$types));
269
	$type = in_array($type, $types) || $type == 'moderate' ? $type : 'admin';
270
271
	// They used a wrong password, log it and unset that.
272
	if (isset($_POST[$type . '_hash_pass']) || isset($_POST[$type . '_pass']))
273
	{
274
		$txt['security_wrong'] = sprintf($txt['security_wrong'], isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : $txt['unknown'], $_SERVER['HTTP_USER_AGENT'], $user_info['ip']);
275
		log_error($txt['security_wrong'], 'critical');
276
277
		if (isset($_POST[$type . '_hash_pass']))
278
			unset($_POST[$type . '_hash_pass']);
279
		if (isset($_POST[$type . '_pass']))
280
			unset($_POST[$type . '_pass']);
281
282
		$context['incorrect_password'] = true;
283
	}
284
285
	createToken('admin-login');
286
287
	// Figure out the get data and post data.
288
	$context['get_data'] = '?' . construct_query_string($_GET);
289
	$context['post_data'] = '';
290
291
	// Now go through $_POST.  Make sure the session hash is sent.
292
	$_POST[$context['session_var']] = $context['session_id'];
293
	foreach ($_POST as $k => $v)
294
		$context['post_data'] .= adminLogin_outputPostVars($k, $v);
295
296
	// Now we'll use the admin_login sub template of the Login template.
297
	$context['sub_template'] = 'admin_login';
298
299
	// And title the page something like "Login".
300
	if (!isset($context['page_title']))
301
		$context['page_title'] = $txt['login'];
302
303
	// The type of action.
304
	$context['sessionCheckType'] = $type;
305
306
	obExit();
307
308
	// We MUST exit at this point, because otherwise we CANNOT KNOW that the user is privileged.
309
	die('No direct access...');
310
}
311
312
/**
313
 * Used by the adminLogin() function.
314
 * if 'value' is an array, the function is called recursively.
315
 *
316
 * @param string $k The keys
317
 * @param string $v The values
318
 * @return string 'hidden' HTML form fields, containing key-value-pairs
319
 */
320
function adminLogin_outputPostVars($k, $v)
321
{
322
	global $smcFunc;
323
324
	if (!is_array($v))
325
		return '
326
<input type="hidden" name="' . $smcFunc['htmlspecialchars']($k) . '" value="' . strtr($v, array('"' => '&quot;', '<' => '&lt;', '>' => '&gt;')) . '">';
327
	else
328
	{
329
		$ret = '';
330
		foreach ($v as $k2 => $v2)
331
			$ret .= adminLogin_outputPostVars($k . '[' . $k2 . ']', $v2);
332
333
		return $ret;
334
	}
335
}
336
337
/**
338
 * Properly urlencodes a string to be used in a query
339
 *
340
 * @param string $get
341
 * @return string Our query string
342
 */
343
function construct_query_string($get)
344
{
345
	global $scripturl;
346
347
	$query_string = '';
348
349
	// Awww, darn.  The $scripturl contains GET stuff!
350
	$q = strpos($scripturl, '?');
351
	if ($q !== false)
352
	{
353
		parse_str(preg_replace('/&(\w+)(?=&|$)/', '&$1=', strtr(substr($scripturl, $q + 1), ';', '&')), $temp);
354
355
		foreach ($get as $k => $v)
356
		{
357
			// Only if it's not already in the $scripturl!
358
			if (!isset($temp[$k]))
359
				$query_string .= urlencode($k) . '=' . urlencode($v) . ';';
360
			// If it changed, put it out there, but with an ampersand.
361
			elseif ($temp[$k] != $get[$k])
362
				$query_string .= urlencode($k) . '=' . urlencode($v) . '&amp;';
363
		}
364
	}
365
	else
366
	{
367
		// Add up all the data from $_GET into get_data.
368
		foreach ($get as $k => $v)
369
			$query_string .= urlencode($k) . '=' . urlencode($v) . ';';
370
	}
371
372
	$query_string = substr($query_string, 0, -1);
373
	return $query_string;
374
}
375
376
/**
377
 * Finds members by email address, username, or real name.
378
 * - searches for members whose username, display name, or e-mail address match the given pattern of array names.
379
 * - searches only buddies if buddies_only is set.
380
 *
381
 * @param array $names The names of members to search for
382
 * @param bool $use_wildcards Whether to use wildcards. Accepts wildcards ? and * in the pattern if true
383
 * @param bool $buddies_only Whether to only search for the user's buddies
384
 * @param int $max The maximum number of results
385
 * @return array An array containing information about the matching members
386
 */
387
function findMembers($names, $use_wildcards = false, $buddies_only = false, $max = 500)
388
{
389
	global $scripturl, $user_info, $smcFunc;
390
391
	// If it's not already an array, make it one.
392
	if (!is_array($names))
393
		$names = explode(',', $names);
394
395
	$maybe_email = false;
396
	$names_list = array();
397
	foreach (array_values($names) as $i => $name)
398
	{
399
		// Trim, and fix wildcards for each name.
400
		$names[$i] = trim($smcFunc['strtolower']($name));
401
402
		$maybe_email |= strpos($name, '@') !== false;
403
404
		// Make it so standard wildcards will work. (* and ?)
405
		if ($use_wildcards)
406
			$names[$i] = strtr($names[$i], array('%' => '\%', '_' => '\_', '*' => '%', '?' => '_', '\'' => '&#039;'));
407
		else
408
			$names[$i] = strtr($names[$i], array('\'' => '&#039;'));
409
410
		$names_list[] = '{string:lookup_name_' . $i . '}';
411
		$where_params['lookup_name_' . $i] = $names[$i];
412
	}
413
414
	// What are we using to compare?
415
	$comparison = $use_wildcards ? 'LIKE' : '=';
416
417
	// Nothing found yet.
418
	$results = array();
419
420
	// This ensures you can't search someones email address if you can't see it.
421
	if (($use_wildcards || $maybe_email) && allowedTo('moderate_forum'))
422
		$email_condition = '
423
			OR (email_address ' . $comparison . ' \'' . implode('\') OR (email_address ' . $comparison . ' \'', $names) . '\')';
424
	else
425
		$email_condition = '';
426
427
	// Get the case of the columns right - but only if we need to as things like MySQL will go slow needlessly otherwise.
428
	$member_name = $smcFunc['db_case_sensitive'] ? 'LOWER(member_name)' : 'member_name';
429
	$real_name = $smcFunc['db_case_sensitive'] ? 'LOWER(real_name)' : 'real_name';
430
431
	// Searches.
432
	$member_name_search = $member_name . ' ' . $comparison . ' ' . implode(' OR ' . $member_name . ' ' . $comparison . ' ', $names_list);
433
	$real_name_search = $real_name . ' ' . $comparison . ' ' . implode(' OR ' . $real_name . ' ' . $comparison . ' ', $names_list);
434
435
	// Search by username, display name, and email address.
436
	$request = $smcFunc['db_query']('', '
437
		SELECT id_member, member_name, real_name, email_address
438
		FROM {db_prefix}members
439
		WHERE (' . $member_name_search . '
440
			OR ' . $real_name_search . ' ' . $email_condition . ')
441
			' . ($buddies_only ? 'AND id_member IN ({array_int:buddy_list})' : '') . '
442
			AND is_activated IN (1, 11)
443
		LIMIT {int:limit}',
444
		array_merge($where_params, array(
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $where_params seems to be defined by a foreach iteration on line 397. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
445
			'buddy_list' => $user_info['buddies'],
446
			'limit' => $max,
447
		))
448
	);
449
	while ($row = $smcFunc['db_fetch_assoc']($request))
450
	{
451
		$results[$row['id_member']] = array(
452
			'id' => $row['id_member'],
453
			'name' => $row['real_name'],
454
			'username' => $row['member_name'],
455
			'email' => allowedTo('moderate_forum') ? $row['email_address'] : '',
456
			'href' => $scripturl . '?action=profile;u=' . $row['id_member'],
457
			'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>'
458
		);
459
	}
460
	$smcFunc['db_free_result']($request);
461
462
	// Return all the results.
463
	return $results;
464
}
465
466
/**
467
 * Called by index.php?action=findmember.
468
 * - is used as a popup for searching members.
469
 * - uses sub template find_members of the Help template.
470
 * - also used to add members for PM's sent using wap2/imode protocol.
471
 */
472
function JSMembers()
473
{
474
	global $context, $scripturl, $user_info, $smcFunc;
475
476
	checkSession('get');
477
478
	// Why is this in the Help template, you ask?  Well, erm... it helps you.  Does that work?
479
	loadTemplate('Help');
480
481
	$context['template_layers'] = array();
482
	$context['sub_template'] = 'find_members';
483
484
	if (isset($_REQUEST['search']))
485
		$context['last_search'] = $smcFunc['htmlspecialchars']($_REQUEST['search'], ENT_QUOTES);
486
	else
487
		$_REQUEST['start'] = 0;
488
489
	// Allow the user to pass the input to be added to to the box.
490
	$context['input_box_name'] = isset($_REQUEST['input']) && preg_match('~^[\w-]+$~', $_REQUEST['input']) === 1 ? $_REQUEST['input'] : 'to';
491
492
	// Take the delimiter over GET in case it's \n or something.
493
	$context['delimiter'] = isset($_REQUEST['delim']) ? ($_REQUEST['delim'] == 'LB' ? "\n" : $_REQUEST['delim']) : ', ';
494
	$context['quote_results'] = !empty($_REQUEST['quote']);
495
496
	// List all the results.
497
	$context['results'] = array();
498
499
	// Some buddy related settings ;)
500
	$context['show_buddies'] = !empty($user_info['buddies']);
501
	$context['buddy_search'] = isset($_REQUEST['buddies']);
502
503
	// If the user has done a search, well - search.
504
	if (isset($_REQUEST['search']))
505
	{
506
		$_REQUEST['search'] = $smcFunc['htmlspecialchars']($_REQUEST['search'], ENT_QUOTES);
507
508
		$context['results'] = findMembers(array($_REQUEST['search']), true, $context['buddy_search']);
509
		$total_results = count($context['results']);
510
511
		$context['page_index'] = constructPageIndex($scripturl . '?action=findmember;search=' . $context['last_search'] . ';' . $context['session_var'] . '=' . $context['session_id'] . ';input=' . $context['input_box_name'] . ($context['quote_results'] ? ';quote=1' : '') . ($context['buddy_search'] ? ';buddies' : ''), $_REQUEST['start'], $total_results, 7);
512
513
		// Determine the navigation context.
514
		$base_url = $scripturl . '?action=findmember;search=' . urlencode($context['last_search']) . (empty($_REQUEST['u']) ? '' : ';u=' . $_REQUEST['u']) . ';' . $context['session_var'] . '=' . $context['session_id'];
515
		$context['links'] = array(
516
			'first' => $_REQUEST['start'] >= 7 ? $base_url . ';start=0' : '',
517
			'prev' => $_REQUEST['start'] >= 7 ? $base_url . ';start=' . ($_REQUEST['start'] - 7) : '',
518
			'next' => $_REQUEST['start'] + 7 < $total_results ? $base_url . ';start=' . ($_REQUEST['start'] + 7) : '',
519
			'last' => $_REQUEST['start'] + 7 < $total_results ? $base_url . ';start=' . (floor(($total_results - 1) / 7) * 7) : '',
520
			'up' => $scripturl . '?action=pm;sa=send' . (empty($_REQUEST['u']) ? '' : ';u=' . $_REQUEST['u']),
521
		);
522
		$context['page_info'] = array(
523
			'current_page' => $_REQUEST['start'] / 7 + 1,
524
			'num_pages' => floor(($total_results - 1) / 7) + 1
525
		);
526
527
		$context['results'] = array_slice($context['results'], $_REQUEST['start'], 7);
528
	}
529
	else
530
		$context['links']['up'] = $scripturl . '?action=pm;sa=send' . (empty($_REQUEST['u']) ? '' : ';u=' . $_REQUEST['u']);
531
}
532
533
/**
534
 * Outputs each member name on its own line.
535
 * - used by javascript to find members matching the request.
536
 */
537
function RequestMembers()
538
{
539
	global $user_info, $txt, $smcFunc;
540
541
	checkSession('get');
542
543
	$_REQUEST['search'] = $smcFunc['htmlspecialchars']($_REQUEST['search']) . '*';
544
	$_REQUEST['search'] = trim($smcFunc['strtolower']($_REQUEST['search']));
545
	$_REQUEST['search'] = strtr($_REQUEST['search'], array('%' => '\%', '_' => '\_', '*' => '%', '?' => '_', '&#038;' => '&amp;'));
546
547
	if (function_exists('iconv'))
548
		header('content-type: text/plain; charset=UTF-8');
549
550
	$request = $smcFunc['db_query']('', '
551
		SELECT real_name
552
		FROM {db_prefix}members
553
		WHERE {raw:real_name} LIKE {string:search}' . (isset($_REQUEST['buddies']) ? '
554
			AND id_member IN ({array_int:buddy_list})' : '') . '
555
			AND is_activated IN (1, 11)
556
		LIMIT ' . ($smcFunc['strlen']($_REQUEST['search']) <= 2 ? '100' : '800'),
557
		array(
558
			'real_name' => $smcFunc['db_case_sensitive'] ? 'LOWER(real_name)' : 'real_name',
559
			'buddy_list' => $user_info['buddies'],
560
			'search' => $_REQUEST['search'],
561
		)
562
	);
563
	while ($row = $smcFunc['db_fetch_assoc']($request))
564
	{
565
		if (function_exists('iconv'))
566
		{
567
			$utf8 = iconv($txt['lang_character_set'], 'UTF-8', $row['real_name']);
568
			if ($utf8)
569
				$row['real_name'] = $utf8;
570
		}
571
572
		$row['real_name'] = strtr($row['real_name'], array('&amp;' => '&#038;', '&lt;' => '&#060;', '&gt;' => '&#062;', '&quot;' => '&#034;'));
573
574
		if (preg_match('~&#\d+;~', $row['real_name']) != 0)
575
			$row['real_name'] = preg_replace_callback('~&#(\d+);~', 'fixchar__callback', $row['real_name']);
576
577
		echo $row['real_name'], "\n";
578
	}
579
	$smcFunc['db_free_result']($request);
580
581
	obExit(false);
582
}
583
584
/**
585
 * Generates a random password for a user and emails it to them.
586
 * - called by Profile.php when changing someone's username.
587
 * - checks the validity of the new username.
588
 * - generates and sets a new password for the given user.
589
 * - mails the new password to the email address of the user.
590
 * - if username is not set, only a new password is generated and sent.
591
 *
592
 * @param int $memID The ID of the member
593
 * @param string $username The new username. If set, also checks the validity of the username
594
 */
595
function resetPassword($memID, $username = null)
596
{
597
	global $sourcedir, $modSettings, $smcFunc, $language;
598
599
	// Language... and a required file.
600
	loadLanguage('Login');
601
	require_once($sourcedir . '/Subs-Post.php');
602
603
	// Get some important details.
604
	$request = $smcFunc['db_query']('', '
605
		SELECT member_name, email_address, lngfile
606
		FROM {db_prefix}members
607
		WHERE id_member = {int:id_member}',
608
		array(
609
			'id_member' => $memID,
610
		)
611
	);
612
	list ($user, $email, $lngfile) = $smcFunc['db_fetch_row']($request);
613
	$smcFunc['db_free_result']($request);
614
615
	if ($username !== null)
616
	{
617
		$old_user = $user;
618
		$user = trim($username);
619
	}
620
621
	// Generate a random password.
622
	$newPassword = substr(preg_replace('/\W/', '', md5($smcFunc['random_int']())), 0, 10);
623
	$newPassword_sha1 = hash_password($user, $newPassword);
624
625
	// Do some checks on the username if needed.
626
	if ($username !== null)
627
	{
628
		validateUsername($memID, $user);
629
630
		// Update the database...
631
		updateMemberData($memID, array('member_name' => $user, 'passwd' => $newPassword_sha1));
632
	}
633
	else
634
		updateMemberData($memID, array('passwd' => $newPassword_sha1));
635
636
	call_integration_hook('integrate_reset_pass', array($old_user, $user, $newPassword));
637
638
	$replacements = array(
639
		'USERNAME' => $user,
640
		'PASSWORD' => $newPassword,
641
	);
642
643
	$emaildata = loadEmailTemplate('change_password', $replacements, empty($lngfile) || empty($modSettings['userLanguage']) ? $language : $lngfile);
644
645
	// Send them the email informing them of the change - then we're done!
646
	sendmail($email, $emaildata['subject'], $emaildata['body'], null, 'chgpass' . $memID, $emaildata['is_html'], 0);
647
}
648
649
/**
650
 * Checks a username obeys a load of rules
651
 *
652
 * @param int $memID The ID of the member
653
 * @param string $username The username to validate
654
 * @param boolean $return_error Whether to return errors
655
 * @param boolean $check_reserved_name Whether to check this against the list of reserved names
656
 * @return array|null Null if there are no errors, otherwise an array of errors if return_error is true
657
 */
658
function validateUsername($memID, $username, $return_error = false, $check_reserved_name = true)
659
{
660
	global $sourcedir, $txt, $smcFunc, $user_info;
661
662
	$errors = array();
663
664
	// Don't use too long a name.
665
	if ($smcFunc['strlen']($username) > 25)
666
		$errors[] = array('lang', 'error_long_name');
667
668
	// No name?!  How can you register with no name?
669
	if ($username == '')
670
		$errors[] = array('lang', 'need_username');
671
672
	// Only these characters are permitted.
673
	if (in_array($username, array('_', '|')) || preg_match('~[<>&"\'=\\\\]~', preg_replace('~&#(?:\\d{1,7}|x[0-9a-fA-F]{1,6});~', '', $username)) != 0 || strpos($username, '[code') !== false || strpos($username, '[/code') !== false)
674
		$errors[] = array('lang', 'error_invalid_characters_username');
675
676
	if (stristr($username, $txt['guest_title']) !== false)
677
		$errors[] = array('lang', 'username_reserved', 'general', array($txt['guest_title']));
678
679
	if ($check_reserved_name)
680
	{
681
		require_once($sourcedir . '/Subs-Members.php');
682
		if (isReservedName($username, $memID, false))
683
			$errors[] = array('done', '(' . $smcFunc['htmlspecialchars']($username) . ') ' . $txt['name_in_use']);
684
	}
685
686
	// Maybe a mod wants to perform more checks?
687
	call_integration_hook('integrate_validate_username', array($username, &$errors));
688
689
	if ($return_error)
690
		return $errors;
691
	elseif (empty($errors))
692
		return null;
693
694
	loadLanguage('Errors');
695
	$error = $errors[0];
696
697
	$message = $error[0] == 'lang' ? (empty($error[3]) ? $txt[$error[1]] : vsprintf($txt[$error[1]], (array) $error[3])) : $error[1];
698
	fatal_error($message, empty($error[2]) || $user_info['is_admin'] ? false : $error[2]);
699
}
700
701
/**
702
 * Checks whether a password meets the current forum rules
703
 * - called when registering/choosing a password.
704
 * - checks the password obeys the current forum settings for password strength.
705
 * - if password checking is enabled, will check that none of the words in restrict_in appear in the password.
706
 * - returns an error identifier if the password is invalid, or null.
707
 *
708
 * @param string $password The desired password
709
 * @param string $username The username
710
 * @param array $restrict_in An array of restricted strings that cannot be part of the password (email address, username, etc.)
711
 * @return null|string Null if valid or a string indicating what the problem was
712
 */
713
function validatePassword($password, $username, $restrict_in = array())
714
{
715
	global $modSettings, $smcFunc;
716
717
	// Perform basic requirements first.
718
	if ($smcFunc['strlen']($password) < (empty($modSettings['password_strength']) ? 4 : 8))
719
		return 'short';
720
721
	// Maybe we need some more fancy password checks.
722
	$pass_error = '';
723
	call_integration_hook('integrate_validatePassword', array($password, $username, $restrict_in, &$pass_error));
724
	if (!empty($pass_error))
725
		return $pass_error;
726
727
	// Is this enough?
728
	if (empty($modSettings['password_strength']))
729
		return null;
730
731
	// Otherwise, perform the medium strength test - checking if password appears in the restricted string.
732
	if (preg_match('~\b' . preg_quote($password, '~') . '\b~', implode(' ', $restrict_in)) != 0)
733
		return 'restricted_words';
734
	elseif ($smcFunc['strpos']($password, $username) !== false)
735
		return 'restricted_words';
736
737
	// If just medium, we're done.
738
	if ($modSettings['password_strength'] == 1)
739
		return null;
740
741
	// Otherwise, hard test next, check for numbers and letters, uppercase too.
742
	$good = preg_match('~(\D\d|\d\D)~', $password) != 0;
743
	$good &= $smcFunc['strtolower']($password) != $password;
744
745
	return $good ? null : 'chars';
746
}
747
748
/**
749
 * Quickly find out what moderation authority this user has
750
 * - builds the moderator, group and board level querys for the user
751
 * - stores the information on the current users moderation powers in $user_info['mod_cache'] and $_SESSION['mc']
752
 */
753
function rebuildModCache()
754
{
755
	global $user_info, $smcFunc;
756
757
	// What groups can they moderate?
758
	$group_query = allowedTo('manage_membergroups') ? '1=1' : '0=1';
759
760
	if ($group_query == '0=1' && !$user_info['is_guest'])
761
	{
762
		$request = $smcFunc['db_query']('', '
763
			SELECT id_group
764
			FROM {db_prefix}group_moderators
765
			WHERE id_member = {int:current_member}',
766
			array(
767
				'current_member' => $user_info['id'],
768
			)
769
		);
770
		$groups = array();
771
		while ($row = $smcFunc['db_fetch_assoc']($request))
772
			$groups[] = $row['id_group'];
773
		$smcFunc['db_free_result']($request);
774
775
		if (empty($groups))
776
			$group_query = '0=1';
777
		else
778
			$group_query = 'id_group IN (' . implode(',', $groups) . ')';
779
	}
780
781
	// Then, same again, just the boards this time!
782
	$board_query = allowedTo('moderate_forum') ? '1=1' : '0=1';
783
784
	if ($board_query == '0=1' && !$user_info['is_guest'])
785
	{
786
		$boards = boardsAllowedTo('moderate_board', true);
787
788
		if (empty($boards))
789
			$board_query = '0=1';
790
		else
791
			$board_query = 'id_board IN (' . implode(',', $boards) . ')';
792
	}
793
794
	// What boards are they the moderator of?
795
	$boards_mod = array();
796
	if (!$user_info['is_guest'])
797
	{
798
		$request = $smcFunc['db_query']('', '
799
			SELECT id_board
800
			FROM {db_prefix}moderators
801
			WHERE id_member = {int:current_member}',
802
			array(
803
				'current_member' => $user_info['id'],
804
			)
805
		);
806
		while ($row = $smcFunc['db_fetch_assoc']($request))
807
			$boards_mod[] = $row['id_board'];
808
		$smcFunc['db_free_result']($request);
809
810
		// Can any of the groups they're in moderate any of the boards?
811
		$request = $smcFunc['db_query']('', '
812
			SELECT id_board
813
			FROM {db_prefix}moderator_groups
814
			WHERE id_group IN({array_int:groups})',
815
			array(
816
				'groups' => $user_info['groups'],
817
			)
818
		);
819
		while ($row = $smcFunc['db_fetch_assoc']($request))
820
			$boards_mod[] = $row['id_board'];
821
		$smcFunc['db_free_result']($request);
822
823
		// Just in case we've got duplicates here...
824
		$boards_mod = array_unique($boards_mod);
825
	}
826
827
	$mod_query = empty($boards_mod) ? '0=1' : 'b.id_board IN (' . implode(',', $boards_mod) . ')';
828
829
	$_SESSION['mc'] = array(
830
		'time' => time(),
831
		// This looks a bit funny but protects against the login redirect.
832
		'id' => $user_info['id'] && $user_info['name'] ? $user_info['id'] : 0,
833
		// If you change the format of 'gq' and/or 'bq' make sure to adjust 'can_mod' in Load.php.
834
		'gq' => $group_query,
835
		'bq' => $board_query,
836
		'ap' => boardsAllowedTo('approve_posts'),
837
		'mb' => $boards_mod,
838
		'mq' => $mod_query,
839
	);
840
	call_integration_hook('integrate_mod_cache');
841
842
	$user_info['mod_cache'] = $_SESSION['mc'];
843
844
	// Might as well clean up some tokens while we are at it.
845
	cleanTokens();
846
}
847
848
/**
849
 * A wrapper for setcookie that gives integration hook access to it
850
 *
851
 * @param string $name
852
 * @param string $value = ''
853
 * @param int $expire = 0
854
 * @param string $path = ''
855
 * @param string $domain = ''
856
 * @param bool $secure = false
857
 * @param bool $httponly = true
858
 * @param string $samesite = lax
859
 */
860
function smf_setcookie($name, $value = '', $expire = 0, $path = '', $domain = '', $secure = null, $httponly = true, $samesite = null)
861
{
862
	global $modSettings;
863
864
	// In case a customization wants to override the default settings
865
	if ($httponly === null)
866
		$httponly = !empty($modSettings['httponlyCookies']);
867
	if ($secure === null)
868
		$secure = !empty($modSettings['secureCookies']);
869
	if ($samesite === null)
870
		$samesite = !empty($modSettings['samesiteCookies']) ? $modSettings['samesiteCookies'] : 'lax';
871
872
	// Intercept cookie?
873
	call_integration_hook('integrate_cookie', array($name, $value, $expire, $path, $domain, $secure, $httponly, $samesite));
874
875
	if(PHP_VERSION_ID < 70300)
876
		return setcookie($name, $value, $expire, $path . ';samesite=' . $samesite, $domain, $secure, $httponly);
877
	else
878
		return setcookie($name, $value, array(
879
			'expires' 	=> $expire,
880
			'path'		=> $path,
881
			'domain' 	=> $domain,
882
			'secure'	=> $secure,
883
			'httponly'	=> $httponly,
884
			'samesite'	=> $samesite
885
		));
886
}
887
888
/**
889
 * Hashes username with password
890
 *
891
 * @param string $username The username
892
 * @param string $password The unhashed password
893
 * @param int $cost The cost
894
 * @return string The hashed password
895
 */
896
function hash_password($username, $password, $cost = null)
897
{
898
	global $smcFunc, $modSettings;
899
900
	$cost = empty($cost) ? (empty($modSettings['bcrypt_hash_cost']) ? 10 : $modSettings['bcrypt_hash_cost']) : $cost;
901
902
	return password_hash($smcFunc['strtolower']($username) . $password, PASSWORD_BCRYPT, array(
903
		'cost' => $cost,
904
	));
905
}
906
907
/**
908
 * Hashes password with salt and authentication secret. This is solely used for cookies.
909
 *
910
 * @param string $password The password
911
 * @param string $salt The salt
912
 * @return string The hashed password
913
 */
914
function hash_salt($password, $salt)
915
{
916
	// Append the salt to get a user-specific authentication secret.
917
	$secret_key = get_auth_secret() . $salt;
918
919
	// Now use that to generate an HMAC of the password.
920
	return hash_hmac('sha512', $password, $secret_key);
921
}
922
923
/**
924
 * Verifies a raw SMF password against the bcrypt'd string
925
 *
926
 * @param string $username The username
927
 * @param string $password The password
928
 * @param string $hash The hashed string
929
 * @return bool Whether the hashed password matches the string
930
 */
931
function hash_verify_password($username, $password, $hash)
932
{
933
	global $smcFunc;
934
935
	return password_verify($smcFunc['strtolower']($username) . $password, $hash);
936
}
937
938
/**
939
 * Returns the length for current hash
940
 *
941
 * @return int The length for the current hash
942
 */
943
function hash_length()
944
{
945
	return 60;
946
}
947
948
/**
949
 * Benchmarks the server to figure out an appropriate cost factor (minimum 9)
950
 *
951
 * @param float $hashTime Time to target, in seconds
952
 * @return int The cost
953
 */
954
function hash_benchmark($hashTime = 0.2)
955
{
956
	$cost = 9;
957
	do
958
	{
959
		$timeStart = microtime(true);
960
		hash_password('test', 'thisisatestpassword', $cost);
961
		$timeTaken = microtime(true) - $timeStart;
962
		$cost++;
963
	}
964
	while ($timeTaken < $hashTime);
965
966
	return $cost;
967
}
968
969
// Based on code by "examplehash at user dot com".
970
// https://www.php.net/manual/en/function.hash-equals.php#125034
971
if (!function_exists('hash_equals'))
972
{
973
	/**
974
	 * A compatibility function for when PHP's "hash_equals" function isn't available
975
	 * @param string $known_string A known hash
976
	 * @param string $user_string The hash of the user string
977
	 * @return bool Whether or not the two are equal
978
	 */
979
	function hash_equals($known_string, $user_string)
980
	{
981
		$known_string = (string) $known_string;
982
		$user_string = (string) $user_string;
983
984
		$sx = 0;
985
		$sy = strlen($known_string);
986
		$uy = strlen($user_string);
987
		$result = $sy - $uy;
988
		for ($ux = 0; $ux < $uy; $ux++)
989
		{
990
			$result |= ord($user_string[$ux]) ^ ord($known_string[$sx]);
991
			$sx = ($sx + 1) % $sy;
992
		}
993
994
		return !$result;
995
	}
996
}
997
998
?>