Rename the CommentNotify table to PackageNotifications
[aur.git] / web / lib / acctfuncs.inc.php
blob0c6388afd6cc9b211c27f44a880014b90e855452
1 <?php
3 /**
4 * Determine if an HTTP request variable is set
6 * @param string $name The request variable to test for
8 * @return string Return the value of the request variable, otherwise blank
9 */
10 function in_request($name) {
11 if (isset($_REQUEST[$name])) {
12 return $_REQUEST[$name];
14 return "";
17 /**
18 * Format the PGP key fingerprint
20 * @param string $fingerprint An unformatted PGP key fingerprint
22 * @return string PGP fingerprint with spaces every 4 characters
24 function html_format_pgp_fingerprint($fingerprint) {
25 if (strlen($fingerprint) != 40 || !ctype_xdigit($fingerprint)) {
26 return $fingerprint;
29 return htmlspecialchars(substr($fingerprint, 0, 4) . " " .
30 substr($fingerprint, 4, 4) . " " .
31 substr($fingerprint, 8, 4) . " " .
32 substr($fingerprint, 12, 4) . " " .
33 substr($fingerprint, 16, 4) . " " .
34 substr($fingerprint, 20, 4) . " " .
35 substr($fingerprint, 24, 4) . " " .
36 substr($fingerprint, 28, 4) . " " .
37 substr($fingerprint, 32, 4) . " " .
38 substr($fingerprint, 36, 4) . " ", ENT_QUOTES);
41 /**
42 * Loads the account editing form, with any values that are already saved
44 * @global array $SUPPORTED_LANGS Languages that are supported by the AUR
45 * @param string $A Form to use, either UpdateAccount or NewAccount
46 * @param string $U The username to display
47 * @param string $T The account type of the displayed user
48 * @param string $S Whether the displayed user has a suspended account
49 * @param string $E The e-mail address of the displayed user
50 * @param string $H Whether the e-mail address of the displayed user is hidden
51 * @param string $P The password value of the displayed user
52 * @param string $C The confirmed password value of the displayed user
53 * @param string $R The real name of the displayed user
54 * @param string $L The language preference of the displayed user
55 * @param string $I The IRC nickname of the displayed user
56 * @param string $K The PGP key fingerprint of the displayed user
57 * @param string $PK The list of SSH public keys
58 * @param string $J The inactivity status of the displayed user
59 * @param string $UID The user ID of the displayed user
60 * @param string $N The username as present in the database
62 * @return void
64 function display_account_form($A,$U="",$T="",$S="",$E="",$H="",$P="",$C="",$R="",
65 $L="",$I="",$K="",$PK="",$J="",$UID=0,$N="") {
66 global $SUPPORTED_LANGS;
68 include("account_edit_form.php");
69 return;
72 /**
73 * Process information given to new/edit account form
75 * @global array $SUPPORTED_LANGS Languages that are supported by the AUR
76 * @param string $TYPE Either "edit" for editing or "new" for registering an account
77 * @param string $A Form to use, either UpdateAccount or NewAccount
78 * @param string $U The username for the account
79 * @param string $T The account type for the user
80 * @param string $S Whether or not the account is suspended
81 * @param string $E The e-mail address for the user
82 * @param string $H Whether or not the e-mail address should be hidden
83 * @param string $P The password for the user
84 * @param string $C The confirmed password for the user
85 * @param string $R The real name of the user
86 * @param string $L The language preference of the user
87 * @param string $I The IRC nickname of the user
88 * @param string $K The PGP fingerprint of the user
89 * @param string $PK The list of public SSH keys
90 * @param string $J The inactivity status of the user
91 * @param string $UID The user ID of the modified account
92 * @param string $N The username as present in the database
94 * @return array Boolean indicating success and message to be printed
96 function process_account_form($TYPE,$A,$U="",$T="",$S="",$E="",$H="",$P="",$C="",
97 $R="",$L="",$I="",$K="",$PK="",$J="",$UID=0,$N="") {
98 global $SUPPORTED_LANGS;
100 $error = '';
101 $message = '';
103 if (is_ipbanned()) {
104 $error = __('Account registration has been disabled ' .
105 'for your IP address, probably due ' .
106 'to sustained spam attacks. Sorry for the ' .
107 'inconvenience.');
110 $dbh = DB::connect();
112 if(isset($_COOKIE['AURSID'])) {
113 $editor_user = uid_from_sid($_COOKIE['AURSID']);
115 else {
116 $editor_user = null;
119 if (empty($E) || empty($U)) {
120 $error = __("Missing a required field.");
123 if ($TYPE != "new" && !$UID) {
124 $error = __("Missing User ID");
127 if (!$error && !valid_username($U)) {
128 $length_min = config_get_int('options', 'username_min_len');
129 $length_max = config_get_int('options', 'username_max_len');
131 $error = __("The username is invalid.") . "<ul>\n"
132 . "<li>" . __("It must be between %s and %s characters long", $length_min, $length_max)
133 . "</li>"
134 . "<li>" . __("Start and end with a letter or number") . "</li>"
135 . "<li>" . __("Can contain only one period, underscore or hyphen.")
136 . "</li>\n</ul>";
139 if (!$error && $P && $C && ($P != $C)) {
140 $error = __("Password fields do not match.");
142 if (!$error && $P != '' && !good_passwd($P)) {
143 $length_min = config_get_int('options', 'passwd_min_len');
144 $error = __("Your password must be at least %s characters.",
145 $length_min);
148 if (!$error && !valid_email($E)) {
149 $error = __("The email address is invalid.");
152 if (!$error && $K != '' && !valid_pgp_fingerprint($K)) {
153 $error = __("The PGP key fingerprint is invalid.");
156 if (!$error && !empty($PK)) {
157 $ssh_keys = array_filter(array_map('trim', explode("\n", $PK)));
158 $ssh_fingerprints = array();
160 foreach ($ssh_keys as &$ssh_key) {
161 if (!valid_ssh_pubkey($ssh_key)) {
162 $error = __("The SSH public key is invalid.");
163 break;
166 $ssh_fingerprint = ssh_key_fingerprint($ssh_key);
167 if (!$ssh_fingerprint) {
168 $error = __("The SSH public key is invalid.");
169 break;
172 $tokens = explode(" ", $ssh_key);
173 $ssh_key = $tokens[0] . " " . $tokens[1];
175 $ssh_fingerprints[] = $ssh_fingerprint;
179 * Destroy last reference to prevent accidentally overwriting
180 * an array element.
182 unset($ssh_key);
185 if (isset($_COOKIE['AURSID'])) {
186 $atype = account_from_sid($_COOKIE['AURSID']);
187 if (($atype == "User" && $T > 1) || ($atype == "Trusted User" && $T > 2)) {
188 $error = __("Cannot increase account permissions.");
192 if (!$error && !array_key_exists($L, $SUPPORTED_LANGS)) {
193 $error = __("Language is not currently supported.");
195 if (!$error) {
197 * Check whether the user name is available.
198 * TODO: Fix race condition.
200 $q = "SELECT COUNT(*) AS CNT FROM Users ";
201 $q.= "WHERE Username = " . $dbh->quote($U);
202 if ($TYPE == "edit") {
203 $q.= " AND ID != ".intval($UID);
205 $result = $dbh->query($q);
206 $row = $result->fetch(PDO::FETCH_NUM);
208 if ($row[0]) {
209 $error = __("The username, %s%s%s, is already in use.",
210 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
213 if (!$error) {
215 * Check whether the e-mail address is available.
216 * TODO: Fix race condition.
218 $q = "SELECT COUNT(*) AS CNT FROM Users ";
219 $q.= "WHERE Email = " . $dbh->quote($E);
220 if ($TYPE == "edit") {
221 $q.= " AND ID != ".intval($UID);
223 $result = $dbh->query($q);
224 $row = $result->fetch(PDO::FETCH_NUM);
226 if ($row[0]) {
227 $error = __("The address, %s%s%s, is already in use.",
228 "<strong>", htmlspecialchars($E,ENT_QUOTES), "</strong>");
231 if (!$error && count($ssh_keys) > 0) {
233 * Check whether any of the SSH public keys is already in use.
234 * TODO: Fix race condition.
236 $q = "SELECT Fingerprint FROM SSHPubKeys ";
237 $q.= "WHERE Fingerprint IN (";
238 $q.= implode(',', array_map(array($dbh, 'quote'), $ssh_fingerprints));
239 $q.= ")";
240 if ($TYPE == "edit") {
241 $q.= " AND UserID != " . intval($UID);
243 $result = $dbh->query($q);
244 $row = $result->fetch(PDO::FETCH_NUM);
246 if ($row) {
247 $error = __("The SSH public key, %s%s%s, is already in use.",
248 "<strong>", htmlspecialchars($row[0], ENT_QUOTES), "</strong>");
252 if ($error) {
253 $message = "<ul class='errorlist'><li>".$error."</li></ul>\n";
254 return array(false, $message);
257 if ($TYPE == "new") {
258 /* Create an unprivileged user. */
259 $salt = generate_salt();
260 if (empty($P)) {
261 $send_resetkey = true;
262 $email = $E;
263 } else {
264 $send_resetkey = false;
265 $P = salted_hash($P, $salt);
267 $U = $dbh->quote($U);
268 $E = $dbh->quote($E);
269 $P = $dbh->quote($P);
270 $salt = $dbh->quote($salt);
271 $R = $dbh->quote($R);
272 $L = $dbh->quote($L);
273 $I = $dbh->quote($I);
274 $K = $dbh->quote(str_replace(" ", "", $K));
275 $q = "INSERT INTO Users (AccountTypeID, Suspended, ";
276 $q.= "InactivityTS, Username, Email, Passwd, Salt, ";
277 $q.= "RealName, LangPreference, IRCNick, PGPKey) ";
278 $q.= "VALUES (1, 0, 0, $U, $E, $P, $salt, $R, $L, ";
279 $q.= "$I, $K)";
280 $result = $dbh->exec($q);
281 if (!$result) {
282 $message = __("Error trying to create account, %s%s%s.",
283 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
284 return array(false, $message);
287 $uid = $dbh->lastInsertId();
288 account_set_ssh_keys($uid, $ssh_keys, $ssh_fingerprints);
290 $message = __("The account, %s%s%s, has been successfully created.",
291 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
292 $message .= "<p>\n";
294 if ($send_resetkey) {
295 send_resetkey($email, true);
296 $message .= __("A password reset key has been sent to your e-mail address.");
297 $message .= "</p>\n";
298 } else {
299 $message .= __("Click on the Login link above to use your account.");
300 $message .= "</p>\n";
302 } else {
303 /* Modify an existing account. */
304 $q = "SELECT InactivityTS FROM Users WHERE ";
305 $q.= "ID = " . intval($UID);
306 $result = $dbh->query($q);
307 $row = $result->fetch(PDO::FETCH_NUM);
308 if ($row[0] && $J) {
309 $inactivity_ts = $row[0];
310 } elseif ($J) {
311 $inactivity_ts = time();
312 } else {
313 $inactivity_ts = 0;
316 $q = "UPDATE Users SET ";
317 $q.= "Username = " . $dbh->quote($U);
318 if ($T) {
319 $q.= ", AccountTypeID = ".intval($T);
321 if ($S) {
322 /* Ensure suspended users can't keep an active session */
323 delete_user_sessions($UID);
324 $q.= ", Suspended = 1";
325 } else {
326 $q.= ", Suspended = 0";
328 $q.= ", Email = " . $dbh->quote($E);
329 if ($H) {
330 $q.= ", HideEmail = 1";
331 } else {
332 $q.= ", HideEmail = 0";
334 if ($P) {
335 $salt = generate_salt();
336 $hash = salted_hash($P, $salt);
337 $q .= ", Passwd = '$hash', Salt = '$salt'";
339 $q.= ", RealName = " . $dbh->quote($R);
340 $q.= ", LangPreference = " . $dbh->quote($L);
341 $q.= ", IRCNick = " . $dbh->quote($I);
342 $q.= ", PGPKey = " . $dbh->quote(str_replace(" ", "", $K));
343 $q.= ", InactivityTS = " . $inactivity_ts;
344 $q.= " WHERE ID = ".intval($UID);
345 $result = $dbh->exec($q);
347 $ssh_key_result = account_set_ssh_keys($UID, $ssh_keys, $ssh_fingerprints);
349 if ($result === false || $ssh_key_result === false) {
350 $message = __("No changes were made to the account, %s%s%s.",
351 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
352 } else {
353 $message = __("The account, %s%s%s, has been successfully modified.",
354 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
358 return array(true, $message);
362 * Display the search results page
364 * @param string $O The offset for the results page
365 * @param string $SB The column to sort the results page by
366 * @param string $U The username search criteria
367 * @param string $T The account type search criteria
368 * @param string $S Whether the account is suspended search criteria
369 * @param string $E The e-mail address search criteria
370 * @param string $R The real name search criteria
371 * @param string $I The IRC nickname search criteria
372 * @param string $K The PGP key fingerprint search criteria
374 * @return void
376 function search_results_page($O=0,$SB="",$U="",$T="",
377 $S="",$E="",$R="",$I="",$K="") {
379 $HITS_PER_PAGE = 50;
380 if ($O) {
381 $OFFSET = intval($O);
382 } else {
383 $OFFSET = 0;
385 if ($OFFSET < 0) {
386 $OFFSET = 0;
388 $search_vars = array();
390 $dbh = DB::connect();
392 $q = "SELECT Users.*, AccountTypes.AccountType ";
393 $q.= "FROM Users, AccountTypes ";
394 $q.= "WHERE AccountTypes.ID = Users.AccountTypeID ";
395 if ($T == "u") {
396 $q.= "AND AccountTypes.ID = 1 ";
397 $search_vars[] = "T";
398 } elseif ($T == "t") {
399 $q.= "AND AccountTypes.ID = 2 ";
400 $search_vars[] = "T";
401 } elseif ($T == "d") {
402 $q.= "AND AccountTypes.ID = 3 ";
403 $search_vars[] = "T";
404 } elseif ($T == "td") {
405 $q.= "AND AccountTypes.ID = 4 ";
406 $search_vars[] = "T";
408 if ($S) {
409 $q.= "AND Users.Suspended = 1 ";
410 $search_vars[] = "S";
412 if ($U) {
413 $U = "%" . addcslashes($U, '%_') . "%";
414 $q.= "AND Username LIKE " . $dbh->quote($U) . " ";
415 $search_vars[] = "U";
417 if ($E) {
418 $E = "%" . addcslashes($E, '%_') . "%";
419 $q.= "AND Email LIKE " . $dbh->quote($E) . " ";
420 $search_vars[] = "E";
422 if ($R) {
423 $R = "%" . addcslashes($R, '%_') . "%";
424 $q.= "AND RealName LIKE " . $dbh->quote($R) . " ";
425 $search_vars[] = "R";
427 if ($I) {
428 $I = "%" . addcslashes($I, '%_') . "%";
429 $q.= "AND IRCNick LIKE " . $dbh->quote($I) . " ";
430 $search_vars[] = "I";
432 if ($K) {
433 $K = "%" . addcslashes(str_replace(" ", "", $K), '%_') . "%";
434 $q.= "AND PGPKey LIKE " . $dbh->quote($K) . " ";
435 $search_vars[] = "K";
437 switch ($SB) {
438 case 't':
439 $q.= "ORDER BY AccountTypeID, Username ";
440 break;
441 case 'r':
442 $q.= "ORDER BY RealName, AccountTypeID ";
443 break;
444 case 'i':
445 $q.= "ORDER BY IRCNick, AccountTypeID ";
446 break;
447 default:
448 $q.= "ORDER BY Username, AccountTypeID ";
449 break;
451 $search_vars[] = "SB";
452 $q.= "LIMIT " . $HITS_PER_PAGE . " OFFSET " . $OFFSET;
454 $dbh = DB::connect();
456 $result = $dbh->query($q);
458 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
459 $userinfo[] = $row;
462 include("account_search_results.php");
463 return;
467 * Attempt to login and generate a session
469 * @return array Session ID for user, error message if applicable
471 function try_login() {
472 $login_error = "";
473 $new_sid = "";
474 $userID = null;
476 if (!isset($_REQUEST['user']) && !isset($_REQUEST['passwd'])) {
477 return array('SID' => '', 'error' => null);
480 if (is_ipbanned()) {
481 $login_error = __('The login form is currently disabled ' .
482 'for your IP address, probably due ' .
483 'to sustained spam attacks. Sorry for the ' .
484 'inconvenience.');
485 return array('SID' => '', 'error' => $login_error);
488 $dbh = DB::connect();
489 $userID = uid_from_loginname($_REQUEST['user']);
491 if (user_suspended($userID)) {
492 $login_error = __('Account suspended');
493 return array('SID' => '', 'error' => $login_error);
494 } elseif (passwd_is_empty($userID)) {
495 $login_error = __('Your password has been reset. ' .
496 'If you just created a new account, please ' .
497 'use the link from the confirmation email ' .
498 'to set an initial password. Otherwise, ' .
499 'please request a reset key on the %s' .
500 'Password Reset%s page.', '<a href="' .
501 htmlspecialchars(get_uri('/passreset')) . '">',
502 '</a>');
503 return array('SID' => '', 'error' => $login_error);
504 } elseif (!valid_passwd($userID, $_REQUEST['passwd'])) {
505 $login_error = __("Bad username or password.");
506 return array('SID' => '', 'error' => $login_error);
509 $logged_in = 0;
510 $num_tries = 0;
512 /* Generate a session ID and store it. */
513 while (!$logged_in && $num_tries < 5) {
514 $session_limit = config_get_int('options', 'max_sessions_per_user');
515 if ($session_limit) {
517 * Delete all user sessions except the
518 * last ($session_limit - 1).
520 $q = "DELETE s.* FROM Sessions s ";
521 $q.= "LEFT JOIN (SELECT SessionID FROM Sessions ";
522 $q.= "WHERE UsersId = " . $userID . " ";
523 $q.= "ORDER BY LastUpdateTS DESC ";
524 $q.= "LIMIT " . ($session_limit - 1) . ") q ";
525 $q.= "ON s.SessionID = q.SessionID ";
526 $q.= "WHERE s.UsersId = " . $userID . " ";
527 $q.= "AND q.SessionID IS NULL;";
528 $dbh->query($q);
531 $new_sid = new_sid();
532 $q = "INSERT INTO Sessions (UsersID, SessionID, LastUpdateTS)"
533 ." VALUES (" . $userID . ", '" . $new_sid . "', UNIX_TIMESTAMP())";
534 $result = $dbh->exec($q);
536 /* Query will fail if $new_sid is not unique. */
537 if ($result) {
538 $logged_in = 1;
539 break;
542 $num_tries++;
545 if (!$logged_in) {
546 $login_error = __('An error occurred trying to generate a user session.');
547 return array('SID' => $new_sid, 'error' => $login_error);
550 $q = "UPDATE Users SET LastLogin = UNIX_TIMESTAMP(), ";
551 $q.= "LastLoginIPAddress = " . $dbh->quote(ip2long($_SERVER['REMOTE_ADDR'])) . " ";
552 $q.= "WHERE ID = '$userID'";
553 $dbh->exec($q);
555 /* Set the SID cookie. */
556 if (isset($_POST['remember_me']) && $_POST['remember_me'] == "on") {
557 /* Set cookies for 30 days. */
558 $timeout = config_get_int('options', 'persistent_cookie_timeout');
559 $cookie_time = time() + $timeout;
561 /* Set session for 30 days. */
562 $q = "UPDATE Sessions SET LastUpdateTS = $cookie_time ";
563 $q.= "WHERE SessionID = '$new_sid'";
564 $dbh->exec($q);
565 } else {
566 $cookie_time = 0;
569 setcookie("AURSID", $new_sid, $cookie_time, "/", null, !empty($_SERVER['HTTPS']), true);
571 $referer = in_request('referer');
572 if (strpos($referer, aur_location()) !== 0) {
573 $referer = '/';
575 header("Location: " . get_uri($referer));
576 $login_error = "";
580 * Determine if the user is using a banned IP address
582 * @return bool True if IP address is banned, otherwise false
584 function is_ipbanned() {
585 $dbh = DB::connect();
587 $q = "SELECT * FROM Bans WHERE IPAddress = " . $dbh->quote(ip2long($_SERVER['REMOTE_ADDR']));
588 $result = $dbh->query($q);
590 return ($result->fetchColumn() ? true : false);
594 * Validate a username against a collection of rules
596 * The username must be longer or equal to the configured minimum length. It
597 * must be shorter or equal to the configured maximum length. It must start and
598 * end with either a letter or a number. It can contain one period, hypen, or
599 * underscore. Returns boolean of whether name is valid.
601 * @param string $user Username to validate
603 * @return bool True if username meets criteria, otherwise false
605 function valid_username($user) {
606 $length_min = config_get_int('options', 'username_min_len');
607 $length_max = config_get_int('options', 'username_max_len');
609 if (strlen($user) < $length_min || strlen($user) > $length_max) {
610 return false;
611 } else if (!preg_match("/^[a-z0-9]+[.\-_]?[a-z0-9]+$/Di", $user)) {
612 return false;
615 return true;
619 * Determine if a user already has a proposal open about themselves
621 * @param string $user Username to checkout for open proposal
623 * @return bool True if there is an open proposal about the user, otherwise false
625 function open_user_proposals($user) {
626 $dbh = DB::connect();
627 $q = "SELECT * FROM TU_VoteInfo WHERE User = " . $dbh->quote($user) . " ";
628 $q.= "AND End > UNIX_TIMESTAMP()";
629 $result = $dbh->query($q);
631 return ($result->fetchColumn() ? true : false);
635 * Add a new Trusted User proposal to the database
637 * @param string $agenda The agenda of the vote
638 * @param string $user The use the vote is about
639 * @param int $votelength The length of time for the vote to last
640 * @param string $submitteruid The user ID of the individual who submitted the proposal
642 * @return void
644 function add_tu_proposal($agenda, $user, $votelength, $quorum, $submitteruid) {
645 $dbh = DB::connect();
647 $q = "SELECT COUNT(*) FROM Users WHERE (AccountTypeID = 2 OR AccountTypeID = 4)";
648 $result = $dbh->query($q);
649 $row = $result->fetch(PDO::FETCH_NUM);
650 $active_tus = $row[0];
652 $q = "INSERT INTO TU_VoteInfo (Agenda, User, Submitted, End, Quorum, ";
653 $q.= "SubmitterID, ActiveTUs) VALUES ";
654 $q.= "(" . $dbh->quote($agenda) . ", " . $dbh->quote($user) . ", ";
655 $q.= "UNIX_TIMESTAMP(), UNIX_TIMESTAMP() + " . $dbh->quote($votelength);
656 $q.= ", " . $dbh->quote($quorum) . ", " . $submitteruid . ", ";
657 $q.= $active_tus . ")";
658 $result = $dbh->exec($q);
662 * Add a reset key to the database for a specified user
664 * @param string $resetkey A password reset key to be stored in database
665 * @param string $uid The user ID to store the reset key for
667 * @return void
669 function create_resetkey($resetkey, $uid) {
670 $dbh = DB::connect();
671 $q = "UPDATE Users ";
672 $q.= "SET ResetKey = '" . $resetkey . "' ";
673 $q.= "WHERE ID = " . $uid;
674 $dbh->exec($q);
678 * Send a reset key to a specific e-mail address
680 * @param string $email E-mail address of the user resetting their password
681 * @param bool $welcome Whether to use the welcome message
683 * @return void
685 function send_resetkey($email, $welcome=false) {
686 $uid = uid_from_email($email);
687 if ($uid == null) {
688 return;
691 /* We (ab)use new_sid() to get a random 32 characters long string. */
692 $resetkey = new_sid();
693 create_resetkey($resetkey, $uid);
695 /* Send e-mail with confirmation link. */
696 notify(array($welcome ? 'welcome' : 'send-resetkey', $uid));
700 * Change a user's password in the database if reset key and e-mail are correct
702 * @param string $hash New MD5 hash of a user's password
703 * @param string $salt New salt for the user's password
704 * @param string $resetkey Code e-mailed to a user to reset a password
705 * @param string $email E-mail address of the user resetting their password
707 * @return string|void Redirect page if successful, otherwise return error message
709 function password_reset($hash, $salt, $resetkey, $email) {
710 $dbh = DB::connect();
711 $q = "UPDATE Users ";
712 $q.= "SET Passwd = '$hash', ";
713 $q.= "Salt = '$salt', ";
714 $q.= "ResetKey = '' ";
715 $q.= "WHERE ResetKey != '' ";
716 $q.= "AND ResetKey = " . $dbh->quote($resetkey) . " ";
717 $q.= "AND Email = " . $dbh->quote($email);
718 $result = $dbh->exec($q);
720 if (!$result) {
721 $error = __('Invalid e-mail and reset key combination.');
722 return $error;
723 } else {
724 header('Location: ' . get_uri('/passreset/') . '?step=complete');
725 exit();
730 * Determine if the password is longer than the minimum length
732 * @param string $passwd The password to check
734 * @return bool True if longer than minimum length, otherwise false
736 function good_passwd($passwd) {
737 $length_min = config_get_int('options', 'passwd_min_len');
738 return (strlen($passwd) >= $length_min);
742 * Determine if the password is correct and salt it if it hasn't been already
744 * @param string $userID The user ID to check the password against
745 * @param string $passwd The password the visitor sent
747 * @return bool True if password was correct and properly salted, otherwise false
749 function valid_passwd($userID, $passwd) {
750 $dbh = DB::connect();
751 if ($passwd == "") {
752 return false;
755 /* Get salt for this user. */
756 $salt = get_salt($userID);
757 if ($salt) {
758 $q = "SELECT ID FROM Users ";
759 $q.= "WHERE ID = " . $userID . " ";
760 $q.= "AND Passwd = " . $dbh->quote(salted_hash($passwd, $salt));
761 $result = $dbh->query($q);
762 if (!$result) {
763 return false;
766 $row = $result->fetch(PDO::FETCH_NUM);
767 return ($row[0] > 0);
768 } else {
769 /* Check password without using salt. */
770 $q = "SELECT ID FROM Users ";
771 $q.= "WHERE ID = " . $userID . " ";
772 $q.= "AND Passwd = " . $dbh->quote(md5($passwd));
773 $result = $dbh->query($q);
774 if (!$result) {
775 return false;
778 $row = $result->fetch(PDO::FETCH_NUM);
779 if (!$row[0]) {
780 return false;
783 /* Password correct, but salt it first! */
784 if (!save_salt($userID, $passwd)) {
785 trigger_error("Unable to salt user's password;" .
786 " ID " . $userID, E_USER_WARNING);
787 return false;
790 return true;
795 * Determine if a user's password is empty
797 * @param string $uid The user ID to check for an empty password
799 * @return bool True if the user's password is empty, otherwise false
801 function passwd_is_empty($uid) {
802 $dbh = DB::connect();
804 $q = "SELECT * FROM Users WHERE ID = " . $dbh->quote($uid) . " ";
805 $q .= "AND Passwd = " . $dbh->quote('');
806 $result = $dbh->query($q);
808 if ($result->fetchColumn()) {
809 return true;
810 } else {
811 return false;
816 * Determine if the PGP key fingerprint is valid (must be 40 hexadecimal digits)
818 * @param string $fingerprint PGP fingerprint to check if valid
820 * @return bool True if the fingerprint is 40 hexadecimal digits, otherwise false
822 function valid_pgp_fingerprint($fingerprint) {
823 $fingerprint = str_replace(" ", "", $fingerprint);
824 return (strlen($fingerprint) == 40 && ctype_xdigit($fingerprint));
828 * Determine if the SSH public key is valid
830 * @param string $pubkey SSH public key to check
832 * @return bool True if the SSH public key is valid, otherwise false
834 function valid_ssh_pubkey($pubkey) {
835 $valid_prefixes = array(
836 "ssh-rsa", "ssh-dss", "ecdsa-sha2-nistp256",
837 "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521", "ssh-ed25519"
840 $has_valid_prefix = false;
841 foreach ($valid_prefixes as $prefix) {
842 if (strpos($pubkey, $prefix . " ") === 0) {
843 $has_valid_prefix = true;
844 break;
847 if (!$has_valid_prefix) {
848 return false;
851 $tokens = explode(" ", $pubkey);
852 if (empty($tokens[1])) {
853 return false;
856 return (base64_encode(base64_decode($tokens[1], true)) == $tokens[1]);
860 * Determine if the user account has been suspended
862 * @param string $id The ID of user to check if suspended
864 * @return bool True if the user is suspended, otherwise false
866 function user_suspended($id) {
867 $dbh = DB::connect();
868 if (!$id) {
869 return false;
871 $q = "SELECT Suspended FROM Users WHERE ID = " . $id;
872 $result = $dbh->query($q);
873 if ($result) {
874 $row = $result->fetch(PDO::FETCH_NUM);
875 if ($row[0]) {
876 return true;
879 return false;
883 * Delete a specified user account from the database
885 * @param int $id The user ID of the account to be deleted
887 * @return void
889 function user_delete($id) {
890 $dbh = DB::connect();
891 $id = intval($id);
894 * These are normally already taken care of by propagation constraints
895 * but it is better to be explicit here.
897 $fields_delete = array(
898 array("Sessions", "UsersID"),
899 array("PackageVotes", "UsersID"),
900 array("PackageNotifications", "UsersID")
903 $fields_set_null = array(
904 array("PackageBases", "SubmitterUID"),
905 array("PackageBases", "MaintainerUID"),
906 array("PackageBases", "SubmitterUID"),
907 array("PackageComments", "UsersID"),
908 array("PackageComments", "DelUsersID"),
909 array("PackageRequests", "UsersID"),
910 array("TU_VoteInfo", "SubmitterID"),
911 array("TU_Votes", "UserID")
914 foreach($fields_delete as list($table, $field)) {
915 $q = "DELETE FROM " . $table . " ";
916 $q.= "WHERE " . $field . " = " . $id;
917 $dbh->query($q);
920 foreach($fields_set_null as list($table, $field)) {
921 $q = "UPDATE " . $table . " SET " . $field . " = NULL ";
922 $q.= "WHERE " . $field . " = " . $id;
923 $dbh->query($q);
926 $q = "DELETE FROM Users WHERE ID = " . $id;
927 $dbh->query($q);
928 return;
932 * Remove the session from the database on logout
934 * @param string $sid User's session ID
936 * @return void
938 function delete_session_id($sid) {
939 $dbh = DB::connect();
941 $q = "DELETE FROM Sessions WHERE SessionID = " . $dbh->quote($sid);
942 $dbh->query($q);
946 * Remove all sessions belonging to a particular user
948 * @param int $uid ID of user to remove all sessions for
950 * @return void
952 function delete_user_sessions($uid) {
953 $dbh = DB::connect();
955 $q = "DELETE FROM Sessions WHERE UsersID = " . intval($uid);
956 $dbh->exec($q);
960 * Remove sessions from the database that have exceed the timeout
962 * @return void
964 function clear_expired_sessions() {
965 $dbh = DB::connect();
967 $timeout = config_get_int('options', 'login_timeout');
968 $q = "DELETE FROM Sessions WHERE LastUpdateTS < (UNIX_TIMESTAMP() - " . $timeout . ")";
969 $dbh->query($q);
971 return;
975 * Get account details for a specific user
977 * @param string $uid The User ID of account to get information for
978 * @param string $username The username of the account to get for
980 * @return array Account details for the specified user
982 function account_details($uid, $username) {
983 $dbh = DB::connect();
984 $q = "SELECT Users.*, AccountTypes.AccountType ";
985 $q.= "FROM Users, AccountTypes ";
986 $q.= "WHERE AccountTypes.ID = Users.AccountTypeID ";
987 if (!empty($uid)) {
988 $q.= "AND Users.ID = ".intval($uid);
989 } else {
990 $q.= "AND Users.Username = " . $dbh->quote($username);
992 $result = $dbh->query($q);
994 if ($result) {
995 $row = $result->fetch(PDO::FETCH_ASSOC);
998 return $row;
1002 * Determine if a user has already voted on a specific proposal
1004 * @param string $voteid The ID of the Trusted User proposal
1005 * @param string $uid The ID to check if the user already voted
1007 * @return bool True if the user has already voted, otherwise false
1009 function tu_voted($voteid, $uid) {
1010 $dbh = DB::connect();
1012 $q = "SELECT COUNT(*) FROM TU_Votes ";
1013 $q.= "WHERE VoteID = " . intval($voteid) . " AND UserID = " . intval($uid);
1014 $result = $dbh->query($q);
1015 if ($result->fetchColumn() > 0) {
1016 return true;
1018 else {
1019 return false;
1024 * Get all current Trusted User proposals from the database
1026 * @param string $order Ascending or descending order for the proposal listing
1028 * @return array The details for all current Trusted User proposals
1030 function current_proposal_list($order) {
1031 $dbh = DB::connect();
1033 $q = "SELECT * FROM TU_VoteInfo WHERE End > " . time() . " ORDER BY Submitted " . $order;
1034 $result = $dbh->query($q);
1036 $details = array();
1037 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
1038 $details[] = $row;
1041 return $details;
1045 * Get a subset of all past Trusted User proposals from the database
1047 * @param string $order Ascending or descending order for the proposal listing
1048 * @param string $lim The number of proposals to list with the offset
1050 * @return array The details for the subset of past Trusted User proposals
1052 function past_proposal_list($order, $lim) {
1053 $dbh = DB::connect();
1055 $q = "SELECT * FROM TU_VoteInfo WHERE End < " . time() . " ORDER BY Submitted " . $order . $lim;
1056 $result = $dbh->query($q);
1058 $details = array();
1059 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
1060 $details[] = $row;
1063 return $details;
1067 * Get the vote ID of the last vote of all Trusted Users
1069 * @return array The vote ID of the last vote of each Trusted User
1071 function last_votes_list() {
1072 $dbh = DB::connect();
1074 $q = "SELECT UserID, MAX(VoteID) AS LastVote FROM TU_Votes, ";
1075 $q .= "TU_VoteInfo, Users WHERE TU_VoteInfo.ID = TU_Votes.VoteID AND ";
1076 $q .= "TU_VoteInfo.End < UNIX_TIMESTAMP() AND ";
1077 $q .= "Users.ID = TU_Votes.UserID AND (Users.AccountTypeID = 2 OR Users.AccountTypeID = 4) ";
1078 $q .= "GROUP BY UserID ORDER BY LastVote DESC, UserName ASC";
1079 $result = $dbh->query($q);
1081 $details = array();
1082 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
1083 $details[] = $row;
1086 return $details;
1090 * Determine the total number of Trusted User proposals
1092 * @return string The total number of Trusted User proposals
1094 function proposal_count() {
1095 $dbh = DB::connect();
1096 $q = "SELECT COUNT(*) FROM TU_VoteInfo";
1097 $result = $dbh->query($q);
1098 $row = $result->fetch(PDO::FETCH_NUM);
1100 return $row[0];
1104 * Get all details related to a specific vote from the database
1106 * @param string $voteid The ID of the Trusted User proposal
1108 * @return array All stored details for a specific vote
1110 function vote_details($voteid) {
1111 $dbh = DB::connect();
1113 $q = "SELECT * FROM TU_VoteInfo ";
1114 $q.= "WHERE ID = " . intval($voteid);
1116 $result = $dbh->query($q);
1117 $row = $result->fetch(PDO::FETCH_ASSOC);
1119 return $row;
1123 * Get an alphabetical list of users who voted for a proposal with HTML links
1125 * @param string $voteid The ID of the Trusted User proposal
1127 * @return array All users who voted for a specific proposal
1129 function voter_list($voteid) {
1130 $dbh = DB::connect();
1132 $whovoted = array();
1134 $q = "SELECT tv.UserID,U.Username ";
1135 $q.= "FROM TU_Votes tv, Users U ";
1136 $q.= "WHERE tv.VoteID = " . intval($voteid);
1137 $q.= " AND tv.UserID = U.ID ";
1138 $q.= "ORDER BY Username";
1140 $result = $dbh->query($q);
1141 if ($result) {
1142 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
1143 $whovoted[] = $row['Username'];
1146 return $whovoted;
1150 * Cast a vote for a specific user proposal
1152 * @param string $voteid The ID of the proposal being voted on
1153 * @param string $uid The user ID of the individual voting
1154 * @param string $vote Vote position, either "Yes", "No", or "Abstain"
1155 * @param int $newtotal The total number of votes after the user has voted
1157 * @return void
1159 function cast_proposal_vote($voteid, $uid, $vote, $newtotal) {
1160 $dbh = DB::connect();
1162 $q = "UPDATE TU_VoteInfo SET " . $vote . " = (" . $newtotal . ") WHERE ID = " . $voteid;
1163 $result = $dbh->exec($q);
1165 $q = "INSERT INTO TU_Votes (VoteID, UserID) VALUES (" . intval($voteid) . ", " . intval($uid) . ")";
1166 $result = $dbh->exec($q);
1170 * Verify a user has the proper permissions to edit an account
1172 * @param array $acctinfo User account information for edited account
1174 * @return bool True if permission to edit the account, otherwise false
1176 function can_edit_account($acctinfo) {
1177 if ($acctinfo['AccountType'] == 'Developer' ||
1178 $acctinfo['AccountType'] == 'Trusted User & Developer') {
1179 return has_credential(CRED_ACCOUNT_EDIT_DEV);
1182 $uid = $acctinfo['ID'];
1183 return has_credential(CRED_ACCOUNT_EDIT, array($uid));
1187 * Compute the fingerprint of an SSH key.
1189 * @param string $ssh_key The SSH public key to retrieve the fingerprint for
1191 * @return string The SSH key fingerprint
1193 function ssh_key_fingerprint($ssh_key) {
1194 $tmpfile = tempnam(sys_get_temp_dir(), "aurweb");
1195 file_put_contents($tmpfile, $ssh_key);
1198 * The -l option of ssh-keygen can be used to show the fingerprint of
1199 * the specified public key file. Expected output format:
1201 * 2048 SHA256:uBBTXmCNjI2CnLfkuz9sG8F+e9/T4C+qQQwLZWIODBY user@host (RSA)
1203 * ... where 2048 is the key length, the second token is the actual
1204 * fingerprint, followed by the key comment and the key type.
1207 $cmd = "/usr/bin/ssh-keygen -l -f " . escapeshellarg($tmpfile);
1208 exec($cmd, $out, $ret);
1209 if ($ret !== 0 || count($out) !== 1) {
1210 return false;
1213 unlink($tmpfile);
1215 $tokens = explode(' ', $out[0]);
1216 if (count($tokens) < 4) {
1217 return false;
1220 $tokens = explode(':', $tokens[1]);
1221 if (count($tokens) != 2 || $tokens[0] != 'SHA256') {
1222 return false;
1225 return $tokens[1];
1229 * Get the SSH public keys associated with an account.
1231 * @param int $uid The user ID of the account to retrieve the keys for.
1233 * @return array An array representing the keys
1235 function account_get_ssh_keys($uid) {
1236 $dbh = DB::connect();
1237 $q = "SELECT PubKey FROM SSHPubKeys WHERE UserID = " . intval($uid);
1238 $result = $dbh->query($q);
1240 if ($result) {
1241 return $result->fetchAll(PDO::FETCH_COLUMN, 0);
1242 } else {
1243 return array();
1248 * Set the SSH public keys associated with an account.
1250 * @param int $uid The user ID of the account to assign the keys to.
1251 * @param array $ssh_keys The SSH public keys.
1252 * @param array $ssh_fingerprints The corresponding SSH key fingerprints.
1254 * @return bool Boolean flag indicating success or failure.
1256 function account_set_ssh_keys($uid, $ssh_keys, $ssh_fingerprints) {
1257 $dbh = DB::connect();
1259 $q = sprintf("DELETE FROM SSHPubKeys WHERE UserID = %d", $uid);
1260 $dbh->exec($q);
1262 $ssh_fingerprint = reset($ssh_fingerprints);
1263 foreach ($ssh_keys as $ssh_key) {
1264 $q = sprintf(
1265 "INSERT INTO SSHPubKeys (UserID, Fingerprint, PubKey) " .
1266 "VALUES (%d, %s, %s)", $uid,
1267 $dbh->quote($ssh_fingerprint), $dbh->quote($ssh_key)
1269 $dbh->exec($q);
1270 $ssh_fingerprint = next($ssh_fingerprints);
1273 return true;
1277 * Invoke the email notification script.
1279 * @param string $params Command line parameters for the script.
1281 * @return void
1283 function notify($params) {
1284 $cmd = config_get('notifications', 'notify-cmd');
1285 foreach ($params as $param) {
1286 $cmd .= ' ' . escapeshellarg($param);
1289 $descspec = array(
1290 0 => array('pipe', 'r'),
1291 1 => array('pipe', 'w'),
1292 2 => array('pipe', 'w')
1295 $p = proc_open($cmd, $descspec, $pipes);
1297 if (!is_resource($p)) {
1298 return false;
1301 fclose($pipes[0]);
1302 fclose($pipes[1]);
1303 fclose($pipes[2]);
1305 return proc_close($p);