git-interface: Add test suite and basic tests
[aur.git] / web / lib / acctfuncs.inc.php
blob172b9621281686ccb7dc7a68cf0e689e3b1e4bce
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 $HP The homepage of the displayed user
56 * @param string $I The IRC nickname of the displayed user
57 * @param string $K The PGP key fingerprint of the displayed user
58 * @param string $PK The list of SSH public keys
59 * @param string $J The inactivity status of the displayed user
60 * @param string $CN Whether to notify of new comments
61 * @param string $UN Whether to notify of package updates
62 * @param string $ON Whether to notify of ownership changes
63 * @param string $UID The user ID of the displayed user
64 * @param string $N The username as present in the database
66 * @return void
68 function display_account_form($A,$U="",$T="",$S="",$E="",$H="",$P="",$C="",$R="",
69 $L="",$HP="",$I="",$K="",$PK="",$J="",$CN="",$UN="",$ON="",$UID=0,$N="") {
70 global $SUPPORTED_LANGS;
72 include("account_edit_form.php");
73 return;
76 /**
77 * Process information given to new/edit account form
79 * @global array $SUPPORTED_LANGS Languages that are supported by the AUR
80 * @param string $TYPE Either "edit" for editing or "new" for registering an account
81 * @param string $A Form to use, either UpdateAccount or NewAccount
82 * @param string $U The username for the account
83 * @param string $T The account type for the user
84 * @param string $S Whether or not the account is suspended
85 * @param string $E The e-mail address for the user
86 * @param string $H Whether or not the e-mail address should be hidden
87 * @param string $P The password for the user
88 * @param string $C The confirmed password for the user
89 * @param string $R The real name of the user
90 * @param string $L The language preference of the user
91 * @param string $HP The homepage of the displayed user
92 * @param string $I The IRC nickname of the user
93 * @param string $K The PGP fingerprint of the user
94 * @param string $PK The list of public SSH keys
95 * @param string $J The inactivity status of the user
96 * @param string $CN Whether to notify of new comments
97 * @param string $UN Whether to notify of package updates
98 * @param string $ON Whether to notify of ownership changes
99 * @param string $UID The user ID of the modified account
100 * @param string $N The username as present in the database
102 * @return array Boolean indicating success and message to be printed
104 function process_account_form($TYPE,$A,$U="",$T="",$S="",$E="",$H="",$P="",$C="",
105 $R="",$L="",$HP="",$I="",$K="",$PK="",$J="",$CN="",$UN="",$ON="",$UID=0,$N="") {
106 global $SUPPORTED_LANGS;
108 $error = '';
109 $message = '';
111 if (is_ipbanned()) {
112 $error = __('Account registration has been disabled ' .
113 'for your IP address, probably due ' .
114 'to sustained spam attacks. Sorry for the ' .
115 'inconvenience.');
118 $dbh = DB::connect();
120 if(isset($_COOKIE['AURSID'])) {
121 $editor_user = uid_from_sid($_COOKIE['AURSID']);
123 else {
124 $editor_user = null;
127 if (empty($E) || empty($U)) {
128 $error = __("Missing a required field.");
131 if ($TYPE != "new" && !$UID) {
132 $error = __("Missing User ID");
135 if (!$error && !valid_username($U)) {
136 $length_min = config_get_int('options', 'username_min_len');
137 $length_max = config_get_int('options', 'username_max_len');
139 $error = __("The username is invalid.") . "<ul>\n"
140 . "<li>" . __("It must be between %s and %s characters long", $length_min, $length_max)
141 . "</li>"
142 . "<li>" . __("Start and end with a letter or number") . "</li>"
143 . "<li>" . __("Can contain only one period, underscore or hyphen.")
144 . "</li>\n</ul>";
147 if (!$error && $P && $C && ($P != $C)) {
148 $error = __("Password fields do not match.");
150 if (!$error && $P != '' && !good_passwd($P)) {
151 $length_min = config_get_int('options', 'passwd_min_len');
152 $error = __("Your password must be at least %s characters.",
153 $length_min);
156 if (!$error && !valid_email($E)) {
157 $error = __("The email address is invalid.");
160 if (!$error && $K != '' && !valid_pgp_fingerprint($K)) {
161 $error = __("The PGP key fingerprint is invalid.");
164 if (!$error && !empty($PK)) {
165 $ssh_keys = array_filter(array_map('trim', explode("\n", $PK)));
166 $ssh_fingerprints = array();
168 foreach ($ssh_keys as &$ssh_key) {
169 if (!valid_ssh_pubkey($ssh_key)) {
170 $error = __("The SSH public key is invalid.");
171 break;
174 $ssh_fingerprint = ssh_key_fingerprint($ssh_key);
175 if (!$ssh_fingerprint) {
176 $error = __("The SSH public key is invalid.");
177 break;
180 $tokens = explode(" ", $ssh_key);
181 $ssh_key = $tokens[0] . " " . $tokens[1];
183 $ssh_fingerprints[] = $ssh_fingerprint;
187 * Destroy last reference to prevent accidentally overwriting
188 * an array element.
190 unset($ssh_key);
193 if (isset($_COOKIE['AURSID'])) {
194 $atype = account_from_sid($_COOKIE['AURSID']);
195 if (($atype == "User" && $T > 1) || ($atype == "Trusted User" && $T > 2)) {
196 $error = __("Cannot increase account permissions.");
200 if (!$error && !array_key_exists($L, $SUPPORTED_LANGS)) {
201 $error = __("Language is not currently supported.");
203 if (!$error) {
205 * Check whether the user name is available.
206 * TODO: Fix race condition.
208 $q = "SELECT COUNT(*) AS CNT FROM Users ";
209 $q.= "WHERE Username = " . $dbh->quote($U);
210 if ($TYPE == "edit") {
211 $q.= " AND ID != ".intval($UID);
213 $result = $dbh->query($q);
214 $row = $result->fetch(PDO::FETCH_NUM);
216 if ($row[0]) {
217 $error = __("The username, %s%s%s, is already in use.",
218 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
221 if (!$error) {
223 * Check whether the e-mail address is available.
224 * TODO: Fix race condition.
226 $q = "SELECT COUNT(*) AS CNT FROM Users ";
227 $q.= "WHERE Email = " . $dbh->quote($E);
228 if ($TYPE == "edit") {
229 $q.= " AND ID != ".intval($UID);
231 $result = $dbh->query($q);
232 $row = $result->fetch(PDO::FETCH_NUM);
234 if ($row[0]) {
235 $error = __("The address, %s%s%s, is already in use.",
236 "<strong>", htmlspecialchars($E,ENT_QUOTES), "</strong>");
239 if (!$error && count($ssh_keys) > 0) {
241 * Check whether any of the SSH public keys is already in use.
242 * TODO: Fix race condition.
244 $q = "SELECT Fingerprint FROM SSHPubKeys ";
245 $q.= "WHERE Fingerprint IN (";
246 $q.= implode(',', array_map(array($dbh, 'quote'), $ssh_fingerprints));
247 $q.= ")";
248 if ($TYPE == "edit") {
249 $q.= " AND UserID != " . intval($UID);
251 $result = $dbh->query($q);
252 $row = $result->fetch(PDO::FETCH_NUM);
254 if ($row) {
255 $error = __("The SSH public key, %s%s%s, is already in use.",
256 "<strong>", htmlspecialchars($row[0], ENT_QUOTES), "</strong>");
260 if ($error) {
261 $message = "<ul class='errorlist'><li>".$error."</li></ul>\n";
262 return array(false, $message);
265 if ($TYPE == "new") {
266 /* Create an unprivileged user. */
267 $salt = generate_salt();
268 if (empty($P)) {
269 $send_resetkey = true;
270 $email = $E;
271 } else {
272 $send_resetkey = false;
273 $P = salted_hash($P, $salt);
275 $U = $dbh->quote($U);
276 $E = $dbh->quote($E);
277 $P = $dbh->quote($P);
278 $salt = $dbh->quote($salt);
279 $R = $dbh->quote($R);
280 $L = $dbh->quote($L);
281 $HP = $dbh->quote($HP);
282 $I = $dbh->quote($I);
283 $K = $dbh->quote(str_replace(" ", "", $K));
284 $q = "INSERT INTO Users (AccountTypeID, Suspended, ";
285 $q.= "InactivityTS, Username, Email, Passwd, Salt, ";
286 $q.= "RealName, LangPreference, Homepage, IRCNick, PGPKey) ";
287 $q.= "VALUES (1, 0, 0, $U, $E, $P, $salt, $R, $L, ";
288 $q.= "$HP, $I, $K)";
289 $result = $dbh->exec($q);
290 if (!$result) {
291 $message = __("Error trying to create account, %s%s%s.",
292 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
293 return array(false, $message);
296 $uid = $dbh->lastInsertId();
297 account_set_ssh_keys($uid, $ssh_keys, $ssh_fingerprints);
299 $message = __("The account, %s%s%s, has been successfully created.",
300 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
301 $message .= "<p>\n";
303 if ($send_resetkey) {
304 send_resetkey($email, true);
305 $message .= __("A password reset key has been sent to your e-mail address.");
306 $message .= "</p>\n";
307 } else {
308 $message .= __("Click on the Login link above to use your account.");
309 $message .= "</p>\n";
311 } else {
312 /* Modify an existing account. */
313 $q = "SELECT InactivityTS FROM Users WHERE ";
314 $q.= "ID = " . intval($UID);
315 $result = $dbh->query($q);
316 $row = $result->fetch(PDO::FETCH_NUM);
317 if ($row[0] && $J) {
318 $inactivity_ts = $row[0];
319 } elseif ($J) {
320 $inactivity_ts = time();
321 } else {
322 $inactivity_ts = 0;
325 $q = "UPDATE Users SET ";
326 $q.= "Username = " . $dbh->quote($U);
327 if ($T) {
328 $q.= ", AccountTypeID = ".intval($T);
330 if ($S) {
331 /* Ensure suspended users can't keep an active session */
332 delete_user_sessions($UID);
333 $q.= ", Suspended = 1";
334 } else {
335 $q.= ", Suspended = 0";
337 $q.= ", Email = " . $dbh->quote($E);
338 if ($H) {
339 $q.= ", HideEmail = 1";
340 } else {
341 $q.= ", HideEmail = 0";
343 if ($P) {
344 $salt = generate_salt();
345 $hash = salted_hash($P, $salt);
346 $q .= ", Passwd = '$hash', Salt = '$salt'";
348 $q.= ", RealName = " . $dbh->quote($R);
349 $q.= ", LangPreference = " . $dbh->quote($L);
350 $q.= ", Homepage = " . $dbh->quote($HP);
351 $q.= ", IRCNick = " . $dbh->quote($I);
352 $q.= ", PGPKey = " . $dbh->quote(str_replace(" ", "", $K));
353 $q.= ", InactivityTS = " . $inactivity_ts;
354 $q.= ", CommentNotify = " . ($CN ? "1" : "0");
355 $q.= ", UpdateNotify = " . ($UN ? "1" : "0");
356 $q.= ", OwnershipNotify = " . ($ON ? "1" : "0");
357 $q.= " WHERE ID = ".intval($UID);
358 $result = $dbh->exec($q);
360 $ssh_key_result = account_set_ssh_keys($UID, $ssh_keys, $ssh_fingerprints);
362 if ($result === false || $ssh_key_result === false) {
363 $message = __("No changes were made to the account, %s%s%s.",
364 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
365 } else {
366 $message = __("The account, %s%s%s, has been successfully modified.",
367 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
371 return array(true, $message);
375 * Display the search results page
377 * @param string $O The offset for the results page
378 * @param string $SB The column to sort the results page by
379 * @param string $U The username search criteria
380 * @param string $T The account type search criteria
381 * @param string $S Whether the account is suspended search criteria
382 * @param string $E The e-mail address search criteria
383 * @param string $R The real name search criteria
384 * @param string $I The IRC nickname search criteria
385 * @param string $K The PGP key fingerprint search criteria
387 * @return void
389 function search_results_page($O=0,$SB="",$U="",$T="",
390 $S="",$E="",$R="",$I="",$K="") {
392 $HITS_PER_PAGE = 50;
393 if ($O) {
394 $OFFSET = intval($O);
395 } else {
396 $OFFSET = 0;
398 if ($OFFSET < 0) {
399 $OFFSET = 0;
401 $search_vars = array();
403 $dbh = DB::connect();
405 $q = "SELECT Users.*, AccountTypes.AccountType ";
406 $q.= "FROM Users, AccountTypes ";
407 $q.= "WHERE AccountTypes.ID = Users.AccountTypeID ";
408 if ($T == "u") {
409 $q.= "AND AccountTypes.ID = 1 ";
410 $search_vars[] = "T";
411 } elseif ($T == "t") {
412 $q.= "AND AccountTypes.ID = 2 ";
413 $search_vars[] = "T";
414 } elseif ($T == "d") {
415 $q.= "AND AccountTypes.ID = 3 ";
416 $search_vars[] = "T";
417 } elseif ($T == "td") {
418 $q.= "AND AccountTypes.ID = 4 ";
419 $search_vars[] = "T";
421 if ($S) {
422 $q.= "AND Users.Suspended = 1 ";
423 $search_vars[] = "S";
425 if ($U) {
426 $U = "%" . addcslashes($U, '%_') . "%";
427 $q.= "AND Username LIKE " . $dbh->quote($U) . " ";
428 $search_vars[] = "U";
430 if ($E) {
431 $E = "%" . addcslashes($E, '%_') . "%";
432 $q.= "AND Email LIKE " . $dbh->quote($E) . " ";
433 $search_vars[] = "E";
435 if ($R) {
436 $R = "%" . addcslashes($R, '%_') . "%";
437 $q.= "AND RealName LIKE " . $dbh->quote($R) . " ";
438 $search_vars[] = "R";
440 if ($I) {
441 $I = "%" . addcslashes($I, '%_') . "%";
442 $q.= "AND IRCNick LIKE " . $dbh->quote($I) . " ";
443 $search_vars[] = "I";
445 if ($K) {
446 $K = "%" . addcslashes(str_replace(" ", "", $K), '%_') . "%";
447 $q.= "AND PGPKey LIKE " . $dbh->quote($K) . " ";
448 $search_vars[] = "K";
450 switch ($SB) {
451 case 't':
452 $q.= "ORDER BY AccountTypeID, Username ";
453 break;
454 case 'r':
455 $q.= "ORDER BY RealName, AccountTypeID ";
456 break;
457 case 'i':
458 $q.= "ORDER BY IRCNick, AccountTypeID ";
459 break;
460 default:
461 $q.= "ORDER BY Username, AccountTypeID ";
462 break;
464 $search_vars[] = "SB";
465 $q.= "LIMIT " . $HITS_PER_PAGE . " OFFSET " . $OFFSET;
467 $dbh = DB::connect();
469 $result = $dbh->query($q);
471 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
472 $userinfo[] = $row;
475 include("account_search_results.php");
476 return;
480 * Attempt to login and generate a session
482 * @return array Session ID for user, error message if applicable
484 function try_login() {
485 $login_error = "";
486 $new_sid = "";
487 $userID = null;
489 if (!isset($_REQUEST['user']) && !isset($_REQUEST['passwd'])) {
490 return array('SID' => '', 'error' => null);
493 if (is_ipbanned()) {
494 $login_error = __('The login form is currently disabled ' .
495 'for your IP address, probably due ' .
496 'to sustained spam attacks. Sorry for the ' .
497 'inconvenience.');
498 return array('SID' => '', 'error' => $login_error);
501 $dbh = DB::connect();
502 $userID = uid_from_loginname($_REQUEST['user']);
504 if (user_suspended($userID)) {
505 $login_error = __('Account suspended');
506 return array('SID' => '', 'error' => $login_error);
507 } elseif (passwd_is_empty($userID)) {
508 $login_error = __('Your password has been reset. ' .
509 'If you just created a new account, please ' .
510 'use the link from the confirmation email ' .
511 'to set an initial password. Otherwise, ' .
512 'please request a reset key on the %s' .
513 'Password Reset%s page.', '<a href="' .
514 htmlspecialchars(get_uri('/passreset')) . '">',
515 '</a>');
516 return array('SID' => '', 'error' => $login_error);
517 } elseif (!valid_passwd($userID, $_REQUEST['passwd'])) {
518 $login_error = __("Bad username or password.");
519 return array('SID' => '', 'error' => $login_error);
522 $logged_in = 0;
523 $num_tries = 0;
525 /* Generate a session ID and store it. */
526 while (!$logged_in && $num_tries < 5) {
527 $session_limit = config_get_int('options', 'max_sessions_per_user');
528 if ($session_limit) {
530 * Delete all user sessions except the
531 * last ($session_limit - 1).
533 $q = "DELETE s.* FROM Sessions s ";
534 $q.= "LEFT JOIN (SELECT SessionID FROM Sessions ";
535 $q.= "WHERE UsersId = " . $userID . " ";
536 $q.= "ORDER BY LastUpdateTS DESC ";
537 $q.= "LIMIT " . ($session_limit - 1) . ") q ";
538 $q.= "ON s.SessionID = q.SessionID ";
539 $q.= "WHERE s.UsersId = " . $userID . " ";
540 $q.= "AND q.SessionID IS NULL;";
541 $dbh->query($q);
544 $new_sid = new_sid();
545 $q = "INSERT INTO Sessions (UsersID, SessionID, LastUpdateTS)"
546 ." VALUES (" . $userID . ", '" . $new_sid . "', UNIX_TIMESTAMP())";
547 $result = $dbh->exec($q);
549 /* Query will fail if $new_sid is not unique. */
550 if ($result) {
551 $logged_in = 1;
552 break;
555 $num_tries++;
558 if (!$logged_in) {
559 $login_error = __('An error occurred trying to generate a user session.');
560 return array('SID' => $new_sid, 'error' => $login_error);
563 $q = "UPDATE Users SET LastLogin = UNIX_TIMESTAMP(), ";
564 $q.= "LastLoginIPAddress = " . $dbh->quote($_SERVER['REMOTE_ADDR']) . " ";
565 $q.= "WHERE ID = $userID";
566 $dbh->exec($q);
568 /* Set the SID cookie. */
569 if (isset($_POST['remember_me']) && $_POST['remember_me'] == "on") {
570 /* Set cookies for 30 days. */
571 $timeout = config_get_int('options', 'persistent_cookie_timeout');
572 $cookie_time = time() + $timeout;
574 /* Set session for 30 days. */
575 $q = "UPDATE Sessions SET LastUpdateTS = $cookie_time ";
576 $q.= "WHERE SessionID = '$new_sid'";
577 $dbh->exec($q);
578 } else {
579 $cookie_time = 0;
582 setcookie("AURSID", $new_sid, $cookie_time, "/", null, !empty($_SERVER['HTTPS']), true);
584 $referer = in_request('referer');
585 if (strpos($referer, aur_location()) !== 0) {
586 $referer = '/';
588 header("Location: " . get_uri($referer));
589 $login_error = "";
593 * Determine if the user is using a banned IP address
595 * @return bool True if IP address is banned, otherwise false
597 function is_ipbanned() {
598 $dbh = DB::connect();
600 $q = "SELECT * FROM Bans WHERE IPAddress = " . $dbh->quote(ip2long($_SERVER['REMOTE_ADDR']));
601 $result = $dbh->query($q);
603 return ($result->fetchColumn() ? true : false);
607 * Validate a username against a collection of rules
609 * The username must be longer or equal to the configured minimum length. It
610 * must be shorter or equal to the configured maximum length. It must start and
611 * end with either a letter or a number. It can contain one period, hypen, or
612 * underscore. Returns boolean of whether name is valid.
614 * @param string $user Username to validate
616 * @return bool True if username meets criteria, otherwise false
618 function valid_username($user) {
619 $length_min = config_get_int('options', 'username_min_len');
620 $length_max = config_get_int('options', 'username_max_len');
622 if (strlen($user) < $length_min || strlen($user) > $length_max) {
623 return false;
624 } else if (!preg_match("/^[a-z0-9]+[.\-_]?[a-z0-9]+$/Di", $user)) {
625 return false;
628 return true;
632 * Determine if a user already has a proposal open about themselves
634 * @param string $user Username to checkout for open proposal
636 * @return bool True if there is an open proposal about the user, otherwise false
638 function open_user_proposals($user) {
639 $dbh = DB::connect();
640 $q = "SELECT * FROM TU_VoteInfo WHERE User = " . $dbh->quote($user) . " ";
641 $q.= "AND End > UNIX_TIMESTAMP()";
642 $result = $dbh->query($q);
644 return ($result->fetchColumn() ? true : false);
648 * Add a new Trusted User proposal to the database
650 * @param string $agenda The agenda of the vote
651 * @param string $user The use the vote is about
652 * @param int $votelength The length of time for the vote to last
653 * @param string $submitteruid The user ID of the individual who submitted the proposal
655 * @return void
657 function add_tu_proposal($agenda, $user, $votelength, $quorum, $submitteruid) {
658 $dbh = DB::connect();
660 $q = "SELECT COUNT(*) FROM Users WHERE (AccountTypeID = 2 OR AccountTypeID = 4)";
661 $result = $dbh->query($q);
662 $row = $result->fetch(PDO::FETCH_NUM);
663 $active_tus = $row[0];
665 $q = "INSERT INTO TU_VoteInfo (Agenda, User, Submitted, End, Quorum, ";
666 $q.= "SubmitterID, ActiveTUs) VALUES ";
667 $q.= "(" . $dbh->quote($agenda) . ", " . $dbh->quote($user) . ", ";
668 $q.= "UNIX_TIMESTAMP(), UNIX_TIMESTAMP() + " . $dbh->quote($votelength);
669 $q.= ", " . $dbh->quote($quorum) . ", " . $submitteruid . ", ";
670 $q.= $active_tus . ")";
671 $result = $dbh->exec($q);
675 * Add a reset key to the database for a specified user
677 * @param string $resetkey A password reset key to be stored in database
678 * @param string $uid The user ID to store the reset key for
680 * @return void
682 function create_resetkey($resetkey, $uid) {
683 $dbh = DB::connect();
684 $q = "UPDATE Users ";
685 $q.= "SET ResetKey = '" . $resetkey . "' ";
686 $q.= "WHERE ID = " . $uid;
687 $dbh->exec($q);
691 * Send a reset key to a specific e-mail address
693 * @param string $email E-mail address of the user resetting their password
694 * @param bool $welcome Whether to use the welcome message
696 * @return void
698 function send_resetkey($email, $welcome=false) {
699 $uid = uid_from_email($email);
700 if ($uid == null) {
701 return;
704 /* We (ab)use new_sid() to get a random 32 characters long string. */
705 $resetkey = new_sid();
706 create_resetkey($resetkey, $uid);
708 /* Send e-mail with confirmation link. */
709 notify(array($welcome ? 'welcome' : 'send-resetkey', $uid));
713 * Change a user's password in the database if reset key and e-mail are correct
715 * @param string $hash New MD5 hash of a user's password
716 * @param string $salt New salt for the user's password
717 * @param string $resetkey Code e-mailed to a user to reset a password
718 * @param string $email E-mail address of the user resetting their password
720 * @return string|void Redirect page if successful, otherwise return error message
722 function password_reset($hash, $salt, $resetkey, $email) {
723 $dbh = DB::connect();
724 $q = "UPDATE Users ";
725 $q.= "SET Passwd = '$hash', ";
726 $q.= "Salt = '$salt', ";
727 $q.= "ResetKey = '' ";
728 $q.= "WHERE ResetKey != '' ";
729 $q.= "AND ResetKey = " . $dbh->quote($resetkey) . " ";
730 $q.= "AND Email = " . $dbh->quote($email);
731 $result = $dbh->exec($q);
733 if (!$result) {
734 $error = __('Invalid e-mail and reset key combination.');
735 return $error;
736 } else {
737 header('Location: ' . get_uri('/passreset/') . '?step=complete');
738 exit();
743 * Determine if the password is longer than the minimum length
745 * @param string $passwd The password to check
747 * @return bool True if longer than minimum length, otherwise false
749 function good_passwd($passwd) {
750 $length_min = config_get_int('options', 'passwd_min_len');
751 return (strlen($passwd) >= $length_min);
755 * Determine if the password is correct and salt it if it hasn't been already
757 * @param string $userID The user ID to check the password against
758 * @param string $passwd The password the visitor sent
760 * @return bool True if password was correct and properly salted, otherwise false
762 function valid_passwd($userID, $passwd) {
763 $dbh = DB::connect();
764 if ($passwd == "") {
765 return false;
768 /* Get salt for this user. */
769 $salt = get_salt($userID);
770 if ($salt) {
771 $q = "SELECT ID FROM Users ";
772 $q.= "WHERE ID = " . $userID . " ";
773 $q.= "AND Passwd = " . $dbh->quote(salted_hash($passwd, $salt));
774 $result = $dbh->query($q);
775 if (!$result) {
776 return false;
779 $row = $result->fetch(PDO::FETCH_NUM);
780 return ($row[0] > 0);
781 } else {
782 /* Check password without using salt. */
783 $q = "SELECT ID FROM Users ";
784 $q.= "WHERE ID = " . $userID . " ";
785 $q.= "AND Passwd = " . $dbh->quote(md5($passwd));
786 $result = $dbh->query($q);
787 if (!$result) {
788 return false;
791 $row = $result->fetch(PDO::FETCH_NUM);
792 if (!$row[0]) {
793 return false;
796 /* Password correct, but salt it first! */
797 if (!save_salt($userID, $passwd)) {
798 trigger_error("Unable to salt user's password;" .
799 " ID " . $userID, E_USER_WARNING);
800 return false;
803 return true;
808 * Determine if a user's password is empty
810 * @param string $uid The user ID to check for an empty password
812 * @return bool True if the user's password is empty, otherwise false
814 function passwd_is_empty($uid) {
815 $dbh = DB::connect();
817 $q = "SELECT * FROM Users WHERE ID = " . $dbh->quote($uid) . " ";
818 $q .= "AND Passwd = " . $dbh->quote('');
819 $result = $dbh->query($q);
821 if ($result->fetchColumn()) {
822 return true;
823 } else {
824 return false;
829 * Determine if the PGP key fingerprint is valid (must be 40 hexadecimal digits)
831 * @param string $fingerprint PGP fingerprint to check if valid
833 * @return bool True if the fingerprint is 40 hexadecimal digits, otherwise false
835 function valid_pgp_fingerprint($fingerprint) {
836 $fingerprint = str_replace(" ", "", $fingerprint);
837 return (strlen($fingerprint) == 40 && ctype_xdigit($fingerprint));
841 * Determine if the SSH public key is valid
843 * @param string $pubkey SSH public key to check
845 * @return bool True if the SSH public key is valid, otherwise false
847 function valid_ssh_pubkey($pubkey) {
848 $valid_prefixes = array(
849 "ssh-rsa", "ssh-dss", "ecdsa-sha2-nistp256",
850 "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521", "ssh-ed25519"
853 $has_valid_prefix = false;
854 foreach ($valid_prefixes as $prefix) {
855 if (strpos($pubkey, $prefix . " ") === 0) {
856 $has_valid_prefix = true;
857 break;
860 if (!$has_valid_prefix) {
861 return false;
864 $tokens = explode(" ", $pubkey);
865 if (empty($tokens[1])) {
866 return false;
869 return (base64_encode(base64_decode($tokens[1], true)) == $tokens[1]);
873 * Determine if the user account has been suspended
875 * @param string $id The ID of user to check if suspended
877 * @return bool True if the user is suspended, otherwise false
879 function user_suspended($id) {
880 $dbh = DB::connect();
881 if (!$id) {
882 return false;
884 $q = "SELECT Suspended FROM Users WHERE ID = " . $id;
885 $result = $dbh->query($q);
886 if ($result) {
887 $row = $result->fetch(PDO::FETCH_NUM);
888 if ($row[0]) {
889 return true;
892 return false;
896 * Delete a specified user account from the database
898 * @param int $id The user ID of the account to be deleted
900 * @return void
902 function user_delete($id) {
903 $dbh = DB::connect();
904 $id = intval($id);
907 * These are normally already taken care of by propagation constraints
908 * but it is better to be explicit here.
910 $fields_delete = array(
911 array("Sessions", "UsersID"),
912 array("PackageVotes", "UsersID"),
913 array("PackageNotifications", "UsersID")
916 $fields_set_null = array(
917 array("PackageBases", "SubmitterUID"),
918 array("PackageBases", "MaintainerUID"),
919 array("PackageBases", "SubmitterUID"),
920 array("PackageComments", "UsersID"),
921 array("PackageComments", "DelUsersID"),
922 array("PackageRequests", "UsersID"),
923 array("TU_VoteInfo", "SubmitterID"),
924 array("TU_Votes", "UserID")
927 foreach($fields_delete as list($table, $field)) {
928 $q = "DELETE FROM " . $table . " ";
929 $q.= "WHERE " . $field . " = " . $id;
930 $dbh->query($q);
933 foreach($fields_set_null as list($table, $field)) {
934 $q = "UPDATE " . $table . " SET " . $field . " = NULL ";
935 $q.= "WHERE " . $field . " = " . $id;
936 $dbh->query($q);
939 $q = "DELETE FROM Users WHERE ID = " . $id;
940 $dbh->query($q);
941 return;
945 * Remove the session from the database on logout
947 * @param string $sid User's session ID
949 * @return void
951 function delete_session_id($sid) {
952 $dbh = DB::connect();
954 $q = "DELETE FROM Sessions WHERE SessionID = " . $dbh->quote($sid);
955 $dbh->query($q);
959 * Remove all sessions belonging to a particular user
961 * @param int $uid ID of user to remove all sessions for
963 * @return void
965 function delete_user_sessions($uid) {
966 $dbh = DB::connect();
968 $q = "DELETE FROM Sessions WHERE UsersID = " . intval($uid);
969 $dbh->exec($q);
973 * Remove sessions from the database that have exceed the timeout
975 * @return void
977 function clear_expired_sessions() {
978 $dbh = DB::connect();
980 $timeout = config_get_int('options', 'login_timeout');
981 $q = "DELETE FROM Sessions WHERE LastUpdateTS < (UNIX_TIMESTAMP() - " . $timeout . ")";
982 $dbh->query($q);
984 return;
988 * Get account details for a specific user
990 * @param string $uid The User ID of account to get information for
991 * @param string $username The username of the account to get for
993 * @return array Account details for the specified user
995 function account_details($uid, $username) {
996 $dbh = DB::connect();
997 $q = "SELECT Users.*, AccountTypes.AccountType ";
998 $q.= "FROM Users, AccountTypes ";
999 $q.= "WHERE AccountTypes.ID = Users.AccountTypeID ";
1000 if (!empty($uid)) {
1001 $q.= "AND Users.ID = ".intval($uid);
1002 } else {
1003 $q.= "AND Users.Username = " . $dbh->quote($username);
1005 $result = $dbh->query($q);
1007 if ($result) {
1008 $row = $result->fetch(PDO::FETCH_ASSOC);
1011 return $row;
1015 * Determine if a user has already voted on a specific proposal
1017 * @param string $voteid The ID of the Trusted User proposal
1018 * @param string $uid The ID to check if the user already voted
1020 * @return bool True if the user has already voted, otherwise false
1022 function tu_voted($voteid, $uid) {
1023 $dbh = DB::connect();
1025 $q = "SELECT COUNT(*) FROM TU_Votes ";
1026 $q.= "WHERE VoteID = " . intval($voteid) . " AND UserID = " . intval($uid);
1027 $result = $dbh->query($q);
1028 if ($result->fetchColumn() > 0) {
1029 return true;
1031 else {
1032 return false;
1037 * Get all current Trusted User proposals from the database
1039 * @param string $order Ascending or descending order for the proposal listing
1041 * @return array The details for all current Trusted User proposals
1043 function current_proposal_list($order) {
1044 $dbh = DB::connect();
1046 $q = "SELECT * FROM TU_VoteInfo WHERE End > " . time() . " ORDER BY Submitted " . $order;
1047 $result = $dbh->query($q);
1049 $details = array();
1050 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
1051 $details[] = $row;
1054 return $details;
1058 * Get a subset of all past Trusted User proposals from the database
1060 * @param string $order Ascending or descending order for the proposal listing
1061 * @param string $lim The number of proposals to list with the offset
1063 * @return array The details for the subset of past Trusted User proposals
1065 function past_proposal_list($order, $lim) {
1066 $dbh = DB::connect();
1068 $q = "SELECT * FROM TU_VoteInfo WHERE End < " . time() . " ORDER BY Submitted " . $order . $lim;
1069 $result = $dbh->query($q);
1071 $details = array();
1072 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
1073 $details[] = $row;
1076 return $details;
1080 * Get the vote ID of the last vote of all Trusted Users
1082 * @return array The vote ID of the last vote of each Trusted User
1084 function last_votes_list() {
1085 $dbh = DB::connect();
1087 $q = "SELECT UserID, MAX(VoteID) AS LastVote FROM TU_Votes, ";
1088 $q .= "TU_VoteInfo, Users WHERE TU_VoteInfo.ID = TU_Votes.VoteID AND ";
1089 $q .= "TU_VoteInfo.End < UNIX_TIMESTAMP() AND ";
1090 $q .= "Users.ID = TU_Votes.UserID AND (Users.AccountTypeID = 2 OR Users.AccountTypeID = 4) ";
1091 $q .= "GROUP BY UserID ORDER BY LastVote DESC, UserName ASC";
1092 $result = $dbh->query($q);
1094 $details = array();
1095 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
1096 $details[] = $row;
1099 return $details;
1103 * Determine the total number of Trusted User proposals
1105 * @return string The total number of Trusted User proposals
1107 function proposal_count() {
1108 $dbh = DB::connect();
1109 $q = "SELECT COUNT(*) FROM TU_VoteInfo";
1110 $result = $dbh->query($q);
1111 $row = $result->fetch(PDO::FETCH_NUM);
1113 return $row[0];
1117 * Get all details related to a specific vote from the database
1119 * @param string $voteid The ID of the Trusted User proposal
1121 * @return array All stored details for a specific vote
1123 function vote_details($voteid) {
1124 $dbh = DB::connect();
1126 $q = "SELECT * FROM TU_VoteInfo ";
1127 $q.= "WHERE ID = " . intval($voteid);
1129 $result = $dbh->query($q);
1130 $row = $result->fetch(PDO::FETCH_ASSOC);
1132 return $row;
1136 * Get an alphabetical list of users who voted for a proposal with HTML links
1138 * @param string $voteid The ID of the Trusted User proposal
1140 * @return array All users who voted for a specific proposal
1142 function voter_list($voteid) {
1143 $dbh = DB::connect();
1145 $whovoted = array();
1147 $q = "SELECT tv.UserID,U.Username ";
1148 $q.= "FROM TU_Votes tv, Users U ";
1149 $q.= "WHERE tv.VoteID = " . intval($voteid);
1150 $q.= " AND tv.UserID = U.ID ";
1151 $q.= "ORDER BY Username";
1153 $result = $dbh->query($q);
1154 if ($result) {
1155 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
1156 $whovoted[] = $row['Username'];
1159 return $whovoted;
1163 * Cast a vote for a specific user proposal
1165 * @param string $voteid The ID of the proposal being voted on
1166 * @param string $uid The user ID of the individual voting
1167 * @param string $vote Vote position, either "Yes", "No", or "Abstain"
1168 * @param int $newtotal The total number of votes after the user has voted
1170 * @return void
1172 function cast_proposal_vote($voteid, $uid, $vote, $newtotal) {
1173 $dbh = DB::connect();
1175 $q = "UPDATE TU_VoteInfo SET " . $vote . " = (" . $newtotal . ") WHERE ID = " . $voteid;
1176 $result = $dbh->exec($q);
1178 $q = "INSERT INTO TU_Votes (VoteID, UserID) VALUES (" . intval($voteid) . ", " . intval($uid) . ")";
1179 $result = $dbh->exec($q);
1183 * Verify a user has the proper permissions to edit an account
1185 * @param array $acctinfo User account information for edited account
1187 * @return bool True if permission to edit the account, otherwise false
1189 function can_edit_account($acctinfo) {
1190 if ($acctinfo['AccountType'] == 'Developer' ||
1191 $acctinfo['AccountType'] == 'Trusted User & Developer') {
1192 return has_credential(CRED_ACCOUNT_EDIT_DEV);
1195 $uid = $acctinfo['ID'];
1196 return has_credential(CRED_ACCOUNT_EDIT, array($uid));
1200 * Compute the fingerprint of an SSH key.
1202 * @param string $ssh_key The SSH public key to retrieve the fingerprint for
1204 * @return string The SSH key fingerprint
1206 function ssh_key_fingerprint($ssh_key) {
1207 $tmpfile = tempnam(sys_get_temp_dir(), "aurweb");
1208 file_put_contents($tmpfile, $ssh_key);
1211 * The -l option of ssh-keygen can be used to show the fingerprint of
1212 * the specified public key file. Expected output format:
1214 * 2048 SHA256:uBBTXmCNjI2CnLfkuz9sG8F+e9/T4C+qQQwLZWIODBY user@host (RSA)
1216 * ... where 2048 is the key length, the second token is the actual
1217 * fingerprint, followed by the key comment and the key type.
1220 $cmd = "/usr/bin/ssh-keygen -l -f " . escapeshellarg($tmpfile);
1221 exec($cmd, $out, $ret);
1222 if ($ret !== 0 || count($out) !== 1) {
1223 return false;
1226 unlink($tmpfile);
1228 $tokens = explode(' ', $out[0]);
1229 if (count($tokens) < 4) {
1230 return false;
1233 $tokens = explode(':', $tokens[1]);
1234 if (count($tokens) != 2 || $tokens[0] != 'SHA256') {
1235 return false;
1238 return $tokens[1];
1242 * Get the SSH public keys associated with an account.
1244 * @param int $uid The user ID of the account to retrieve the keys for.
1246 * @return array An array representing the keys
1248 function account_get_ssh_keys($uid) {
1249 $dbh = DB::connect();
1250 $q = "SELECT PubKey FROM SSHPubKeys WHERE UserID = " . intval($uid);
1251 $result = $dbh->query($q);
1253 if ($result) {
1254 return $result->fetchAll(PDO::FETCH_COLUMN, 0);
1255 } else {
1256 return array();
1261 * Set the SSH public keys associated with an account.
1263 * @param int $uid The user ID of the account to assign the keys to.
1264 * @param array $ssh_keys The SSH public keys.
1265 * @param array $ssh_fingerprints The corresponding SSH key fingerprints.
1267 * @return bool Boolean flag indicating success or failure.
1269 function account_set_ssh_keys($uid, $ssh_keys, $ssh_fingerprints) {
1270 $dbh = DB::connect();
1272 $q = sprintf("DELETE FROM SSHPubKeys WHERE UserID = %d", $uid);
1273 $dbh->exec($q);
1275 $ssh_fingerprint = reset($ssh_fingerprints);
1276 foreach ($ssh_keys as $ssh_key) {
1277 $q = sprintf(
1278 "INSERT INTO SSHPubKeys (UserID, Fingerprint, PubKey) " .
1279 "VALUES (%d, %s, %s)", $uid,
1280 $dbh->quote($ssh_fingerprint), $dbh->quote($ssh_key)
1282 $dbh->exec($q);
1283 $ssh_fingerprint = next($ssh_fingerprints);
1286 return true;
1290 * Invoke the email notification script.
1292 * @param string $params Command line parameters for the script.
1294 * @return void
1296 function notify($params) {
1297 $cmd = config_get('notifications', 'notify-cmd');
1298 foreach ($params as $param) {
1299 $cmd .= ' ' . escapeshellarg($param);
1302 $descspec = array(
1303 0 => array('pipe', 'r'),
1304 1 => array('pipe', 'w'),
1305 2 => array('pipe', 'w')
1308 $p = proc_open($cmd, $descspec, $pipes);
1310 if (!is_resource($p)) {
1311 return false;
1314 fclose($pipes[0]);
1315 fclose($pipes[1]);
1316 fclose($pipes[2]);
1318 return proc_close($p);