acctfuncs.inc.php 28.2 KB
Newer Older
1
<?php
2

3
4
5
6
7
8
9
/**
 * Determine if an HTTP request variable is set
 *
 * @param string $name The request variable to test for
 *
 * @return string Return the value of the request variable, otherwise blank
 */
Dan McGee's avatar
Dan McGee committed
10
11
12
13
14
15
16
function in_request($name) {
	if (isset($_REQUEST[$name])) {
		return $_REQUEST[$name];
	}
	return "";
}

17
18
19
20
21
22
23
/**
 * Format the PGP key fingerprint
 *
 * @param string $fingerprint An unformatted PGP key fingerprint
 *
 * @return string PGP fingerprint with spaces every 4 characters
 */
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
function html_format_pgp_fingerprint($fingerprint) {
	if (strlen($fingerprint) != 40 || !ctype_xdigit($fingerprint)) {
		return $fingerprint;
	}

	return htmlspecialchars(substr($fingerprint, 0, 4) . " " .
		substr($fingerprint, 4, 4) . " " .
		substr($fingerprint, 8, 4) . " " .
		substr($fingerprint, 12, 4) . " " .
		substr($fingerprint, 16, 4) . "  " .
		substr($fingerprint, 20, 4) . " " .
		substr($fingerprint, 24, 4) . " " .
		substr($fingerprint, 28, 4) . " " .
		substr($fingerprint, 32, 4) . " " .
		substr($fingerprint, 36, 4) . " ", ENT_QUOTES);
}

41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
 * Loads the account editing form, with any values that are already saved
 *
 * @global array $SUPPORTED_LANGS Languages that are supported by the AUR
 * @param string $UTYPE User type of the account accessing the form
 * @param string $A Form to use, either UpdateAccount or NewAccount
 * @param string $U The username to display
 * @param string $T The account type of the displayed user
 * @param string $S Whether the displayed user has a suspended account
 * @param string $E The e-mail address of the displayed user
 * @param string $P The password value of the displayed user
 * @param string $C The confirmed password value of the displayed user
 * @param string $R The real name of the displayed user
 * @param string $L The language preference of the displayed user
 * @param string $I The IRC nickname of the displayed user
 * @param string $K The PGP key fingerprint of the displayed user
 * @param string $UID The user ID of the displayed user
 *
 * @return void
 */
eric's avatar
eric committed
61
function display_account_form($UTYPE,$A,$U="",$T="",$S="",
62
			$E="",$P="",$C="",$R="",$L="",$I="",$K="",$UID=0) {
63
64
	global $SUPPORTED_LANGS;

65
	include("account_edit_form.php");
66
67
68
	return;
} # function display_account_form()

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
 * Process information given to new/edit account form
 *
 * @global array $SUPPORTED_LANGS Languages that are supported by the AUR
 * @param string $UTYPE The account type of the user modifying the account
 * @param string $TYPE Either "edit" for editing or "new" for registering an account
 * @param string $A Form to use, either UpdateAccount or NewAccount
 * @param string $U The username for the account
 * @param string $T The account type for the user
 * @param string $S Whether or not the account is suspended
 * @param string $E The e-mail address for the user
 * @param string $P The password for the user
 * @param string $C The confirmed password for the user
 * @param string $R The real name of the user
 * @param string $L The language preference of the user
 * @param string $I The IRC nickname of the user
 * @param string $K The PGP fingerprint of the user
 * @param string $UID The user ID of the modified account
 * @param \PDO $dbh An already established database connection
 *
 * @return string|void Return void if successful, otherwise return error
 */
eric's avatar
eric committed
91
function process_account_form($UTYPE,$TYPE,$A,$U="",$T="",$S="",$E="",
92
			$P="",$C="",$R="",$L="",$I="",$K="",$UID=0,$dbh=NULL) {
93
94
95
96

	# error check and process request for a new/modified account
	global $SUPPORTED_LANGS;

97
98
99
	if (!$dbh) {
		$dbh = db_connect();
	}
100

101
	if(isset($_COOKIE['AURSID'])) {
102
		$editor_user = uid_from_sid($_COOKIE['AURSID'], $dbh);
103
104
	}
	else {
105
		$editor_user = null;
106
	}
107

108
	$error = "";
109
	if (empty($E) || empty($U)) {
110
111
		$error = __("Missing a required field.");
	}
112

113
114
115
	if ($TYPE == "new") {
		# they need password fields for this type of action
		#
116
		if (empty($P) || empty($C)) {
117
118
119
120
121
122
123
			$error = __("Missing a required field.");
		}
	} else {
		if (!$UID) {
			$error = __("Missing User ID");
		}
	}
124

125
  if (!$error && !valid_username($U) && !user_is_privileged($editor_user, $dbh))
126
	$error = __("The username is invalid.") . "<ul>\n"
127
			."<li>" . __("It must be between %s and %s characters long",
128
129
			USERNAME_MIN_LEN,  USERNAME_MAX_LEN )
			. "</li>"
130
			. "<li>" . __("Start and end with a letter or number") . "</li>"
131
			. "<li>" . __("Can contain only one period, underscore or hyphen.")
132
133
			. "</li>\n</ul>";

134
135
136
	if (!$error && $P && $C && ($P != $C)) {
		$error = __("Password fields do not match.");
	}
137
	if (!$error && $P != '' && !good_passwd($P))
138
		$error = __("Your password must be at least %s characters.",PASSWD_MIN_LEN);
139

140
141
142
	if (!$error && !valid_email($E)) {
		$error = __("The email address is invalid.");
	}
143
144
145
146
147

	if (!$error && $K != '' && !valid_pgp_fingerprint($K)) {
		$error = __("The PGP key fingerprint is invalid.");
	}

148
149
	if (($UTYPE == "User" && $T > 1) || ($UTYPE == "Trusted User" && $T > 2)) {
		$error = __("Cannot increase account permissions.");
eric's avatar
eric committed
150
	}
151
152
153
154
155
156
157
158
	if (!$error && !array_key_exists($L, $SUPPORTED_LANGS)) {
		$error = __("Language is not currently supported.");
	}
	if (!$error) {
		# check to see if this username is available
		# NOTE: a race condition exists here if we care...
		#
		$q = "SELECT COUNT(*) AS CNT FROM Users ";
canyonknight's avatar
canyonknight committed
159
		$q.= "WHERE Username = " . $dbh->quote($U);
eric's avatar
eric committed
160
161
162
		if ($TYPE == "edit") {
			$q.= " AND ID != ".intval($UID);
		}
canyonknight's avatar
canyonknight committed
163
164
165
166
167
		$result = $dbh->query($q);
		$row = $result->fetch(PDO::FETCH_NUM);

		if ($row[0]) {
			$error = __("The username, %s%s%s, is already in use.",
Lukas Fleischer's avatar
Lukas Fleischer committed
168
				"<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
169
170
171
172
173
174
175
		}
	}
	if (!$error) {
		# check to see if this email address is available
		# NOTE: a race condition exists here if we care...
		#
		$q = "SELECT COUNT(*) AS CNT FROM Users ";
canyonknight's avatar
canyonknight committed
176
		$q.= "WHERE Email = " . $dbh->quote($E);
eric's avatar
eric committed
177
178
179
		if ($TYPE == "edit") {
			$q.= " AND ID != ".intval($UID);
		}
canyonknight's avatar
canyonknight committed
180
181
182
183
184
		$result = $dbh->query($q);
		$row = $result->fetch(PDO::FETCH_NUM);

		if ($row[0]) {
			$error = __("The address, %s%s%s, is already in use.",
Lukas Fleischer's avatar
Lukas Fleischer committed
185
					"<strong>", htmlspecialchars($E,ENT_QUOTES), "</strong>");
186
187
188
189
		}
	}
	if ($error) {
		print "<span class='error'>".$error."</span><br/>\n";
eric's avatar
eric committed
190
		display_account_form($UTYPE, $A, $U, $T, $S, $E, "", "",
191
				$R, $L, $I, $K, $UID);
192
193
194
	} else {
		if ($TYPE == "new") {
			# no errors, go ahead and create the unprivileged user
Denis's avatar
Denis committed
195
196
			$salt = generate_salt();
			$P = salted_hash($P, $salt);
canyonknight's avatar
canyonknight committed
197
198
199
200
201
202
203
204
205
206
207
208
209
			$U = $dbh->quote($U);
			$E = $dbh->quote($E);
			$P = $dbh->quote($P);
			$salt = $dbh->quote($salt);
			$R = $dbh->quote($R);
			$L = $dbh->quote($L);
			$I = $dbh->quote($I);
			$K = $dbh->quote(str_replace(" ", "", $K));
			$q = "INSERT INTO Users (AccountTypeID, Suspended, ";
			$q.= "Username, Email, Passwd, Salt, RealName, ";
			$q.= "LangPreference, IRCNick, PGPKey) VALUES (1, 0, ";
			$q.= "$U, $E, $P, $salt, $R, $L, $I, $K)";
			$result = $dbh->exec($q);
210
			if (!$result) {
canyonknight's avatar
canyonknight committed
211
				print __("Error trying to create account, %s%s%s.",
Lukas Fleischer's avatar
Lukas Fleischer committed
212
						"<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
213
			} else {
214
215
				# account created/modified, tell them so.
				#
216
				print __("The account, %s%s%s, has been successfully created.",
Lukas Fleischer's avatar
Lukas Fleischer committed
217
						"<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
218
				print "<p>\n";
219
				print __("Click on the Login link above to use your account.");
220
221
222
223
224
				print "</p>\n";
			}

		} else {
			# no errors, go ahead and modify the user account
jchu's avatar
jchu committed
225

226
			$q = "UPDATE Users SET ";
canyonknight's avatar
canyonknight committed
227
			$q.= "Username = " . $dbh->quote($U);
eric's avatar
eric committed
228
229
230
231
232
233
234
235
			if ($T) {
				$q.= ", AccountTypeID = ".intval($T);
			}
			if ($S) {
				$q.= ", Suspended = 1";
			} else {
				$q.= ", Suspended = 0";
			}
canyonknight's avatar
canyonknight committed
236
			$q.= ", Email = " . $dbh->quote($E);
eric's avatar
eric committed
237
			if ($P) {
Denis's avatar
Denis committed
238
239
240
				$salt = generate_salt();
				$hash = salted_hash($P, $salt);
				$q .= ", Passwd = '$hash', Salt = '$salt'";
eric's avatar
eric committed
241
			}
canyonknight's avatar
canyonknight committed
242
243
244
245
			$q.= ", RealName = " . $dbh->quote($R);
			$q.= ", LangPreference = " . $dbh->quote($L);
			$q.= ", IRCNick = " . $dbh->quote($I);
			$q.= ", PGPKey = " . $dbh->quote(str_replace(" ", "", $K));
246
			$q.= " WHERE ID = ".intval($UID);
canyonknight's avatar
canyonknight committed
247
			$result = $dbh->exec($q);
248
			if (!$result) {
canyonknight's avatar
canyonknight committed
249
				print __("Error trying to modify account, %s%s%s.",
Lukas Fleischer's avatar
Lukas Fleischer committed
250
						"<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
251
			} else {
252
				print __("The account, %s%s%s, has been successfully modified.",
Lukas Fleischer's avatar
Lukas Fleischer committed
253
						"<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
254
255
256
257
258
259
			}
		}
	}
	return;
}

260
261
262
263
264
/**
 * Include the search accounts form
 *
 * @return void
 */
265
function search_accounts_form() {
266
	include("search_accounts_form.php");
267
268
269
	return;
}

270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/**
 * Display the search results page
 *
 * @param string $UTYPE User type of the account accessing the form
 * @param string $O The offset for the results page
 * @param string $SB The column to sort the results page by
 * @param string $U The username search criteria
 * @param string $T The account type search criteria
 * @param string $S Whether the account is suspended search criteria
 * @param string $E The e-mail address search criteria
 * @param string $R The real name search criteria
 * @param string $I The IRC nickname search criteria
 * @param string $K The PGP key fingerprint search criteria
 * @param \PDO $dbh An already established database connection
 *
 * @return void
 */
eric's avatar
eric committed
287
function search_results_page($UTYPE,$O=0,$SB="",$U="",$T="",
288
		$S="",$E="",$R="",$I="",$K="",$dbh=NULL) {
289
290
291
292
293
294
295
296
297
298
299
300

	$HITS_PER_PAGE = 50;
	if ($O) {
		$OFFSET = intval($O);
	} else {
		$OFFSET = 0;
	}
	if ($OFFSET < 0) {
		$OFFSET = 0;
	}
	$search_vars = array();

canyonknight's avatar
canyonknight committed
301
302
303
304
	if (!$dbh) {
		$dbh = db_connect();
	}

305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
	$q = "SELECT Users.*, AccountTypes.AccountType ";
	$q.= "FROM Users, AccountTypes ";
	$q.= "WHERE AccountTypes.ID = Users.AccountTypeID ";
	if ($T == "u") {
		$q.= "AND AccountTypes.ID = 1 ";
		$search_vars[] = "T";
	} elseif ($T == "t") {
		$q.= "AND AccountTypes.ID = 2 ";
		$search_vars[] = "T";
	} elseif ($T == "d") {
		$q.= "AND AccountTypes.ID = 3 ";
		$search_vars[] = "T";
	}
	if ($S) {
		$q.= "AND Users.Suspended = 1 ";
		$search_vars[] = "S";
	}
	if ($U) {
canyonknight's avatar
canyonknight committed
323
324
		$U = "%" . addcslashes($U, '%_') . "%";
		$q.= "AND Username LIKE " . $dbh->quote($U) . " ";
325
326
327
		$search_vars[] = "U";
	}
	if ($E) {
canyonknight's avatar
canyonknight committed
328
329
		$E = "%" . addcslashes($E, '%_') . "%";
		$q.= "AND Email LIKE " . $dbh->quote($E) . " ";
330
331
332
		$search_vars[] = "E";
	}
	if ($R) {
canyonknight's avatar
canyonknight committed
333
334
		$R = "%" . addcslashes($R, '%_') . "%";
		$q.= "AND RealName LIKE " . $dbh->quote($R) . " ";
335
336
337
		$search_vars[] = "R";
	}
	if ($I) {
canyonknight's avatar
canyonknight committed
338
339
		$I = "%" . addcslashes($I, '%_') . "%";
		$q.= "AND IRCNick LIKE " . $dbh->quote($I) . " ";
340
341
		$search_vars[] = "I";
	}
342
	if ($K) {
canyonknight's avatar
canyonknight committed
343
344
		$K = "%" . addcslashes(str_replace(" ", "", $K), '%_') . "%";
		$q.= "AND PGPKey LIKE " . $dbh->quote($K) . " ";
345
346
		$search_vars[] = "K";
	}
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
	switch ($SB) {
		case 't':
			$q.= "ORDER BY AccountTypeID, Username ";
			break;
		case 'r':
			$q.= "ORDER BY RealName, AccountTypeID ";
			break;
		case 'i':
			$q.= "ORDER BY IRCNick, AccountTypeID ";
			break;
		case 'v':
			$q.= "ORDER BY LastVoted, Username ";
			break;
		default:
			$q.= "ORDER BY Username, AccountTypeID ";
			break;
	}
	$search_vars[] = "SB";
365
	$q.= "LIMIT " . $HITS_PER_PAGE . " OFFSET " . $OFFSET;
366

367
368
369
	if (!$dbh) {
		$dbh = db_connect();
	}
370

canyonknight's avatar
canyonknight committed
371
	$result = $dbh->query($q);
372

canyonknight's avatar
canyonknight committed
373
	while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
374
375
376
		$userinfo[] = $row;
	}

377
	include("account_search_results.php");
378
379
380
	return;
}

381
382
383
384
385
386
387
388
/**
 * Attempt to login and generate a session
 *
 * @global int $MAX_SESSIONS_PER_USER Maximum sessions a single user may have open
 * @global int $PERSISTENT_COOKIE_TIMEOUT Time until cookie expires
 * @param \PDO $dbh An already established database connection
 *
 * @return array Session ID for user, error message if applicable
389
 */
390
function try_login($dbh=NULL) {
391
	global $MAX_SESSIONS_PER_USER, $PERSISTENT_COOKIE_TIMEOUT;
392

Loui Chang's avatar
Loui Chang committed
393
	$login_error = "";
394
395
396
397
	$new_sid = "";
	$userID = null;

	if ( isset($_REQUEST['user']) || isset($_REQUEST['passwd']) ) {
398
399
400
		if (!$dbh) {
			$dbh = db_connect();
		}
401
		$userID = valid_user($_REQUEST['user'], $dbh);
402

403
		if ( user_suspended($userID, $dbh) ) {
404
405
406
			$login_error = "Account Suspended.";
		}
		elseif ( $userID && isset($_REQUEST['passwd'])
407
		  && valid_passwd($userID, $_REQUEST['passwd'], $dbh) ) {
408
409
410
411
412
413
414

			$logged_in = 0;
			$num_tries = 0;

			# Account looks good.  Generate a SID and store it.

			while (!$logged_in && $num_tries < 5) {
415
416
417
418
419
				if ($MAX_SESSIONS_PER_USER) {
					# Delete all user sessions except the
					# last ($MAX_SESSIONS_PER_USER - 1).
					$q = "DELETE s.* FROM Sessions s ";
					$q.= "LEFT JOIN (SELECT SessionID FROM Sessions ";
420
					$q.= "WHERE UsersId = " . $userID . " ";
421
422
423
					$q.= "ORDER BY LastUpdateTS DESC ";
					$q.= "LIMIT " . ($MAX_SESSIONS_PER_USER - 1) . ") q ";
					$q.= "ON s.SessionID = q.SessionID ";
424
					$q.= "WHERE s.UsersId = " . $userID . " ";
425
					$q.= "AND q.SessionID IS NULL;";
canyonknight's avatar
canyonknight committed
426
					$dbh->query($q);
427
428
				}

429
430
				$new_sid = new_sid();
				$q = "INSERT INTO Sessions (UsersID, SessionID, LastUpdateTS)"
431
				  ." VALUES (" . $userID . ", '" . $new_sid . "', UNIX_TIMESTAMP())";
canyonknight's avatar
canyonknight committed
432
				$result = $dbh->exec($q);
433

434
435
436
437
438
				# Query will fail if $new_sid is not unique
				if ($result) {
					$logged_in = 1;
					break;
				}
439

440
				$num_tries++;
441
			}
442

443
			if ($logged_in) {
444
445
				$q = "UPDATE Users SET LastLogin = UNIX_TIMESTAMP() ";
				$q.= "WHERE ID = '$userID'";
canyonknight's avatar
canyonknight committed
446
				$dbh->exec($q);
447

448
				# set our SID cookie
Dan McGee's avatar
Dan McGee committed
449
450
				if (isset($_POST['remember_me']) &&
					$_POST['remember_me'] == "on") {
451
					# Set cookies for 30 days.
452
					$cookie_time = time() + $PERSISTENT_COOKIE_TIMEOUT;
453
454
455
456

					# Set session for 30 days.
					$q = "UPDATE Sessions SET LastUpdateTS = $cookie_time ";
					$q.= "WHERE SessionID = '$new_sid'";
canyonknight's avatar
canyonknight committed
457
					$dbh->exec($q);
458
				}
459
460
				else
					$cookie_time = 0;
461

462
				setcookie("AURSID", $new_sid, $cookie_time, "/", null, !empty($_SERVER['HTTPS']), true);
463
				header("Location: " . get_uri('/'));
464
465
466
467
468
469
470
471
				$login_error = "";

			}
			else {
				$login_error = "Error trying to generate session id.";
			}
		}
		else {
472
			$login_error = __("Bad username or password.");
473
474
475
476
477
		}
	}
	return array('SID' => $new_sid, 'error' => $login_error);
}

478
479
480
481
482
483
484
485
486
487
488
/**
 * Validate a username against a collection of rules
 *
 * The username must be longer or equal to USERNAME_MIN_LEN. It must be shorter
 * or equal to USERNAME_MAX_LEN. It must start and end with either a letter or
 * a number. It can contain one period, hypen, or underscore. Returns username
 * if it meets all of those rules.
 *
 * @param string $user Username to validate
 *
 * @return string|void Return username if it meets criteria, otherwise void
489
 */
490
function valid_username($user) {
491
	if (!empty($user)) {
492

493
494
495
		#Is username at not too short or too long?
		if ( strlen($user) >= USERNAME_MIN_LEN &&
		  strlen($user) <= USERNAME_MAX_LEN ) {
496

497
			$user = strtolower($user);
498
			# Does username:
499
500
501
502
503
504
505
506
507
			# start and end with a letter or number
			# contain only letters and numbers,
			#  and at most has one dash, period, or underscore
			if ( preg_match("/^[a-z0-9]+[.\-_]?[a-z0-9]+$/", $user) ) {
				#All is good return the username
				return $user;
			}
		}
	}
508

509
510
511
	return;
}

512
513
514
515
516
517
518
/**
 * Determine if a username exists in the database
 *
 * @param string $user Username to check in the database
 * @param \PDO $dbh An already established database connection
 *
 * @return string|void Return user ID if in database, otherwise void
519
 */
canyonknight's avatar
canyonknight committed
520
function valid_user($user, $dbh=NULL) {
521
	/*	if ( $user = valid_username($user) ) { */
canyonknight's avatar
canyonknight committed
522
523
524
525
526

	if(!$dbh) {
		$dbh = db_connect();
	}

527
	if ( $user ) {
canyonknight's avatar
canyonknight committed
528
529
		$q = "SELECT ID FROM Users ";
		$q.= "WHERE Username = " . $dbh->quote($user);
530

canyonknight's avatar
canyonknight committed
531
		$result = $dbh->query($q);
532
		# Is the username in the database?
533
		if ($result) {
canyonknight's avatar
canyonknight committed
534
			$row = $result->fetch(PDO::FETCH_NUM);
535
			return $row[0];
536
537
538
539
540
		}
	}
	return;
}

541
542
543
544
545
546
547
548
/**
 * Determine if a user already has a proposal open about themselves
 *
 * @param string $user Username to checkout for open proposal
 * @param \PDO $dbh An already established database connection
 *
 * @return bool True if there is an open proposal about the user, otherwise false
 */
canyonknight's avatar
canyonknight committed
549
550
551
552
function open_user_proposals($user, $dbh=NULL) {
	if(!$dbh) {
		$dbh = db_connect();
	}
canyonknight's avatar
canyonknight committed
553
554
555
556
	$q = "SELECT * FROM TU_VoteInfo WHERE User = " . $dbh->quote($user) . " ";
	$q.= "AND End > UNIX_TIMESTAMP()";
	$result = $dbh->query($q);
	if ($result->fetchColumn()) {
canyonknight's avatar
canyonknight committed
557
558
559
560
561
562
563
		return true;
	}
	else {
		return false;
	}
}

564
565
566
567
568
569
570
571
572
573
574
/**
 * Add a new Trusted User proposal to the database
 *
 * @param string $agenda The agenda of the vote
 * @param string $user The use the vote is about
 * @param int $votelength The length of time for the vote to last
 * @param string $submitteruid The user ID of the individual who submitted the proposal
 * @param \PDO $dbh An already established database connection
 *
 * @return void
 */
canyonknight's avatar
canyonknight committed
575
576
577
578
function add_tu_proposal($agenda, $user, $votelength, $submitteruid, $dbh=NULL) {
	if(!$dbh) {
		$dbh = db_connect();
	}
canyonknight's avatar
canyonknight committed
579

canyonknight's avatar
canyonknight committed
580
	$q = "INSERT INTO TU_VoteInfo (Agenda, User, Submitted, End, SubmitterID) VALUES ";
canyonknight's avatar
canyonknight committed
581
582
	$q.= "(" . $dbh->quote($agenda) . ", " . $dbh->quote($user) . ", ";
	$q.= "UNIX_TIMESTAMP(), UNIX_TIMESTAMP() + " . $dbh->quote($votelength);
canyonknight's avatar
canyonknight committed
583
	$q.= ", " . $submitteruid . ")";
canyonknight's avatar
canyonknight committed
584
	$result = $dbh->exec($q);
canyonknight's avatar
canyonknight committed
585
586
}

587
588
589
590
591
592
593
594
595
/**
 * Add a reset key to the database for a specified user
 *
 * @param string $resetkey A password reset key to be stored in database
 * @param string $uid The user ID to store the reset key for
 * @param \PDO $dbh An already established database connection
 *
 * @return void
 */
canyonknight's avatar
canyonknight committed
596
597
598
599
600
601
602
function create_resetkey($resetkey, $uid, $dbh=NULL) {
	if(!$dbh) {
		$dbh = db_connect();
	}
	$q = "UPDATE Users ";
	$q.= "SET ResetKey = '" . $resetkey . "' ";
	$q.= "WHERE ID = " . $uid;
canyonknight's avatar
canyonknight committed
603
	$dbh->exec($q);
canyonknight's avatar
canyonknight committed
604
605
}

606
607
608
609
610
611
612
613
614
615
616
/**
 * Change a user's password in the database if reset key and e-mail are correct
 *
 * @param string $hash New MD5 hash of a user's password
 * @param string $salt New salt for the user's password
 * @param string $resetkey Code e-mailed to a user to reset a password
 * @param string $email E-mail address of the user resetting their password
 * @param \PDO $dbh An already established database connection
 *
 * @return string|void Redirect page if successful, otherwise return error message
 */
canyonknight's avatar
canyonknight committed
617
618
619
620
621
622
623
624
625
function password_reset($hash, $salt, $resetkey, $email, $dbh=NULL) {
	if(!$dbh) {
		$dbh = db_connect();
	}
	$q = "UPDATE Users ";
	$q.= "SET Passwd = '$hash', ";
	$q.= "Salt = '$salt', ";
	$q.= "ResetKey = '' ";
	$q.= "WHERE ResetKey != '' ";
canyonknight's avatar
canyonknight committed
626
627
628
	$q.= "AND ResetKey = " . $dbh->quote($resetkey) . " ";
	$q.= "AND Email = " . $dbh->quote($email);
	$result = $dbh->exec($q);
canyonknight's avatar
canyonknight committed
629

canyonknight's avatar
canyonknight committed
630
	if (!$result) {
canyonknight's avatar
canyonknight committed
631
632
633
		$error = __('Invalid e-mail and reset key combination.');
		return $error;
	} else {
634
		header('Location: ' . get_uri('/passreset/') . '?step=complete');
canyonknight's avatar
canyonknight committed
635
636
637
638
		exit();
	}
}

639
640
641
642
643
644
645
/**
 * Determine if the password is longer than the minimum length
 *
 * @param string $passwd The password to check
 *
 * @return bool True if longer than minimum length, otherwise false
 */
646
function good_passwd($passwd) {
647
648
649
650
651
652
	if ( strlen($passwd) >= PASSWD_MIN_LEN ) {
		return true;
	}
	return false;
}

653
654
655
656
657
658
659
660
/**
 * Determine if the password is correct and salt it if it hasn't been already
 *
 * @param string $userID The user ID to check the password against
 * @param string $passwd The password the visitor sent
 * @param \PDO $dbh An already established database connection
 *
 * @return bool True if password was correct and properly salted, otherwise false
661
 */
662
663
664
665
function valid_passwd($userID, $passwd, $dbh=NULL) {
	if (!$dbh) {
		$dbh = db_connect();
	}
666
	if ( strlen($passwd) > 0 ) {
Denis's avatar
Denis committed
667
668
669
670
		# get salt for this user
		$salt = get_salt($userID);
		if ($salt) {
			# use salt
canyonknight's avatar
canyonknight committed
671
672
673
674
			$q = "SELECT ID FROM Users ";
			$q.= "WHERE ID = " . $userID . " ";
			$q.= "AND Passwd = " . $dbh->quote(salted_hash($passwd, $salt));
			$result = $dbh->query($q);
675
			if ($result) {
canyonknight's avatar
canyonknight committed
676
677
				$row = $result->fetch(PDO::FETCH_NUM);
				if ($row[0]) {
678
679
					return true;
				}
Denis's avatar
Denis committed
680
681
682
			}
		} else {
			# check without salt
canyonknight's avatar
canyonknight committed
683
684
685
686
			$q = "SELECT ID FROM Users ";
			$q.= "WHERE ID = " . $userID . " ";
			$q.= "AND Passwd = " . $dbh->quote(md5($passwd));
			$result = $dbh->query($q);
687
			if ($result) {
canyonknight's avatar
canyonknight committed
688
689
				$row = $result->fetch(PDO::FETCH_NUM);
				if ($row[0]) {
690
691
692
693
694
695
696
					# password correct, but salt it first
					if (!save_salt($userID, $passwd)) {
						trigger_error("Unable to salt user's password;" .
							" ID " . $userID, E_USER_WARNING);
						return false;
					}
					return true;
Denis's avatar
Denis committed
697
698
				}
			}
699
700
701
702
703
		}
	}
	return false;
}

704
705
706
707
708
709
/**
 * Determine if the PGP key fingerprint is valid (must be 40 hexadecimal digits)
 *
 * @param string $fingerprint PGP fingerprint to check if valid
 *
 * @return bool True if the fingerprint is 40 hexadecimal digits, otherwise false
710
 */
711
function valid_pgp_fingerprint($fingerprint) {
712
713
714
715
	$fingerprint = str_replace(" ", "", $fingerprint);
	return (strlen($fingerprint) == 40 && ctype_xdigit($fingerprint));
}

716
717
718
719
720
721
722
/**
 * Determine if the user account has been suspended
 *
 * @param string $id The ID of user to check if suspended
 * @param \PDO $dbh An already established database connection
 *
 * @return bool True if the user is suspended, otherwise false
723
 */
724
725
726
727
function user_suspended($id, $dbh=NULL) {
	if (!$dbh) {
		$dbh = db_connect();
	}
elij's avatar
elij committed
728
729
730
	if (!$id) {
		return false;
	}
731
	$q = "SELECT Suspended FROM Users WHERE ID = " . $id;
canyonknight's avatar
canyonknight committed
732
	$result = $dbh->query($q);
733
	if ($result) {
canyonknight's avatar
canyonknight committed
734
		$row = $result->fetch(PDO::FETCH_NUM);
735
		if ($row[0]) {
736
737
			return true;
		}
738
739
740
741
	}
	return false;
}

742
743
744
745
746
747
748
/**
 * Delete a specified user account from the database
 *
 * @param int $id The user ID of the account to be deleted
 * @param \PDO $dbh An already established database connection
 *
 * @return void
749
 */
750
751
752
753
function user_delete($id, $dbh=NULL) {
	if (!$dbh) {
		$dbh = db_connect();
	}
754
	$q = "DELETE FROM Users WHERE ID = " . $id;
canyonknight's avatar
canyonknight committed
755
	$dbh->query($q);
756
757
758
	return;
}

759
760
761
762
763
764
765
/**
 * Determine if a user is either a Trusted User or Developer
 *
 * @param string $id The ID of the user to check if privileged
 * @param \PDO $dbh An already established database connection
 *
 * @return int|string Return  0 if un-privileged, "2" if Trusted User, "3" if Developer
766
 */
767
768
769
770
function user_is_privileged($id, $dbh=NULL) {
	if (!$dbh) {
		$dbh = db_connect();
	}
771
	$q = "SELECT AccountTypeID FROM Users WHERE ID = " . $id;
canyonknight's avatar
canyonknight committed
772
	$result = $dbh->query($q);
773
	if ($result) {
canyonknight's avatar
canyonknight committed
774
		$row = $result->fetch(PDO::FETCH_NUM);
775
776
		if($row[0] > 1) {
			return $row[0];
777
		}
778
	}
779
780
781
782
	return 0;

}

783
784
785
786
787
788
789
790
/**
 * Remove the session from the database on logout
 *
 * @param string $sid User's session ID
 * @param \PDO $dbh An already established database connection
 *
 * @return void
 */
canyonknight's avatar
canyonknight committed
791
792
793
794
795
function delete_session_id($sid, $dbh=NULL) {
	if(!$dbh) {
		$dbh = db_connect();
	}

canyonknight's avatar
canyonknight committed
796
797
	$q = "DELETE FROM Sessions WHERE SessionID = " . $dbh->quote($sid);
	$dbh->query($q);
canyonknight's avatar
canyonknight committed
798
799
}

800
801
802
803
804
805
806
807
/**
 * Remove sessions from the database that have exceed the timeout
 *
 * @global int $LOGIN_TIMEOUT Time until session expires
 * @param \PDO $dbh An already established database connection
 *
 * @return void
 */
canyonknight's avatar
canyonknight committed
808
function clear_expired_sessions($dbh=NULL) {
809
810
	global $LOGIN_TIMEOUT;

canyonknight's avatar
canyonknight committed
811
812
813
814
	if(!$dbh) {
		$dbh = db_connect();
	}

815
	$q = "DELETE FROM Sessions WHERE LastUpdateTS < (UNIX_TIMESTAMP() - $LOGIN_TIMEOUT)";
canyonknight's avatar
canyonknight committed
816
	$dbh->query($q);
817
818
819

	return;
}
820

821
822
823
824
825
826
827
828
829
/**
 * Get account details for a specific user
 *
 * @param string $uid The User ID of account to get information for
 * @param string $username The username of the account to get for
 * @param \PDO $dbh An already established database connection
 *
 * @return array Account details for the specified user
 */
canyonknight's avatar
canyonknight committed
830
831
832
833
834
835
836
837
838
839
function account_details($uid, $username, $dbh=NULL) {
	if(!$dbh) {
		$dbh = db_connect();
	}
	$q = "SELECT Users.*, AccountTypes.AccountType ";
	$q.= "FROM Users, AccountTypes ";
	$q.= "WHERE AccountTypes.ID = Users.AccountTypeID ";
	if (!empty($uid)) {
		$q.= "AND Users.ID = ".intval($uid);
	} else {
canyonknight's avatar
canyonknight committed
840
		$q.= "AND Users.Username = " . $dbh->quote($username);
canyonknight's avatar
canyonknight committed
841
	}
canyonknight's avatar
canyonknight committed
842
	$result = $dbh->query($q);
canyonknight's avatar
canyonknight committed
843
844

	if ($result) {
canyonknight's avatar
canyonknight committed
845
		$row = $result->fetch(PDO::FETCH_ASSOC);
canyonknight's avatar
canyonknight committed
846
847
848
849
850
	}

	return $row;
}

851
852
853
854
855
856
857
858
859
/**
 * Determine if a user has already voted on a specific proposal
 *
 * @param string $voteid The ID of the Trusted User proposal
 * @param string $uid The ID to check if the user already voted
 * @param \PDO $dbh An already established database connection
 *
 * @return bool True if the user has already voted, otherwise false
 */
860
861
862
863
864
function tu_voted($voteid, $uid, $dbh=NULL) {
	if (!$dbh) {
		$dbh = db_connect();
	}

canyonknight's avatar
canyonknight committed
865
866
867
868
	$q = "SELECT COUNT(*) FROM TU_Votes ";
	$q.= "WHERE VoteID = " . intval($voteid) . " AND UserID = " . intval($uid);
	$result = $dbh->query($q);
	if ($result->fetchColumn() > 0) {
869
870
871
872
873
874
875
		return true;
	}
	else {
		return false;
	}
}

876
877
878
879
880
881
882
883
/**
 * Get all current Trusted User proposals from the database
 *
 * @param string $order Ascending or descending order for the proposal listing
 * @param \PDO $dbh An already established database connection
 *
 * @return array The details for all current Trusted User proposals
 */
884
885
886
887
888
889
function current_proposal_list($order, $dbh=NULL) {
	if (!$dbh) {
		$dbh = db_connect();
	}

	$q = "SELECT * FROM TU_VoteInfo WHERE End > " . time() . " ORDER BY Submitted " . $order;
canyonknight's avatar
canyonknight committed
890
	$result = $dbh->query($q);
891

892
	$details = array();
canyonknight's avatar
canyonknight committed
893
	while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
894
895
896
897
898
899
		$details[] = $row;
	}

	return $details;
}

900
901
902
903
904
905
906
907
908
/**
 * Get a subset of all past Trusted User proposals from the database
 *
 * @param string $order Ascending or descending order for the proposal listing
 * @param string $lim The number of proposals to list with the offset
 * @param \PDO $dbh An already established database connection
 *
 * @return array The details for the subset of past Trusted User proposals
 */
909
910
911
912
913
914
function past_proposal_list($order, $lim, $dbh=NULL) {
	if (!$dbh) {
		$dbh = db_connect();
	}

	$q = "SELECT * FROM TU_VoteInfo WHERE End < " . time() . " ORDER BY Submitted " . $order . $lim;
canyonknight's avatar
canyonknight committed
915
	$result = $dbh->query($q);
916

917
	$details = array();
canyonknight's avatar
canyonknight committed
918
	while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
919
920
921
922
923
924
		$details[] = $row;
	}

	return $details;
}

925
926
927
928
929
930
931
/**
 * Determine the total number of Trusted User proposals
 *
 * @param \PDO $dbh An already established database connection
 *
 * @return string The total number of Trusted User proposals
 */
932
933
934
935
936
937
function proposal_count($dbh=NULL) {
	if (!$dbh) {
		$dbh = db_connect();
	}

	$q = "SELECT COUNT(*) FROM TU_VoteInfo";
canyonknight's avatar
canyonknight committed
938
939
	$result = $dbh->query($q);
	$row = $result->fetch(PDO::FETCH_NUM);
940
941
942
943

	return $row[0];
}

944
945
946
947
948
949
950
951
/**
 * Get all details related to a specific vote from the database
 *
 * @param string $voteid The ID of the Trusted User proposal
 * @param \PDO $dbh An already established database connection
 *
 * @return array All stored details for a specific vote
 */
952
953
954
955
956
957
958
959
function vote_details($voteid, $dbh=NULL) {
	if (!$dbh) {
		$dbh = db_connect();
	}

	$q = "SELECT * FROM TU_VoteInfo ";
	$q.= "WHERE ID = " . intval($voteid);

canyonknight's avatar
canyonknight committed
960
961
	$result = $dbh->query($q);
	$row = $result->fetch(PDO::FETCH_ASSOC);
962
963
964
965

	return $row;
}

966
967
968
969
970
971
/**
 * Get an alphabetical list of users who voted for a proposal with HTML links
 *
 * @param string $voteid The ID of the Trusted User proposal
 * @param \PDO $dbh An already established database connection
 *
Lukas Fleischer's avatar
Lukas Fleischer committed
972
 * @return array All users who voted for a specific proposal
973
 */
974
975
976
977
978
function voter_list($voteid, $dbh=NULL) {
	if (!$dbh) {
		$dbh = db_connect();
	}

Lukas Fleischer's avatar
Lukas Fleischer committed
979
	$whovoted = array();
980

981
982
983
984
985
986
	$q = "SELECT tv.UserID,U.Username ";
	$q.= "FROM TU_Votes tv, Users U ";
	$q.= "WHERE tv.VoteID = " . intval($voteid);
	$q.= " AND tv.UserID = U.ID ";
	$q.= "ORDER BY Username";

canyonknight's avatar
canyonknight committed
987
	$result = $dbh->query($q);
988
	if ($result) {
canyonknight's avatar
canyonknight committed
989
		while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
Lukas Fleischer's avatar
Lukas Fleischer committed
990
			$whovoted[] = $row['Username'];
991
992
993
994
995
		}
	}
	return $whovoted;
}

996
997
998
999
1000
/**
 * Cast a vote for a specific user proposal
 *
 * @param string $voteid The ID of the proposal being voted on
 * @param string $uid The user ID of the individual voting
For faster browsing, not all history is shown. View entire blame