users.php 46.6 KB
Newer Older
Scott committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<?php
/*
	Question2Answer by Gideon Greenspan and contributors
	http://www.question2answer.org/

	Description: User management (application level) for basic user operations


	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	More about this license: http://www.question2answer.org/license.php
*/

Scott committed
22
if (!defined('QA_VERSION')) { // don't allow this page to be requested directly from browser
23
	header('Location: ../../');
Scott committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
	exit;
}

define('QA_USER_LEVEL_BASIC', 0);
define('QA_USER_LEVEL_APPROVED', 10);
define('QA_USER_LEVEL_EXPERT', 20);
define('QA_USER_LEVEL_EDITOR', 50);
define('QA_USER_LEVEL_MODERATOR', 80);
define('QA_USER_LEVEL_ADMIN', 100);
define('QA_USER_LEVEL_SUPER', 120);

define('QA_USER_FLAGS_EMAIL_CONFIRMED', 1);
define('QA_USER_FLAGS_USER_BLOCKED', 2);
define('QA_USER_FLAGS_SHOW_AVATAR', 4);
define('QA_USER_FLAGS_SHOW_GRAVATAR', 8);
define('QA_USER_FLAGS_NO_MESSAGES', 16);
define('QA_USER_FLAGS_NO_MAILINGS', 32);
define('QA_USER_FLAGS_WELCOME_NOTICE', 64);
define('QA_USER_FLAGS_MUST_CONFIRM', 128);
define('QA_USER_FLAGS_NO_WALL_POSTS', 256);
44
define('QA_USER_FLAGS_MUST_APPROVE', 512); // @deprecated
Scott committed
45 46 47 48 49

define('QA_FIELD_FLAGS_MULTI_LINE', 1);
define('QA_FIELD_FLAGS_LINK_URL', 2);
define('QA_FIELD_FLAGS_ON_REGISTER', 4);

50 51 52 53 54 55 56
if (!defined('QA_FORM_EXPIRY_SECS')) {
	// how many seconds a form is valid for submission
	define('QA_FORM_EXPIRY_SECS', 86400);
}
if (!defined('QA_FORM_KEY_LENGTH')) {
	define('QA_FORM_KEY_LENGTH', 32);
}
Scott committed
57 58 59 60 61 62 63 64 65 66 67


if (QA_FINAL_EXTERNAL_USERS) {
	// If we're using single sign-on integration (WordPress or otherwise), load PHP file for that

	if (defined('QA_FINAL_WORDPRESS_INTEGRATE_PATH')) {
		require_once QA_INCLUDE_DIR . 'util/external-users-wp.php';
	} elseif (defined('QA_FINAL_JOOMLA_INTEGRATE_PATH')) {
		require_once QA_INCLUDE_DIR . 'util/external-users-joomla.php';
	} else {
		require_once QA_EXTERNAL_DIR . 'qa-external-users.php';
Scott committed
68 69
	}

Scott committed
70
	// Access functions for user information
Scott committed
71

Scott committed
72 73 74 75 76 77
	/**
	 * Return array of information about the currently logged in user, cache to ensure only one call to external code
	 */
	function qa_get_logged_in_user_cache()
	{
		global $qa_cached_logged_in_user;
Scott committed
78

Scott committed
79 80
		if (!isset($qa_cached_logged_in_user)) {
			$user = qa_get_logged_in_user();
Scott committed
81

Scott committed
82 83 84 85 86
			if (isset($user)) {
				$user['flags'] = isset($user['blocked']) ? QA_USER_FLAGS_USER_BLOCKED : 0;
				$qa_cached_logged_in_user = $user;
			} else
				$qa_cached_logged_in_user = false;
pupi1985 committed
87
		}
Scott committed
88

Scott committed
89 90
		return @$qa_cached_logged_in_user;
	}
Scott committed
91 92


Scott committed
93 94
	/**
	 * Return $field of the currently logged in user, or null if not available
95 96
	 * @param string $field
	 * @return string|null
Scott committed
97 98 99 100
	 */
	function qa_get_logged_in_user_field($field)
	{
		$user = qa_get_logged_in_user_cache();
101

Scott committed
102 103
		return isset($user[$field]) ? $user[$field] : null;
	}
Scott committed
104 105


Scott committed
106 107 108 109 110 111 112
	/**
	 * Return the userid of the currently logged in user, or null if none
	 */
	function qa_get_logged_in_userid()
	{
		return qa_get_logged_in_user_field('userid');
	}
Scott committed
113 114


Scott committed
115 116 117 118 119 120
	/**
	 * Return the number of points of the currently logged in user, or null if none is logged in
	 */
	function qa_get_logged_in_points()
	{
		global $qa_cached_logged_in_points;
Scott committed
121

Scott committed
122 123
		if (!isset($qa_cached_logged_in_points)) {
			require_once QA_INCLUDE_DIR . 'db/selects.php';
Scott committed
124

Scott committed
125
			$qa_cached_logged_in_points = qa_db_select_with_pending(qa_db_user_points_selectspec(qa_get_logged_in_userid(), true));
Scott committed
126 127
		}

Scott committed
128 129
		return $qa_cached_logged_in_points['points'];
	}
Scott committed
130 131


Scott committed
132 133
	/**
	 * Return HTML to display for the avatar of $userid, constrained to $size pixels, with optional $padding to that size
134 135
	 * @param mixed $userid
	 * @param int|null $size
Scott committed
136
	 * @param bool $padding
137
	 * @return string|null
Scott committed
138 139 140 141 142 143 144 145
	 */
	function qa_get_external_avatar_html($userid, $size, $padding = false)
	{
		if (function_exists('qa_avatar_html_from_userid'))
			return qa_avatar_html_from_userid($userid, $size, $padding);
		else
			return null;
	}
Scott committed
146 147


Scott committed
148
} else {
Scott committed
149

Scott committed
150 151 152 153 154 155
	/**
	 * Open a PHP session if one isn't opened already
	 */
	function qa_start_session()
	{
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
156

Scott committed
157 158 159
		@ini_set('session.gc_maxlifetime', 86400); // worth a try, but won't help in shared hosting environment
		@ini_set('session.use_trans_sid', false); // sessions need cookies to work, since we redirect after login
		@ini_set('session.cookie_domain', QA_COOKIE_DOMAIN);
Scott committed
160

Scott committed
161 162 163
		if (!isset($_SESSION))
			session_start();
	}
Scott committed
164 165


Scott committed
166 167 168 169 170 171
	/**
	 * Returns a suffix to be used for names of session variables to prevent them being shared between multiple Q2A sites on the same server
	 */
	function qa_session_var_suffix()
	{
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
172

Scott committed
173
		global $qa_session_suffix;
Scott committed
174

Scott committed
175 176 177
		if (!$qa_session_suffix) {
			$prefix = defined('QA_MYSQL_USERS_PREFIX') ? QA_MYSQL_USERS_PREFIX : QA_MYSQL_TABLE_PREFIX;
			$qa_session_suffix = md5(QA_FINAL_MYSQL_HOSTNAME . '/' . QA_FINAL_MYSQL_USERNAME . '/' . QA_FINAL_MYSQL_PASSWORD . '/' . QA_FINAL_MYSQL_DATABASE . '/' . $prefix);
Scott committed
178 179
		}

Scott committed
180 181
		return $qa_session_suffix;
	}
Scott committed
182 183


Scott committed
184 185
	/**
	 * Returns a verification code used to ensure that a user session can't be generated by another PHP script running on the same server
186 187
	 * @param int $userid
	 * @return string
Scott committed
188 189 190 191
	 */
	function qa_session_verify_code($userid)
	{
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
192

Scott committed
193 194
		return sha1($userid . '/' . QA_MYSQL_TABLE_PREFIX . '/' . QA_FINAL_MYSQL_DATABASE . '/' . QA_FINAL_MYSQL_PASSWORD . '/' . QA_FINAL_MYSQL_USERNAME . '/' . QA_FINAL_MYSQL_HOSTNAME);
	}
Scott committed
195 196


Scott committed
197 198 199
	/**
	 * Set cookie in browser for username $handle with $sessioncode (in database).
	 * Pass true if user checked 'Remember me' (either now or previously, as learned from cookie).
200 201 202
	 * @param string $handle
	 * @param string $sessioncode
	 * @param bool $remember
Scott committed
203 204 205 206 207
	 * @return mixed
	 */
	function qa_set_session_cookie($handle, $sessioncode, $remember)
	{
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
208

Scott committed
209 210 211
		// if $remember is true, store in browser for a month, otherwise store only until browser is closed
		setcookie('qa_session', $handle . '/' . $sessioncode . '/' . ($remember ? 1 : 0), $remember ? (time() + 2592000) : 0, '/', QA_COOKIE_DOMAIN, (bool)ini_get('session.cookie_secure'), true);
	}
Scott committed
212 213


Scott committed
214 215 216 217 218 219
	/**
	 * Remove session cookie from browser
	 */
	function qa_clear_session_cookie()
	{
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
220

Scott committed
221 222
		setcookie('qa_session', false, 0, '/', QA_COOKIE_DOMAIN, (bool)ini_get('session.cookie_secure'), true);
	}
Scott committed
223 224


Scott committed
225 226
	/**
	 * Set the session variables to indicate that $userid is logged in from $source
227 228
	 * @param int $userid
	 * @param string|null $source
Scott committed
229 230 231 232 233
	 * @return mixed
	 */
	function qa_set_session_user($userid, $source)
	{
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
234

Scott committed
235
		$suffix = qa_session_var_suffix();
Scott committed
236

Scott committed
237 238 239 240 241
		$_SESSION['qa_session_userid_' . $suffix] = $userid;
		$_SESSION['qa_session_source_' . $suffix] = $source;
		// prevents one account on a shared server being able to create a log in a user to Q2A on another account on same server
		$_SESSION['qa_session_verify_' . $suffix] = qa_session_verify_code($userid);
	}
Scott committed
242 243


Scott committed
244 245 246 247 248 249
	/**
	 * Clear the session variables indicating that a user is logged in
	 */
	function qa_clear_session_user()
	{
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
250

Scott committed
251
		$suffix = qa_session_var_suffix();
Scott committed
252

Scott committed
253 254 255 256
		unset($_SESSION['qa_session_userid_' . $suffix]);
		unset($_SESSION['qa_session_source_' . $suffix]);
		unset($_SESSION['qa_session_verify_' . $suffix]);
	}
Scott committed
257 258


Scott committed
259 260 261
	/**
	 * Call for successful log in by $userid and $handle or successful log out with $userid=null.
	 * $remember states if 'Remember me' was checked in the login form.
262
	 * @param int|null $userid
Scott committed
263 264
	 * @param string $handle
	 * @param bool $remember
265
	 * @param string|null $source
Scott committed
266 267 268 269 270
	 * @return mixed
	 */
	function qa_set_logged_in_user($userid, $handle = '', $remember = false, $source = null)
	{
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
271

Scott committed
272
		require_once QA_INCLUDE_DIR . 'app/cookies.php';
Scott committed
273

Scott committed
274
		qa_start_session();
Scott committed
275

Scott committed
276 277
		if (isset($userid)) {
			qa_set_session_user($userid, $source);
Scott committed
278

Scott committed
279 280 281
			// PHP sessions time out too quickly on the server side, so we also set a cookie as backup.
			// Logging in from a second browser will make the previous browser's 'Remember me' no longer
			// work - I'm not sure if this is the right behavior - could see it either way.
Scott committed
282

Scott committed
283
			require_once QA_INCLUDE_DIR . 'db/selects.php';
Scott committed
284

Scott committed
285
			$userinfo = qa_db_single_select(qa_db_user_account_selectspec($userid, true));
Scott committed
286

Scott committed
287 288
			// if we have logged in before, and are logging in the same way as before, we don't need to change the sessioncode/source
			// this means it will be possible to automatically log in (via cookies) to the same account from more than one browser
Scott committed
289

Scott committed
290 291
			if (empty($userinfo['sessioncode']) || ($source !== $userinfo['sessionsource'])) {
				$sessioncode = qa_db_user_rand_sessioncode();
292 293 294 295
				qa_db_user_set($userid, array(
					'sessioncode' => $sessioncode,
					'sessionsource' => $source,
				));
Scott committed
296 297
			} else
				$sessioncode = $userinfo['sessioncode'];
Scott committed
298

Scott committed
299 300
			qa_db_user_logged_in($userid, qa_remote_ip_address());
			qa_set_session_cookie($handle, $sessioncode, $remember);
Scott committed
301

Scott committed
302
			qa_report_event('u_login', $userid, $userinfo['handle'], qa_cookie_get());
Scott committed
303

Scott committed
304 305 306
		} else {
			$olduserid = qa_get_logged_in_userid();
			$oldhandle = qa_get_logged_in_handle();
Scott committed
307

Scott committed
308 309
			qa_clear_session_cookie();
			qa_clear_session_user();
Scott committed
310

Scott committed
311
			qa_report_event('u_logout', $olduserid, $oldhandle, qa_cookie_get());
Scott committed
312
		}
Scott committed
313
	}
Scott committed
314 315


Scott committed
316 317 318
	/**
	 * Call to log in a user based on an external identity provider $source with external $identifier
	 * A new user is created based on $fields if it's a new combination of $source and $identifier
319 320 321
	 * @param string $source
	 * @param string $identifier
	 * @param array $fields
Scott committed
322 323 324 325 326
	 * @return mixed
	 */
	function qa_log_in_external_user($source, $identifier, $fields)
	{
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
327

Scott committed
328
		require_once QA_INCLUDE_DIR . 'db/users.php';
Scott committed
329

Scott committed
330 331
		$users = qa_db_user_login_find($source, $identifier);
		$countusers = count($users);
Scott committed
332

Scott committed
333 334
		if ($countusers > 1)
			qa_fatal_error('External login mapped to more than one user'); // should never happen
Scott committed
335

Scott committed
336 337
		if ($countusers) // user exists so log them in
			qa_set_logged_in_user($users[0]['userid'], $users[0]['handle'], false, $source);
Scott committed
338

Scott committed
339 340
		else { // create and log in user
			require_once QA_INCLUDE_DIR . 'app/users-edit.php';
Scott committed
341

Scott committed
342
			qa_db_user_login_sync(true);
Scott committed
343

Scott committed
344
			$users = qa_db_user_login_find($source, $identifier); // check again after table is locked
Scott committed
345

Scott committed
346 347 348
			if (count($users) == 1) {
				qa_db_user_login_sync(false);
				qa_set_logged_in_user($users[0]['userid'], $users[0]['handle'], false, $source);
Scott committed
349

Scott committed
350 351 352 353 354 355 356 357 358
			} else {
				$handle = qa_handle_make_valid(@$fields['handle']);

				if (strlen(@$fields['email'])) { // remove email address if it will cause a duplicate
					$emailusers = qa_db_user_find_by_email($fields['email']);
					if (count($emailusers)) {
						qa_redirect('login', array('e' => $fields['email'], 'ee' => '1'));
						unset($fields['email']);
						unset($fields['confirmed']);
Scott committed
359 360 361
					}
				}

Scott committed
362 363
				$userid = qa_create_new_user((string)@$fields['email'], null /* no password */, $handle,
					isset($fields['level']) ? $fields['level'] : QA_USER_LEVEL_BASIC, @$fields['confirmed']);
Scott committed
364

Scott committed
365 366
				qa_db_user_login_add($userid, $source, $identifier);
				qa_db_user_login_sync(false);
Scott committed
367

Scott committed
368
				$profilefields = array('name', 'location', 'website', 'about');
Scott committed
369

Scott committed
370 371 372
				foreach ($profilefields as $fieldname) {
					if (strlen(@$fields[$fieldname]))
						qa_db_user_profile_set($userid, $fieldname, $fields[$fieldname]);
Scott committed
373 374
				}

Scott committed
375 376
				if (strlen(@$fields['avatar']))
					qa_set_user_avatar($userid, $fields['avatar']);
Scott committed
377

Scott committed
378
				qa_set_logged_in_user($userid, $handle, false, $source);
Scott committed
379
			}
380
		}
Scott committed
381
	}
382 383


Scott committed
384 385 386 387 388 389
	/**
	 * Return the userid of the currently logged in user, or null if none logged in
	 */
	function qa_get_logged_in_userid()
	{
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
390

Scott committed
391
		global $qa_logged_in_userid_checked;
Scott committed
392

Scott committed
393
		$suffix = qa_session_var_suffix();
Scott committed
394

Scott committed
395 396
		if (!$qa_logged_in_userid_checked) { // only check once
			qa_start_session(); // this will load logged in userid from the native PHP session, but that's not enough
Scott committed
397

Scott committed
398
			$sessionuserid = @$_SESSION['qa_session_userid_' . $suffix];
Scott committed
399

Scott committed
400 401 402
			if (isset($sessionuserid)) // check verify code matches
				if (!hash_equals(qa_session_verify_code($sessionuserid), @$_SESSION['qa_session_verify_' . $suffix]))
					qa_clear_session_user();
Scott committed
403

Scott committed
404 405
			if (!empty($_COOKIE['qa_session'])) {
				@list($handle, $sessioncode, $remember) = explode('/', $_COOKIE['qa_session']);
Scott committed
406

Scott committed
407 408
				if ($remember)
					qa_set_session_cookie($handle, $sessioncode, $remember); // extend 'remember me' cookies each time
Scott committed
409

Scott committed
410
				$sessioncode = trim($sessioncode); // trim to prevent passing in blank values to match uninitiated DB rows
pupi1985 committed
411

Scott committed
412
				// Try to recover session from the database if PHP session has timed out
Scott committed
413
				if (!isset($_SESSION['qa_session_userid_' . $suffix]) && !empty($handle) && !empty($sessioncode)) {
Scott committed
414
					require_once QA_INCLUDE_DIR . 'db/selects.php';
pupi1985 committed
415

Scott committed
416
					$userinfo = qa_db_single_select(qa_db_user_account_selectspec($handle, false)); // don't get any pending
pupi1985 committed
417

Scott committed
418 419 420 421 422
					if (strtolower(trim($userinfo['sessioncode'])) == strtolower($sessioncode))
						qa_set_session_user($userinfo['userid'], $userinfo['sessionsource']);
					else
						qa_clear_session_cookie(); // if cookie not valid, remove it to save future checks
				}
pupi1985 committed
423 424
			}

Scott committed
425
			$qa_logged_in_userid_checked = true;
Scott committed
426 427
		}

Scott committed
428 429
		return @$_SESSION['qa_session_userid_' . $suffix];
	}
Scott committed
430

pupi1985 committed
431

Scott committed
432 433 434 435 436 437
	/**
	 * Get the source of the currently logged in user, from call to qa_log_in_external_user() or null if logged in normally
	 */
	function qa_get_logged_in_source()
	{
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
pupi1985 committed
438

Scott committed
439 440
		$userid = qa_get_logged_in_userid();
		$suffix = qa_session_var_suffix();
pupi1985 committed
441

Scott committed
442 443 444
		if (isset($userid))
			return @$_SESSION['qa_session_source_' . $suffix];
	}
pupi1985 committed
445 446


Scott committed
447 448 449 450 451 452
	/**
	 * Return array of information about the currently logged in user, cache to ensure only one call to external code
	 */
	function qa_get_logged_in_user_cache()
	{
		global $qa_cached_logged_in_user;
pupi1985 committed
453

Scott committed
454 455
		if (!isset($qa_cached_logged_in_user)) {
			$userid = qa_get_logged_in_userid();
pupi1985 committed
456

Scott committed
457 458 459
			if (isset($userid)) {
				require_once QA_INCLUDE_DIR . 'db/selects.php';
				$qa_cached_logged_in_user = qa_db_get_pending_result('loggedinuser', qa_db_user_account_selectspec($userid, true));
pupi1985 committed
460

461 462 463 464 465 466 467 468 469 470 471
				// If the site is configured to share the ^users table then there might not be a record in the
				// ^userpoints table so this creates it
				if ($qa_cached_logged_in_user['points'] === null) {
					require_once QA_INCLUDE_DIR . 'db/points.php';
					require_once QA_INCLUDE_DIR . 'db/users.php';

					qa_db_points_update_ifuser($userid, null);
					qa_db_uapprovecount_update();
					$qa_cached_logged_in_user = qa_db_single_select(qa_db_user_account_selectspec($userid, true));
				}

Scott committed
472 473 474 475 476
				if (!isset($qa_cached_logged_in_user)) {
					// the user can no longer be found (should only apply to deleted users)
					qa_clear_session_user();
					qa_redirect(''); // implicit exit;
				}
pupi1985 committed
477
			}
Scott committed
478 479
		}

Scott committed
480
		return $qa_cached_logged_in_user;
Scott committed
481 482 483
	}


Scott committed
484 485
	/**
	 * Return $field of the currently logged in user
486 487
	 * @param string $field
	 * @return string|null
Scott committed
488 489
	 */
	function qa_get_logged_in_user_field($field)
Scott committed
490
	{
Scott committed
491
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
492

Scott committed
493
		$usercache = qa_get_logged_in_user_cache();
Scott committed
494

Scott committed
495
		return isset($usercache[$field]) ? $usercache[$field] : null;
Scott committed
496 497 498
	}


Scott committed
499 500 501 502
	/**
	 * Return the number of points of the currently logged in user, or null if none is logged in
	 */
	function qa_get_logged_in_points()
Scott committed
503
	{
Scott committed
504 505 506
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

		return qa_get_logged_in_user_field('points');
Scott committed
507 508 509
	}


Scott committed
510 511 512 513
	/**
	 * Return column type to use for users (if not using single sign-on integration)
	 */
	function qa_get_mysql_user_column_type()
Scott committed
514
	{
Scott committed
515
		return 'INT UNSIGNED';
Scott committed
516 517 518
	}


Scott committed
519 520 521 522
	/**
	 * Return the URL to the $blobId with a stored size of $width and $height.
	 * Constrain the image to $size (width AND height)
	 *
523
	 * @since 1.8.0
Scott committed
524 525 526 527 528 529 530
	 * @param string $blobId The blob ID from the image
	 * @param int|null $size The resulting image's size. If omitted the original image size will be used. If the
	 * size is present it must be greater than 0
	 * @param bool $absolute Whether the link returned should be absolute or relative
	 * @return string|null The URL to the avatar or null if the $blobId was empty or the $size not valid
	 */
	function qa_get_avatar_blob_url($blobId, $size = null, $absolute = false)
Scott committed
531
	{
Scott committed
532
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
533

Scott committed
534
		require_once QA_INCLUDE_DIR . 'util/image.php';
Scott committed
535

536
		if (strlen($blobId) == 0 || (isset($size) && $size <= 0)) {
Scott committed
537 538
			return null;
		}
Scott committed
539

Scott committed
540 541 542
		$params = array('qa_blobid' => $blobId);
		if (isset($size)) {
			$params['qa_size'] = $size;
Scott committed
543 544
		}

Scott committed
545
		$rootUrl = $absolute ? qa_opt('site_url') : null;
Scott committed
546

Scott committed
547
		return qa_path('image', $params, $rootUrl, QA_URL_FORMAT_PARAMS);
Scott committed
548 549 550
	}


Scott committed
551 552 553 554 555 556 557 558
	/**
	 * Get HTML to display a username, linked to their user page.
	 * @param string $handle  The username.
	 * @param bool $microdata  Whether to include microdata.
	 * @param bool $favorited  Show the user as favorited.
	 * @return string  The user HTML.
	 */
	function qa_get_one_user_html($handle, $microdata = false, $favorited = false)
Scott committed
559
	{
Scott committed
560
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
561

562 563 564
		if (strlen($handle) === 0) {
			return qa_lang('main/anonymous');
		}
Scott committed
565

Scott committed
566 567
		$url = qa_path_html('user/' . $handle);
		$favclass = $favorited ? ' qa-user-favorited' : '';
568
		$mfAttr = $microdata ? ' itemprop="url"' : '';
Scott committed
569

570 571 572 573
		$userHandle = $microdata ? '<span itemprop="name">' . qa_html($handle) . '</span>' : qa_html($handle);
		$userHtml = '<a href="' . $url . '" class="qa-user-link' . $favclass . '"' . $mfAttr . '>' . $userHandle . '</a>';

		if ($microdata) {
Scott committed
574
			$userHtml = '<span itemprop="author" itemscope itemtype="https://schema.org/Person">' . $userHtml . '</span>';
575 576 577
		}

		return $userHtml;
Scott committed
578
	}
Scott committed
579 580


Scott committed
581 582 583 584 585 586
	/**
	 * Return where the avatar will be fetched from for the given user flags. The possible return values are
	 * 'gravatar' for an avatar that will be fetched from Gravatar, 'local-user' for an avatar fetched locally from
	 * the user's profile, 'local-default' for an avatar fetched locally from the default avatar blob ID, and NULL
	 * if the avatar could not be fetched from any of these sources
	 *
587
	 * @since 1.8.0
Scott committed
588 589 590 591 592 593
	 * @param int $flags The user's flags
	 * @param string|null $email The user's email
	 * @param string|null $blobId The blob ID for a locally stored avatar.
	 * @return string|null The source of the avatar: 'gravatar', 'local-user', 'local-default' and null
	 */
	function qa_get_user_avatar_source($flags, $email, $blobId)
Scott committed
594
	{
Scott committed
595
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
596

Scott committed
597 598 599 600 601 602 603 604
		if (qa_opt('avatar_allow_gravatar') && (($flags & QA_USER_FLAGS_SHOW_GRAVATAR) > 0) && isset($email)) {
			return 'gravatar';
		} elseif (qa_opt('avatar_allow_upload') && (($flags & QA_USER_FLAGS_SHOW_AVATAR) > 0) && isset($blobId)) {
			return 'local-user';
		} elseif ((qa_opt('avatar_allow_gravatar') || qa_opt('avatar_allow_upload')) && qa_opt('avatar_default_show') && strlen(qa_opt('avatar_default_blobid') > 0)) {
			return 'local-default';
		} else {
			return null;
Scott committed
605 606 607 608
		}
	}


Scott committed
609 610 611 612 613
	/**
	 * Return the avatar URL, either Gravatar or from a blob ID, constrained to $size pixels.
	 * @param int $flags The user's flags
	 * @param string $email The user's email. Only needed to return the Gravatar link
	 * @param string $blobId The blob ID. Only needed to return the locally stored avatar
614
	 * @param int|null $size The size to constrain the final image
Scott committed
615
	 * @param bool $absolute Whether the link returned should be absolute or relative
616
	 * @return string|null The URL to the user's avatar or null if none could be found (not even as a default site avatar)
Scott committed
617 618
	 */
	function qa_get_user_avatar_url($flags, $email, $blobId, $size = null, $absolute = false)
Scott committed
619 620 621
	{
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

Scott committed
622
		$avatarSource = qa_get_user_avatar_source($flags, $email, $blobId);
Scott committed
623

Scott committed
624 625 626 627 628 629 630 631 632 633 634
		switch ($avatarSource) {
			case 'gravatar':
				return qa_get_gravatar_url($email, $size);
			case 'local-user':
				return qa_get_avatar_blob_url($blobId, $size, $absolute);
			case 'local-default':
				return qa_get_avatar_blob_url(qa_opt('avatar_default_blobid'), $size, $absolute);
			default: // NULL
				return null;
		}
	}
Scott committed
635 636


Scott committed
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
	/**
	 * Return HTML to display for the user's avatar, constrained to $size pixels, with optional $padding to that size
	 * @param int $flags The user's flags
	 * @param string $email The user's email. Only needed to return the Gravatar HTML
	 * @param string $blobId The blob ID. Only needed to return the locally stored avatar HTML
	 * @param string $handle The handle of the user that the avatar will link to
	 * @param int $width The width to constrain the image
	 * @param int $height The height to constrain the image
	 * @param int $size The size to constrain the final image
	 * @param bool $padding HTML padding to add to the image
	 * @return string|null The HTML to the user's avatar or null if no valid source for the avatar could be found
	 */
	function qa_get_user_avatar_html($flags, $email, $handle, $blobId, $width, $height, $size, $padding = false)
	{
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

		require_once QA_INCLUDE_DIR . 'app/format.php';
Scott committed
654

Scott committed
655 656 657 658 659 660 661 662 663 664 665
		$avatarSource = qa_get_user_avatar_source($flags, $email, $blobId);

		switch ($avatarSource) {
			case 'gravatar':
				$html = qa_get_gravatar_html($email, $size);
				break;
			case 'local-user':
				$html = qa_get_avatar_blob_html($blobId, $width, $height, $size, $padding);
				break;
			case 'local-default':
				$html = qa_get_avatar_blob_html(qa_opt('avatar_default_blobid'), qa_opt('avatar_default_width'), qa_opt('avatar_default_height'), $size, $padding);
666 667 668
				if (strlen($handle) == 0) {
					return $html;
				}
Scott committed
669 670 671
				break;
			default: // NULL
				return null;
Scott committed
672 673
		}

Scott committed
674
		return sprintf('<a href="%s" class="qa-avatar-link">%s</a>', qa_path_html('user/' . $handle), $html);
Scott committed
675 676 677
	}


Scott committed
678 679
	/**
	 * Return email address for user $userid (if not using single sign-on integration)
680
	 * @param int $userid
681
	 * @return string
Scott committed
682 683
	 */
	function qa_get_user_email($userid)
Scott committed
684
	{
Scott committed
685
		$userinfo = qa_db_select_with_pending(qa_db_user_account_selectspec($userid, true));
Scott committed
686

Scott committed
687
		return $userinfo['email'];
Scott committed
688 689 690
	}


Scott committed
691 692
	/**
	 * Called after a database write $action performed by a user $userid
693 694
	 * @param int $userid
	 * @param string $action
Scott committed
695 696 697
	 * @return mixed
	 */
	function qa_user_report_action($userid, $action)
Scott committed
698 699 700
	{
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

Scott committed
701
		require_once QA_INCLUDE_DIR . 'db/users.php';
Scott committed
702

Scott committed
703
		qa_db_user_written($userid, qa_remote_ip_address());
Scott committed
704 705 706
	}


Scott committed
707 708
	/**
	 * Return textual representation of the user $level
709 710
	 * @param int $level
	 * @return string
Scott committed
711 712
	 */
	function qa_user_level_string($level)
Scott committed
713
	{
Scott committed
714
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
715

Scott committed
716 717 718 719 720 721 722 723 724 725 726 727 728 729
		if ($level >= QA_USER_LEVEL_SUPER)
			$string = 'users/level_super';
		elseif ($level >= QA_USER_LEVEL_ADMIN)
			$string = 'users/level_admin';
		elseif ($level >= QA_USER_LEVEL_MODERATOR)
			$string = 'users/level_moderator';
		elseif ($level >= QA_USER_LEVEL_EDITOR)
			$string = 'users/level_editor';
		elseif ($level >= QA_USER_LEVEL_EXPERT)
			$string = 'users/level_expert';
		elseif ($level >= QA_USER_LEVEL_APPROVED)
			$string = 'users/approved_user';
		else
			$string = 'users/registered_user';
Scott committed
730

Scott committed
731
		return qa_lang($string);
Scott committed
732 733 734
	}


735
	/**
Scott committed
736
	 * Return an array of links to login, register, email confirm and logout pages (if not using single sign-on integration)
737 738
	 * @param string $rooturl
	 * @param string|null $tourl
Scott committed
739
	 * @return array
740
	 */
Scott committed
741
	function qa_get_login_links($rooturl, $tourl)
Scott committed
742
	{
Scott committed
743 744 745 746 747 748 749
		return array(
			'login' => qa_path('login', isset($tourl) ? array('to' => $tourl) : null, $rooturl),
			'register' => qa_path('register', isset($tourl) ? array('to' => $tourl) : null, $rooturl),
			'confirm' => qa_path('confirm', null, $rooturl),
			'logout' => qa_path('logout', null, $rooturl),
		);
	}
Scott committed
750

Scott committed
751 752 753 754 755
} // end of: if (QA_FINAL_EXTERNAL_USERS) { ... } else { ... }


/**
 * Return whether someone is logged in at the moment
756
 * @return bool
Scott committed
757 758 759 760 761 762 763 764 765 766
 */
function qa_is_logged_in()
{
	$userid = qa_get_logged_in_userid();
	return isset($userid);
}


/**
 * Return displayable handle/username of currently logged in user, or null if none
767
 * @return string
Scott committed
768 769 770 771 772 773 774 775 776
 */
function qa_get_logged_in_handle()
{
	return qa_get_logged_in_user_field(QA_FINAL_EXTERNAL_USERS ? 'publicusername' : 'handle');
}


/**
 * Return email of currently logged in user, or null if none
777
 * @return string
Scott committed
778 779 780 781 782 783 784 785 786
 */
function qa_get_logged_in_email()
{
	return qa_get_logged_in_user_field('email');
}


/**
 * Return level of currently logged in user, or null if none
787
 * @return string
Scott committed
788 789 790 791 792 793 794 795 796
 */
function qa_get_logged_in_level()
{
	return qa_get_logged_in_user_field('level');
}


/**
 * Return flags (see QA_USER_FLAGS_*) of currently logged in user, or null if none
797
 * @return string
Scott committed
798 799 800 801 802 803 804 805 806 807 808 809
 */
function qa_get_logged_in_flags()
{
	if (QA_FINAL_EXTERNAL_USERS)
		return qa_get_logged_in_user_field('blocked') ? QA_USER_FLAGS_USER_BLOCKED : 0;
	else
		return qa_get_logged_in_user_field('flags');
}


/**
 * Return an array of all the specific (e.g. per category) level privileges for the logged in user, retrieving from the database if necessary
810
 * @return array
Scott committed
811 812 813 814 815 816 817 818 819 820 821
 */
function qa_get_logged_in_levels()
{
	require_once QA_INCLUDE_DIR . 'db/selects.php';

	return qa_db_get_pending_result('userlevels', qa_db_user_levels_selectspec(qa_get_logged_in_userid(), true));
}


/**
 * Return an array mapping each userid in $userids to that user's handle (public username), or to null if not found
822
 * @param array $userids
Scott committed
823 824 825 826 827 828 829 830 831 832 833
 * @return array
 */
function qa_userids_to_handles($userids)
{
	if (QA_FINAL_EXTERNAL_USERS)
		$rawuseridhandles = qa_get_public_from_userids($userids);

	else {
		require_once QA_INCLUDE_DIR . 'db/users.php';
		$rawuseridhandles = qa_db_user_get_userid_handles($userids);
	}
834

Scott committed
835 836 837 838 839 840 841 842 843 844
	$gotuseridhandles = array();
	foreach ($userids as $userid)
		$gotuseridhandles[$userid] = @$rawuseridhandles[$userid];

	return $gotuseridhandles;
}


/**
 * Return an string mapping the received userid to that user's handle (public username), or to null if not found
845
 * @param array $userid
Scott committed
846 847 848 849 850 851 852 853 854 855 856 857 858
 * @return mixed|null
 */
function qa_userid_to_handle($userid)
{
	$handles = qa_userids_to_handles(array($userid));
	return empty($handles) ? null : $handles[$userid];
}


/**
 * Return an array mapping each handle in $handles the user's userid, or null if not found. If $exactonly is true then
 * $handles must have the correct case and accents. Otherwise, handles are case- and accent-insensitive, and the keys
 * of the returned array will match the $handles provided, not necessary those in the DB.
859
 * @param array $handles
Scott committed
860 861 862 863 864 865 866 867 868 869 870 871 872 873
 * @param bool $exactonly
 * @return array
 */
function qa_handles_to_userids($handles, $exactonly = false)
{
	require_once QA_INCLUDE_DIR . 'util/string.php';

	if (QA_FINAL_EXTERNAL_USERS)
		$rawhandleuserids = qa_get_userids_from_public($handles);

	else {
		require_once QA_INCLUDE_DIR . 'db/users.php';
		$rawhandleuserids = qa_db_user_get_handle_userids($handles);
	}
874

Scott committed
875
	$gothandleuserids = array();
Scott committed
876

Scott committed
877 878 879
	if ($exactonly) { // only take the exact matches
		foreach ($handles as $handle)
			$gothandleuserids[$handle] = @$rawhandleuserids[$handle];
Scott committed
880

Scott committed
881 882 883 884
	} else { // normalize to lowercase without accents, and then find matches
		$normhandleuserids = array();
		foreach ($rawhandleuserids as $handle => $userid)
			$normhandleuserids[qa_string_remove_accents(qa_strtolower($handle))] = $userid;
Scott committed
885

Scott committed
886 887 888
		foreach ($handles as $handle)
			$gothandleuserids[$handle] = @$normhandleuserids[qa_string_remove_accents(qa_strtolower($handle))];
	}
Scott committed
889

Scott committed
890 891
	return $gothandleuserids;
}
Scott committed
892 893


Scott committed
894 895
/**
 * Return the userid corresponding to $handle (not case- or accent-sensitive)
896
 * @param string $handle
Scott committed
897 898 899 900 901 902
 * @return mixed|null
 */
function qa_handle_to_userid($handle)
{
	if (QA_FINAL_EXTERNAL_USERS)
		$handleuserids = qa_get_userids_from_public(array($handle));
Scott committed
903

Scott committed
904 905 906
	else {
		require_once QA_INCLUDE_DIR . 'db/users.php';
		$handleuserids = qa_db_user_get_handle_userids(array($handle));
Scott committed
907 908
	}

Scott committed
909 910
	if (count($handleuserids) == 1)
		return reset($handleuserids); // don't use $handleuserids[$handle] since capitalization might be different
Scott committed
911

Scott committed
912 913
	return null;
}
Scott committed
914 915


Scott committed
916 917
/**
 * Return the level of the logged in user for a post with $categoryids (expressing the full hierarchy to the final category)
918
 * @param array $categoryids
Scott committed
919 920 921 922 923
 * @return mixed|null
 */
function qa_user_level_for_categories($categoryids)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
924

Scott committed
925
	require_once QA_INCLUDE_DIR . 'app/updates.php';
Scott committed
926

Scott committed
927
	$level = qa_get_logged_in_level();
Scott committed
928

Scott committed
929 930
	if (count($categoryids)) {
		$userlevels = qa_get_logged_in_levels();
Scott committed
931

Scott committed
932 933 934 935
		$categorylevels = array(); // create a map
		foreach ($userlevels as $userlevel) {
			if ($userlevel['entitytype'] == QA_ENTITY_CATEGORY)
				$categorylevels[$userlevel['entityid']] = $userlevel['level'];
936
		}
Scott committed
937

Scott committed
938 939 940
		foreach ($categoryids as $categoryid) {
			$level = max($level, @$categorylevels[$categoryid]);
		}
Scott committed
941 942
	}

Scott committed
943 944
	return $level;
}
Scott committed
945 946


Scott committed
947 948
/**
 * Return the level of the logged in user for $post, as retrieved from the database
949 950
 * @param array $post
 * @return int|null
Scott committed
951 952 953 954
 */
function qa_user_level_for_post($post)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
955

Scott committed
956 957
	if (strlen(@$post['categoryids']))
		return qa_user_level_for_categories(explode(',', $post['categoryids']));
Scott committed
958

Scott committed
959 960
	return null;
}
Scott committed
961 962


Scott committed
963 964
/**
 * Return the maximum possible level of the logged in user in any context (i.e. for any category)
965
 * @return int
Scott committed
966 967 968 969
 */
function qa_user_level_maximum()
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
970

Scott committed
971
	$level = qa_get_logged_in_level();
Scott committed
972

Scott committed
973 974 975
	$userlevels = qa_get_logged_in_levels();
	foreach ($userlevels as $userlevel) {
		$level = max($level, $userlevel['level']);
Scott committed
976 977
	}

Scott committed
978 979 980 981 982 983 984
	return $level;
}


/**
 * Check whether the logged in user has permission to perform $permitoption on post $post (from the database)
 * Other parameters and the return value are as for qa_user_permit_error(...)
985 986 987
 * @param string $permitoption
 * @param array $post
 * @param string|null $limitaction
Scott committed
988 989 990 991 992 993 994 995 996 997 998 999
 * @param bool $checkblocks
 * @return bool|string
 */
function qa_user_post_permit_error($permitoption, $post, $limitaction = null, $checkblocks = true)
{
	return qa_user_permit_error($permitoption, $limitaction, qa_user_level_for_post($post), $checkblocks);
}


/**
 * Check whether the logged in user would have permittion to perform $permitoption in any context (i.e. for any category)
 * Other parameters and the return value are as for qa_user_permit_error(...)
1000 1001
 * @param string $permitoption
 * @param string|null $limitaction
Scott committed
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
 * @param bool $checkblocks
 * @return bool|string
 */
function qa_user_maximum_permit_error($permitoption, $limitaction = null, $checkblocks = true)
{
	return qa_user_permit_error($permitoption, $limitaction, qa_user_level_maximum(), $checkblocks);
}


/**
 * Check whether the logged in user has permission to perform an action.
1013 1014 1015
 * @param string|null $permitoption The permission to check (if null, this simply checks whether the user is blocked).
 * @param string|null $limitaction Constant from /qa-include/app/limits.php to check against user or IP rate limits.
 * @param int|null $userlevel A QA_USER_LEVEL_* constant to consider the user at a different level to usual (e.g. if
Scott committed
1016 1017
 *   they are performing this action in a category for which they have elevated privileges).
 * @param bool $checkblocks Whether to check the user's blocked status.
1018
 * @param array|null $userfields Cache for logged in user, containing keys 'userid', 'level' (optional), 'flags'.
Scott committed
1019 1020 1021 1022 1023 1024
 * @return bool|string The permission error, or false if no error. Possible errors, in order of priority:
 *   'login' => the user should login or register
 *   'level' => a special privilege level (e.g. expert) or minimum number of points is required
 *   'userblock' => the user has been blocked
 *   'ipblock' => the ip address has been blocked
 *   'confirm' => the user should confirm their email address
1025
 *   'approve' => the user needs to be approved by the site admins (no longer used as global permission)
Scott committed
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
 *   'limit' => the user or IP address has reached a rate limit (if $limitaction specified)
 *   false => the operation can go ahead
 */
function qa_user_permit_error($permitoption = null, $limitaction = null, $userlevel = null, $checkblocks = true, $userfields = null)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	require_once QA_INCLUDE_DIR . 'app/limits.php';

	if (!isset($userfields))
		$userfields = qa_get_logged_in_user_cache();

	$userid = isset($userfields['userid']) ? $userfields['userid'] : null;

	if (!isset($userlevel))
		$userlevel = isset($userfields['level']) ? $userfields['level'] : null;

	$flags = isset($userfields['flags']) ? $userfields['flags'] : null;
	if (!$checkblocks)
		$flags &= ~QA_USER_FLAGS_USER_BLOCKED;

	$error = qa_permit_error($permitoption, $userid, $userlevel, $flags);

	if ($checkblocks && !$error && qa_is_ip_blocked())
		$error = 'ipblock';

	if (!$error && isset($userid) && ($flags & QA_USER_FLAGS_MUST_CONFIRM) && qa_opt('confirm_user_emails'))
		$error = 'confirm';

	if (isset($limitaction) && !$error) {
		if (qa_user_limits_remaining($limitaction) <= 0)
			$error = 'limit';
	}
Scott committed
1059

Scott committed
1060 1061 1062 1063 1064 1065
	return $error;
}


/**
 * Check whether user can perform $permitoption. Result as for qa_user_permit_error(...).
1066 1067 1068 1069 1070
 * @param string|null $permitoption Permission option name (from database) for action.
 * @param int|null $userid ID of user (null for no user).
 * @param int|null $userlevel Level to check against.
 * @param int|null $userflags Flags for this user.
 * @param int|null $userpoints User's points: if $userid is currently logged in, you can set $userpoints=null to retrieve them only if necessary.
Scott committed
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
 * @return string|bool Reason the user is not permitted, or false if the operation can go ahead.
 */
function qa_permit_error($permitoption, $userid, $userlevel, $userflags, $userpoints = null)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	$permit = isset($permitoption) ? qa_opt($permitoption) : QA_PERMIT_ALL;

	if (isset($userid) && ($permit == QA_PERMIT_POINTS || $permit == QA_PERMIT_POINTS_CONFIRMED || $permit == QA_PERMIT_APPROVED_POINTS)) {
		// deal with points threshold by converting as appropriate

		if (!isset($userpoints) && $userid == qa_get_logged_in_userid())
			$userpoints = qa_get_logged_in_points(); // allow late retrieval of points (to avoid unnecessary DB query when using external users)

		if ($userpoints >= qa_opt($permitoption . '_points')) {
			$permit = $permit == QA_PERMIT_APPROVED_POINTS
				? QA_PERMIT_APPROVED
				: ($permit == QA_PERMIT_POINTS_CONFIRMED ? QA_PERMIT_CONFIRMED : QA_PERMIT_USERS); // convert if user has enough points
		} else
			$permit = QA_PERMIT_EXPERTS; // otherwise show a generic message so they're not tempted to collect points just for this
	}
Scott committed
1092

Scott committed
1093 1094 1095 1096 1097 1098 1099
	return qa_permit_value_error($permit, $userid, $userlevel, $userflags);
}


/**
 * Check whether user can reach the permission level. Result as for qa_user_permit_error(...).
 * @param int $permit Permission constant.
1100 1101 1102
 * @param int|null $userid ID of user (null for no user).
 * @param int|null $userlevel Level to check against.
 * @param int|null $userflags Flags for this user.
Scott committed
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
 * @return string|bool Reason the user is not permitted, or false if the operation can go ahead
 */
function qa_permit_value_error($permit, $userid, $userlevel, $userflags)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	if (!isset($userid) && $permit < QA_PERMIT_ALL)
		return 'login';

	$levelError =
		($permit <= QA_PERMIT_SUPERS && $userlevel < QA_USER_LEVEL_SUPER) ||
		($permit <= QA_PERMIT_ADMINS && $userlevel < QA_USER_LEVEL_ADMIN) ||
		($permit <= QA_PERMIT_MODERATORS && $userlevel < QA_USER_LEVEL_MODERATOR) ||
		($permit <= QA_PERMIT_EDITORS && $userlevel < QA_USER_LEVEL_EDITOR) ||
		($permit <= QA_PERMIT_EXPERTS && $userlevel < QA_USER_LEVEL_EXPERT);

	if ($levelError)
		return 'level';

	if (isset($userid) && ($userflags & QA_USER_FLAGS_USER_BLOCKED))
		return 'userblock';

	if ($permit >= QA_PERMIT_USERS)
		return false;
Scott committed
1127

Scott committed
1128 1129
	if ($permit >= QA_PERMIT_CONFIRMED) {
		$confirmed = ($userflags & QA_USER_FLAGS_EMAIL_CONFIRMED);
1130 1131
		// not currently supported by single sign-on integration; approved users and above don't need confirmation
		if (!QA_FINAL_EXTERNAL_USERS && qa_opt('confirm_user_emails') && $userlevel < QA_USER_LEVEL_APPROVED && !$confirmed) {
Scott committed
1132
			return 'confirm';
1133
		}
Scott committed
1134
	} elseif ($permit >= QA_PERMIT_APPROVED) {
1135 1136
		// check user is approved, only if we require it
		if (qa_opt('moderate_users') && $userlevel < QA_USER_LEVEL_APPROVED) {
Scott committed
1137
			return 'approve';
1138
		}
Scott committed
1139 1140
	}

Scott committed
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
	return false;
}


/**
 * Return whether a captcha is required for posts submitted by the current user. You can pass in a QA_USER_LEVEL_*
 * constant in $userlevel to consider the user at a different level to usual (e.g. if they are performing this action
 * in a category for which they have elevated privileges).
 *
 * Possible results:
 * 'login' => captcha required because the user is not logged in
 * 'approve' => captcha required because the user has not been approved
 * 'confirm' => captcha required because the user has not confirmed their email address
 * false => captcha is not required
1155 1156
 * @param int|null $userlevel
 * @return bool|string
Scott committed
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
 */
function qa_user_captcha_reason($userlevel = null)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	$reason = false;
	if (!isset($userlevel))
		$userlevel = qa_get_logged_in_level();

	if ($userlevel < QA_USER_LEVEL_APPROVED) { // approved users and above aren't shown captchas
		$userid = qa_get_logged_in_userid();

		if (qa_opt('captcha_on_anon_post') && !isset($userid))
			$reason = 'login';
		elseif (qa_opt('moderate_users') && qa_opt('captcha_on_unapproved'))
			$reason = 'approve';
		elseif (qa_opt('confirm_user_emails') && qa_opt('captcha_on_unconfirmed') && !(qa_get_logged_in_flags() & QA_USER_FLAGS_EMAIL_CONFIRMED))
			$reason = 'confirm';
	}
Scott committed
1176

Scott committed
1177 1178 1179 1180 1181 1182 1183
	return $reason;
}


/**
 * Return whether a captcha should be presented to the logged in user for writing posts. You can pass in a
 * QA_USER_LEVEL_* constant in $userlevel to consider the user at a different level to usual.
1184 1185
 * @param int|null $userlevel
 * @return bool|string
Scott committed
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
 */
function qa_user_use_captcha($userlevel = null)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	return qa_user_captcha_reason($userlevel) != false;
}


/**
 * Return whether moderation is required for posts submitted by the current user. You can pass in a QA_USER_LEVEL_*
 * constant in $userlevel to consider the user at a different level to usual (e.g. if they are performing this action
 * in a category for which they have elevated privileges).
 *
 * Possible results:
 * 'login' => moderation required because the user is not logged in
 * 'approve' => moderation required because the user has not been approved
 * 'confirm' => moderation required because the user has not confirmed their email address
 * 'points' => moderation required because the user has insufficient points
 * false => moderation is not required
1206
 * @param int|null $userlevel
Scott committed
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
 * @return bool|string
 */
function qa_user_moderation_reason($userlevel = null)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	$reason = false;
	if (!isset($userlevel))
		$userlevel = qa_get_logged_in_level();

1217 1218
	if ($userlevel < QA_USER_LEVEL_EXPERT && qa_user_permit_error('permit_moderate')) {
		// experts and above aren't moderated; if the user can approve posts, no point in moderating theirs
Scott committed
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
		$userid = qa_get_logged_in_userid();

		if (isset($userid)) {
			if (qa_opt('moderate_users') && qa_opt('moderate_unapproved') && ($userlevel < QA_USER_LEVEL_APPROVED))
				$reason = 'approve';
			elseif (qa_opt('confirm_user_emails') && qa_opt('moderate_unconfirmed') && !(qa_get_logged_in_flags() & QA_USER_FLAGS_EMAIL_CONFIRMED))
				$reason = 'confirm';
			elseif (qa_opt('moderate_by_points') && (qa_get_logged_in_points() < qa_opt('moderate_points_limit')))
				$reason = 'points';

		} elseif (qa_opt('moderate_anon_post'))
			$reason = 'login';
	}
Scott committed
1232

Scott committed
1233 1234 1235 1236 1237 1238
	return $reason;
}


/**
 * Return the label to display for $userfield as retrieved from the database, using default if no name set
1239
 * @param array $userfield
Scott committed
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
 * @return string
 */
function qa_user_userfield_label($userfield)
{
	if (isset($userfield['content']))
		return $userfield['content'];

	else {
		$defaultlabels = array(
			'name' => 'users/full_name',
			'about' => 'users/about',
			'location' => 'users/location',
			'website' => 'users/website',
		);

		if (isset($defaultlabels[$userfield['title']]))
			return qa_lang($defaultlabels[$userfield['title']]);
Scott committed
1257 1258
	}

Scott committed
1259 1260
	return '';
}
Scott committed
1261 1262


Scott committed
1263 1264
/**
 * Set or extend the cookie in browser of non logged-in users which identifies them for the purposes of form security (anti-CSRF protection)
1265
 * @return mixed
Scott committed
1266 1267 1268 1269
 */
function qa_set_form_security_key()
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1270

Scott committed
1271
	global $qa_form_key_cookie_set;
Scott committed
1272

Scott committed
1273
	if (!qa_is_logged_in() && !@$qa_form_key_cookie_set) {
Scott committed
1274
		$qa_form_key_cookie_set = true;
Scott committed
1275

Scott committed
1276 1277 1278
		if (strlen(@$_COOKIE['qa_key']) != QA_FORM_KEY_LENGTH) {
			require_once QA_INCLUDE_DIR . 'util/string.php';
			$_COOKIE['qa_key'] = qa_random_alphanum(QA_FORM_KEY_LENGTH);
Scott committed
1279 1280
		}

Scott committed
1281
		setcookie('qa_key', $_COOKIE['qa_key'], time() + 2 * QA_FORM_EXPIRY_SECS, '/', QA_COOKIE_DOMAIN, (bool)ini_get('session.cookie_secure'), true); // extend on every page request
Scott committed
1282
	}
Scott committed
1283
}
Scott committed
1284 1285


Scott committed
1286 1287 1288
/**
 * Return the form security (anti-CSRF protection) hash for an $action (any string), that can be performed within
 * QA_FORM_EXPIRY_SECS of $timestamp (in unix seconds) by the current user.
1289 1290 1291
 * @param string $action
 * @param int $timestamp
 * @return string
Scott committed
1292 1293 1294 1295
 */
function qa_calc_form_security_hash($action, $timestamp)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1296

Scott committed
1297
	$salt = qa_opt('form_security_salt');
Scott committed
1298

Scott committed
1299 1300 1301 1302 1303
	if (qa_is_logged_in())
		return sha1($salt . '/' . $action . '/' . $timestamp . '/' . qa_get_logged_in_userid() . '/' . qa_get_logged_in_user_field('passsalt'));
	else
		return sha1($salt . '/' . $action . '/' . $timestamp . '/' . @$_COOKIE['qa_key']); // lower security for non logged in users - code+cookie can be transferred
}
Scott committed
1304 1305


Scott committed
1306 1307 1308
/**
 * Return the full form security (anti-CSRF protection) code for an $action (any string) performed within
 * QA_FORM_EXPIRY_SECS of now by the current user.
1309 1310
 * @param string $action
 * @return string
Scott committed
1311 1312 1313 1314
 */
function qa_get_form_security_code($action)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1315

Scott committed
1316 1317 1318
	qa_set_form_security_key();

	$timestamp = qa_opt('db_time');
Scott committed
1319

Scott committed
1320 1321
	return (int)qa_is_logged_in() . '-' . $timestamp . '-' . qa_calc_form_security_hash($action, $timestamp);
}
Scott committed
1322 1323


Scott committed
1324 1325 1326
/**
 * Return whether $value matches the expected form security (anti-CSRF protection) code for $action (any string) and
 * that the code has not expired (if more than QA_FORM_EXPIRY_SECS have passed). Logs causes for suspicion.
1327 1328
 * @param string $action
 * @param string|null $value
Scott committed
1329 1330 1331 1332 1333
 * @return bool
 */
function qa_check_form_security_code($action, $value)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1334

Scott committed
1335 1336
	$reportproblems = array();
	$silentproblems = array();
Scott committed
1337

Scott committed
1338 1339
	if (!isset($value)) {
		$silentproblems[] = 'code missing';
Scott committed
1340

Scott committed
1341 1342
	} elseif (!strlen($value)) {
		$silentproblems[] = 'code empty';
Scott committed
1343

Scott committed
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
	} else {
		$parts = explode('-', $value);

		if (count($parts) == 3) {
			$loggedin = $parts[0];
			$timestamp = $parts[1];
			$hash = $parts[2];
			$timenow = qa_opt('db_time');

			if ($timestamp > $timenow) {
				$reportproblems[] = 'time ' . ($timestamp - $timenow) . 's in future';
			} elseif ($timestamp < ($timenow - QA_FORM_EXPIRY_SECS)) {
				$silentproblems[] = 'timeout after ' . ($timenow - $timestamp) . 's';
			}
Scott committed
1358

Scott committed
1359 1360 1361 1362 1363 1364 1365
			if (qa_is_logged_in()) {
				if (!$loggedin) {
					$silentproblems[] = 'now logged in';
				}
			} else {
				if ($loggedin) {
					$silentproblems[] = 'now logged out';
Scott committed
1366
				} else {
Scott committed
1367 1368 1369 1370 1371 1372 1373 1374
					$key = @$_COOKIE['qa_key'];

					if (!isset($key)) {
						$silentproblems[] = 'key cookie missing';
					} elseif (!strlen($key)) {
						$silentproblems[] = 'key cookie empty';
					} elseif (strlen($key) != QA_FORM_KEY_LENGTH) {
						$reportproblems[] = 'key cookie ' . $key . ' invalid';
Scott committed
1375 1376
					}
				}
Scott committed
1377
			}
Scott committed
1378

Scott committed
1379 1380 1381 1382 1383
			if (empty($silentproblems) && empty($reportproblems)) {
				if (!hash_equals(strtolower(qa_calc_form_security_hash($action, $timestamp)), strtolower($hash))) {
					$reportproblems[] = 'code mismatch';
				}
			}
Scott committed
1384

Scott committed
1385 1386
		} else {
			$reportproblems[] = 'code ' . $value . ' malformed';
Scott committed
1387 1388 1389
		}
	}

Scott committed
1390 1391 1392 1393 1394 1395 1396 1397 1398
	if (!empty($reportproblems) && QA_DEBUG_PERFORMANCE) {
		@error_log(
			'PHP Question2Answer form security violation for ' . $action .
			' by ' . (qa_is_logged_in() ? ('userid ' . qa_get_logged_in_userid()) : 'anonymous') .
			' (' . implode(', ', array_merge($reportproblems, $silentproblems)) . ')' .
			' on ' . @$_SERVER['REQUEST_URI'] .
			' via ' . @$_SERVER['HTTP_REFERER']
		);
	}
Scott committed
1399

Scott committed
1400 1401
	return (empty($silentproblems) && empty($reportproblems));
}
1402 1403 1404 1405 1406


/**
 * Return the URL for the Gravatar corresponding to $email, constrained to $size
 *
1407
 * @since 1.8.0
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
 * @param string $email The email of the Gravatar to return
 * @param int|null $size The size of the Gravatar to return. If omitted the default size will be used
 * @return string The URL to the Gravatar of the user
 */
function qa_get_gravatar_url($email, $size = null)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	$link = 'https://www.gravatar.com/avatar/%s';

	$params = array(md5(strtolower(trim($email))));

	$size = (int)$size;
	if ($size > 0) {
		$link .= '?s=%d';
		$params[] = $size;
	}

	return vsprintf($link, $params);
}