Only print no changes message if queries failed
[aur.git] / web / lib / acctfuncs.inc.php
blob861de0ac3bac473846006e488be9dfd09dc96d38
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 $P The password value of the displayed user
51 * @param string $C The confirmed password value of the displayed user
52 * @param string $R The real name of the displayed user
53 * @param string $L The language preference of the displayed user
54 * @param string $I The IRC nickname of the displayed user
55 * @param string $K The PGP key fingerprint of the displayed user
56 * @param string $PK The list of SSH public keys
57 * @param string $J The inactivity status of the displayed user
58 * @param string $UID The user ID of the displayed user
60 * @return void
62 function display_account_form($A,$U="",$T="",$S="",$E="",$P="",$C="",$R="",
63 $L="",$I="",$K="",$PK="",$J="", $UID=0) {
64 global $SUPPORTED_LANGS;
66 include("account_edit_form.php");
67 return;
70 /**
71 * Process information given to new/edit account form
73 * @global array $SUPPORTED_LANGS Languages that are supported by the AUR
74 * @param string $TYPE Either "edit" for editing or "new" for registering an account
75 * @param string $A Form to use, either UpdateAccount or NewAccount
76 * @param string $U The username for the account
77 * @param string $T The account type for the user
78 * @param string $S Whether or not the account is suspended
79 * @param string $E The e-mail address for the user
80 * @param string $P The password for the user
81 * @param string $C The confirmed password for the user
82 * @param string $R The real name of the user
83 * @param string $L The language preference of the user
84 * @param string $I The IRC nickname of the user
85 * @param string $K The PGP fingerprint of the user
86 * @param string $PK The list of public SSH keys
87 * @param string $J The inactivity status of the user
88 * @param string $UID The user ID of the modified account
90 * @return string|void Return void if successful, otherwise return error
92 function process_account_form($TYPE,$A,$U="",$T="",$S="",$E="",$P="",$C="",
93 $R="",$L="",$I="",$K="",$PK="",$J="",$UID=0) {
94 global $SUPPORTED_LANGS;
96 $error = '';
98 if (is_ipbanned()) {
99 $error = __('Account registration has been disabled ' .
100 'for your IP address, probably due ' .
101 'to sustained spam attacks. Sorry for the ' .
102 'inconvenience.');
105 $dbh = DB::connect();
107 if(isset($_COOKIE['AURSID'])) {
108 $editor_user = uid_from_sid($_COOKIE['AURSID']);
110 else {
111 $editor_user = null;
114 if (empty($E) || empty($U)) {
115 $error = __("Missing a required field.");
118 if ($TYPE != "new" && !$UID) {
119 $error = __("Missing User ID");
122 if (!$error && !valid_username($U)) {
123 $length_min = config_get_int('options', 'username_min_len');
124 $length_max = config_get_int('options', 'username_max_len');
126 $error = __("The username is invalid.") . "<ul>\n"
127 . "<li>" . __("It must be between %s and %s characters long", $length_min, $length_max)
128 . "</li>"
129 . "<li>" . __("Start and end with a letter or number") . "</li>"
130 . "<li>" . __("Can contain only one period, underscore or hyphen.")
131 . "</li>\n</ul>";
134 if (!$error && $P && $C && ($P != $C)) {
135 $error = __("Password fields do not match.");
137 if (!$error && $P != '' && !good_passwd($P)) {
138 $length_min = config_get_int('options', 'passwd_min_len');
139 $error = __("Your password must be at least %s characters.",
140 $length_min);
143 if (!$error && !valid_email($E)) {
144 $error = __("The email address is invalid.");
147 if (!$error && $K != '' && !valid_pgp_fingerprint($K)) {
148 $error = __("The PGP key fingerprint is invalid.");
151 if (!$error && !empty($PK)) {
152 $ssh_keys = array_filter(array_map('trim', explode("\n", $PK)));
153 $ssh_fingerprints = array();
155 foreach ($ssh_keys as &$ssh_key) {
156 if (!valid_ssh_pubkey($ssh_key)) {
157 $error = __("The SSH public key is invalid.");
158 break;
161 $ssh_fingerprint = ssh_key_fingerprint($ssh_key);
162 if (!$ssh_fingerprint) {
163 $error = __("The SSH public key is invalid.");
164 break;
167 $tokens = explode(" ", $ssh_key);
168 $ssh_key = $tokens[0] . " " . $tokens[1];
170 $ssh_fingerprints[] = $ssh_fingerprint;
174 * Destroy last reference to prevent accidentally overwriting
175 * an array element.
177 unset($ssh_key);
180 if (isset($_COOKIE['AURSID'])) {
181 $atype = account_from_sid($_COOKIE['AURSID']);
182 if (($atype == "User" && $T > 1) || ($atype == "Trusted User" && $T > 2)) {
183 $error = __("Cannot increase account permissions.");
187 if (!$error && !array_key_exists($L, $SUPPORTED_LANGS)) {
188 $error = __("Language is not currently supported.");
190 if (!$error) {
192 * Check whether the user name is available.
193 * TODO: Fix race condition.
195 $q = "SELECT COUNT(*) AS CNT FROM Users ";
196 $q.= "WHERE Username = " . $dbh->quote($U);
197 if ($TYPE == "edit") {
198 $q.= " AND ID != ".intval($UID);
200 $result = $dbh->query($q);
201 $row = $result->fetch(PDO::FETCH_NUM);
203 if ($row[0]) {
204 $error = __("The username, %s%s%s, is already in use.",
205 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
208 if (!$error) {
210 * Check whether the e-mail address is available.
211 * TODO: Fix race condition.
213 $q = "SELECT COUNT(*) AS CNT FROM Users ";
214 $q.= "WHERE Email = " . $dbh->quote($E);
215 if ($TYPE == "edit") {
216 $q.= " AND ID != ".intval($UID);
218 $result = $dbh->query($q);
219 $row = $result->fetch(PDO::FETCH_NUM);
221 if ($row[0]) {
222 $error = __("The address, %s%s%s, is already in use.",
223 "<strong>", htmlspecialchars($E,ENT_QUOTES), "</strong>");
226 if (!$error && count($ssh_keys) > 0) {
228 * Check whether any of the SSH public keys is already in use.
229 * TODO: Fix race condition.
231 $q = "SELECT Fingerprint FROM SSHPubKeys ";
232 $q.= "WHERE Fingerprint IN (";
233 $q.= implode(',', array_map(array($dbh, 'quote'), $ssh_fingerprints));
234 $q.= ")";
235 if ($TYPE == "edit") {
236 $q.= " AND UserID != " . intval($UID);
238 $result = $dbh->query($q);
239 $row = $result->fetch(PDO::FETCH_NUM);
241 if ($row) {
242 $error = __("The SSH public key, %s%s%s, is already in use.",
243 "<strong>", htmlspecialchars($row[0], ENT_QUOTES), "</strong>");
247 if ($error) {
248 print "<ul class='errorlist'><li>".$error."</li></ul>\n";
249 display_account_form($A, $U, $T, $S, $E, "", "",
250 $R, $L, $I, $K, $PK, $J, $UID);
251 return;
254 if ($TYPE == "new") {
255 /* Create an unprivileged user. */
256 $salt = generate_salt();
257 if (empty($P)) {
258 $send_resetkey = true;
259 $email = $E;
260 } else {
261 $send_resetkey = false;
262 $P = salted_hash($P, $salt);
264 $U = $dbh->quote($U);
265 $E = $dbh->quote($E);
266 $P = $dbh->quote($P);
267 $salt = $dbh->quote($salt);
268 $R = $dbh->quote($R);
269 $L = $dbh->quote($L);
270 $I = $dbh->quote($I);
271 $K = $dbh->quote(str_replace(" ", "", $K));
272 $q = "INSERT INTO Users (AccountTypeID, Suspended, ";
273 $q.= "InactivityTS, Username, Email, Passwd, Salt, ";
274 $q.= "RealName, LangPreference, IRCNick, PGPKey) ";
275 $q.= "VALUES (1, 0, 0, $U, $E, $P, $salt, $R, $L, ";
276 $q.= "$I, $K)";
277 $result = $dbh->exec($q);
278 if (!$result) {
279 print __("Error trying to create account, %s%s%s.",
280 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
281 return;
284 $uid = $dbh->lastInsertId();
285 account_set_ssh_keys($uid, $ssh_keys, $ssh_fingerprints);
287 print __("The account, %s%s%s, has been successfully created.",
288 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
289 print "<p>\n";
291 if (!$send_resetkey) {
292 print __("Click on the Login link above to use your account.");
293 print "</p>\n";
294 return;
297 $subject = 'Welcome to the Arch User Repository';
298 $body = __('Welcome to %s! In order ' .
299 'to set an initial password ' .
300 'for your new account, ' .
301 'please click the link ' .
302 'below. If the link does ' .
303 'not work try copying and ' .
304 'pasting it into your ' .
305 'browser.',
306 aur_location());
307 send_resetkey($email, $subject, $body);
309 print __("A password reset key has been sent to your e-mail address.");
310 print "</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 ($P) {
339 $salt = generate_salt();
340 $hash = salted_hash($P, $salt);
341 $q .= ", Passwd = '$hash', Salt = '$salt'";
343 $q.= ", RealName = " . $dbh->quote($R);
344 $q.= ", LangPreference = " . $dbh->quote($L);
345 $q.= ", IRCNick = " . $dbh->quote($I);
346 $q.= ", PGPKey = " . $dbh->quote(str_replace(" ", "", $K));
347 $q.= ", InactivityTS = " . $inactivity_ts;
348 $q.= " WHERE ID = ".intval($UID);
349 $result = $dbh->exec($q);
351 $ssh_key_result = account_set_ssh_keys($UID, $ssh_keys, $ssh_fingerprints);
353 if ($result === false || $ssh_key_result === false) {
354 print __("No changes were made to the account, %s%s%s.",
355 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
356 } else {
357 print __("The account, %s%s%s, has been successfully modified.",
358 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
364 * Display the search results page
366 * @param string $O The offset for the results page
367 * @param string $SB The column to sort the results page by
368 * @param string $U The username search criteria
369 * @param string $T The account type search criteria
370 * @param string $S Whether the account is suspended search criteria
371 * @param string $E The e-mail address search criteria
372 * @param string $R The real name search criteria
373 * @param string $I The IRC nickname search criteria
374 * @param string $K The PGP key fingerprint search criteria
376 * @return void
378 function search_results_page($O=0,$SB="",$U="",$T="",
379 $S="",$E="",$R="",$I="",$K="") {
381 $HITS_PER_PAGE = 50;
382 if ($O) {
383 $OFFSET = intval($O);
384 } else {
385 $OFFSET = 0;
387 if ($OFFSET < 0) {
388 $OFFSET = 0;
390 $search_vars = array();
392 $dbh = DB::connect();
394 $q = "SELECT Users.*, AccountTypes.AccountType ";
395 $q.= "FROM Users, AccountTypes ";
396 $q.= "WHERE AccountTypes.ID = Users.AccountTypeID ";
397 if ($T == "u") {
398 $q.= "AND AccountTypes.ID = 1 ";
399 $search_vars[] = "T";
400 } elseif ($T == "t") {
401 $q.= "AND AccountTypes.ID = 2 ";
402 $search_vars[] = "T";
403 } elseif ($T == "d") {
404 $q.= "AND AccountTypes.ID = 3 ";
405 $search_vars[] = "T";
406 } elseif ($T == "td") {
407 $q.= "AND AccountTypes.ID = 4 ";
408 $search_vars[] = "T";
410 if ($S) {
411 $q.= "AND Users.Suspended = 1 ";
412 $search_vars[] = "S";
414 if ($U) {
415 $U = "%" . addcslashes($U, '%_') . "%";
416 $q.= "AND Username LIKE " . $dbh->quote($U) . " ";
417 $search_vars[] = "U";
419 if ($E) {
420 $E = "%" . addcslashes($E, '%_') . "%";
421 $q.= "AND Email LIKE " . $dbh->quote($E) . " ";
422 $search_vars[] = "E";
424 if ($R) {
425 $R = "%" . addcslashes($R, '%_') . "%";
426 $q.= "AND RealName LIKE " . $dbh->quote($R) . " ";
427 $search_vars[] = "R";
429 if ($I) {
430 $I = "%" . addcslashes($I, '%_') . "%";
431 $q.= "AND IRCNick LIKE " . $dbh->quote($I) . " ";
432 $search_vars[] = "I";
434 if ($K) {
435 $K = "%" . addcslashes(str_replace(" ", "", $K), '%_') . "%";
436 $q.= "AND PGPKey LIKE " . $dbh->quote($K) . " ";
437 $search_vars[] = "K";
439 switch ($SB) {
440 case 't':
441 $q.= "ORDER BY AccountTypeID, Username ";
442 break;
443 case 'r':
444 $q.= "ORDER BY RealName, AccountTypeID ";
445 break;
446 case 'i':
447 $q.= "ORDER BY IRCNick, AccountTypeID ";
448 break;
449 default:
450 $q.= "ORDER BY Username, AccountTypeID ";
451 break;
453 $search_vars[] = "SB";
454 $q.= "LIMIT " . $HITS_PER_PAGE . " OFFSET " . $OFFSET;
456 $dbh = DB::connect();
458 $result = $dbh->query($q);
460 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
461 $userinfo[] = $row;
464 include("account_search_results.php");
465 return;
469 * Attempt to login and generate a session
471 * @return array Session ID for user, error message if applicable
473 function try_login() {
474 $login_error = "";
475 $new_sid = "";
476 $userID = null;
478 if (!isset($_REQUEST['user']) && !isset($_REQUEST['passwd'])) {
479 return array('SID' => '', 'error' => null);
482 if (is_ipbanned()) {
483 $login_error = __('The login form is currently disabled ' .
484 'for your IP address, probably due ' .
485 'to sustained spam attacks. Sorry for the ' .
486 'inconvenience.');
487 return array('SID' => '', 'error' => $login_error);
490 $dbh = DB::connect();
491 $userID = valid_user($_REQUEST['user']);
493 if (user_suspended($userID)) {
494 $login_error = __('Account suspended');
495 return array('SID' => '', 'error' => $login_error);
496 } elseif (passwd_is_empty($userID)) {
497 $login_error = __('Your password has been reset. ' .
498 'If you just created a new account, please ' .
499 'use the link from the confirmation email ' .
500 'to set an initial password. Otherwise, ' .
501 'please request a reset key on the %s' .
502 'Password Reset%s page.', '<a href="' .
503 htmlspecialchars(get_uri('/passreset')) . '">',
504 '</a>');
505 return array('SID' => '', 'error' => $login_error);
506 } elseif (!valid_passwd($userID, $_REQUEST['passwd'])) {
507 $login_error = __("Bad username or password.");
508 return array('SID' => '', 'error' => $login_error);
511 $logged_in = 0;
512 $num_tries = 0;
514 /* Generate a session ID and store it. */
515 while (!$logged_in && $num_tries < 5) {
516 $session_limit = config_get_int('options', 'max_sessions_per_user');
517 if ($session_limit) {
519 * Delete all user sessions except the
520 * last ($session_limit - 1).
522 $q = "DELETE s.* FROM Sessions s ";
523 $q.= "LEFT JOIN (SELECT SessionID FROM Sessions ";
524 $q.= "WHERE UsersId = " . $userID . " ";
525 $q.= "ORDER BY LastUpdateTS DESC ";
526 $q.= "LIMIT " . ($session_limit - 1) . ") q ";
527 $q.= "ON s.SessionID = q.SessionID ";
528 $q.= "WHERE s.UsersId = " . $userID . " ";
529 $q.= "AND q.SessionID IS NULL;";
530 $dbh->query($q);
533 $new_sid = new_sid();
534 $q = "INSERT INTO Sessions (UsersID, SessionID, LastUpdateTS)"
535 ." VALUES (" . $userID . ", '" . $new_sid . "', UNIX_TIMESTAMP())";
536 $result = $dbh->exec($q);
538 /* Query will fail if $new_sid is not unique. */
539 if ($result) {
540 $logged_in = 1;
541 break;
544 $num_tries++;
547 if (!$logged_in) {
548 $login_error = __('An error occurred trying to generate a user session.');
549 return array('SID' => $new_sid, 'error' => $login_error);
552 $q = "UPDATE Users SET LastLogin = UNIX_TIMESTAMP(), ";
553 $q.= "LastLoginIPAddress = " . $dbh->quote(ip2long($_SERVER['REMOTE_ADDR'])) . " ";
554 $q.= "WHERE ID = '$userID'";
555 $dbh->exec($q);
557 /* Set the SID cookie. */
558 if (isset($_POST['remember_me']) && $_POST['remember_me'] == "on") {
559 /* Set cookies for 30 days. */
560 $timeout = config_get_int('options', 'persistent_cookie_timeout');
561 $cookie_time = time() + $timeout;
563 /* Set session for 30 days. */
564 $q = "UPDATE Sessions SET LastUpdateTS = $cookie_time ";
565 $q.= "WHERE SessionID = '$new_sid'";
566 $dbh->exec($q);
567 } else {
568 $cookie_time = 0;
571 setcookie("AURSID", $new_sid, $cookie_time, "/", null, !empty($_SERVER['HTTPS']), true);
573 $referer = in_request('referer');
574 if (strpos($referer, aur_location()) !== 0) {
575 $referer = '/';
577 header("Location: " . get_uri($referer));
578 $login_error = "";
582 * Determine if the user is using a banned IP address
584 * @return bool True if IP address is banned, otherwise false
586 function is_ipbanned() {
587 $dbh = DB::connect();
589 $q = "SELECT * FROM Bans WHERE IPAddress = " . $dbh->quote(ip2long($_SERVER['REMOTE_ADDR']));
590 $result = $dbh->query($q);
592 return ($result->fetchColumn() ? true : false);
596 * Validate a username against a collection of rules
598 * The username must be longer or equal to the configured minimum length. It
599 * must be shorter or equal to the configured maximum length. It must start and
600 * end with either a letter or a number. It can contain one period, hypen, or
601 * underscore. Returns boolean of whether name is valid.
603 * @param string $user Username to validate
605 * @return bool True if username meets criteria, otherwise false
607 function valid_username($user) {
608 $length_min = config_get_int('options', 'username_min_len');
609 $length_max = config_get_int('options', 'username_max_len');
611 if (strlen($user) < $length_min || strlen($user) > $length_max) {
612 return false;
613 } else if (!preg_match("/^[a-z0-9]+[.\-_]?[a-z0-9]+$/Di", $user)) {
614 return false;
617 return true;
621 * Determine if a username exists in the database
623 * @param string $user Username to check in the database
625 * @return string|void Return user ID if in database, otherwise void
627 function valid_user($user) {
628 if (!$user) {
629 return false;
632 $dbh = DB::connect();
634 $q = "SELECT ID FROM Users WHERE ";
635 $q.= "Username = " . $dbh->quote($user);
636 $result = $dbh->query($q);
637 if (!$result) {
638 return null;
641 $row = $result->fetch(PDO::FETCH_NUM);
642 return $row[0];
646 * Determine if a user already has a proposal open about themselves
648 * @param string $user Username to checkout for open proposal
650 * @return bool True if there is an open proposal about the user, otherwise false
652 function open_user_proposals($user) {
653 $dbh = DB::connect();
654 $q = "SELECT * FROM TU_VoteInfo WHERE User = " . $dbh->quote($user) . " ";
655 $q.= "AND End > UNIX_TIMESTAMP()";
656 $result = $dbh->query($q);
658 return ($result->fetchColumn() ? true : false);
662 * Add a new Trusted User proposal to the database
664 * @param string $agenda The agenda of the vote
665 * @param string $user The use the vote is about
666 * @param int $votelength The length of time for the vote to last
667 * @param string $submitteruid The user ID of the individual who submitted the proposal
669 * @return void
671 function add_tu_proposal($agenda, $user, $votelength, $quorum, $submitteruid) {
672 $dbh = DB::connect();
674 $q = "SELECT COUNT(*) FROM Users WHERE (AccountTypeID = 2 OR AccountTypeID = 4)";
675 $result = $dbh->query($q);
676 $row = $result->fetch(PDO::FETCH_NUM);
677 $active_tus = $row[0];
679 $q = "INSERT INTO TU_VoteInfo (Agenda, User, Submitted, End, Quorum, ";
680 $q.= "SubmitterID, ActiveTUs) VALUES ";
681 $q.= "(" . $dbh->quote($agenda) . ", " . $dbh->quote($user) . ", ";
682 $q.= "UNIX_TIMESTAMP(), UNIX_TIMESTAMP() + " . $dbh->quote($votelength);
683 $q.= ", " . $dbh->quote($quorum) . ", " . $submitteruid . ", ";
684 $q.= $active_tus . ")";
685 $result = $dbh->exec($q);
689 * Add a reset key to the database for a specified user
691 * @param string $resetkey A password reset key to be stored in database
692 * @param string $uid The user ID to store the reset key for
694 * @return void
696 function create_resetkey($resetkey, $uid) {
697 $dbh = DB::connect();
698 $q = "UPDATE Users ";
699 $q.= "SET ResetKey = '" . $resetkey . "' ";
700 $q.= "WHERE ID = " . $uid;
701 $dbh->exec($q);
705 * Send a reset key to a specific e-mail address
707 * @param string $email E-mail address of the user resetting their password
708 * @param string $subject Subject of the email
709 * @param string $body Body of the email
711 * @return void
713 function send_resetkey($email, $subject, $body) {
714 $uid = uid_from_email($email);
715 if ($uid == null) {
716 return;
719 /* We (ab)use new_sid() to get a random 32 characters long string. */
720 $resetkey = new_sid();
721 create_resetkey($resetkey, $uid);
723 /* Send e-mail with confirmation link. */
724 $body = wordwrap($body, 70);
725 $body .= "\n\n". get_uri('/passreset/', true) .
726 "?resetkey={$resetkey}";
727 $headers = "MIME-Version: 1.0\r\n" .
728 "Content-type: text/plain; charset=UTF-8\r\n" .
729 "Reply-to: noreply@aur.archlinux.org\r\n" .
730 "From: notify@aur.archlinux.org\r\n" .
731 "X-Mailer: PHP\r\n" .
732 "X-MimeOLE: Produced By AUR";
733 @mail($email, $subject, $body, $headers);
737 * Change a user's password in the database if reset key and e-mail are correct
739 * @param string $hash New MD5 hash of a user's password
740 * @param string $salt New salt for the user's password
741 * @param string $resetkey Code e-mailed to a user to reset a password
742 * @param string $email E-mail address of the user resetting their password
744 * @return string|void Redirect page if successful, otherwise return error message
746 function password_reset($hash, $salt, $resetkey, $email) {
747 $dbh = DB::connect();
748 $q = "UPDATE Users ";
749 $q.= "SET Passwd = '$hash', ";
750 $q.= "Salt = '$salt', ";
751 $q.= "ResetKey = '' ";
752 $q.= "WHERE ResetKey != '' ";
753 $q.= "AND ResetKey = " . $dbh->quote($resetkey) . " ";
754 $q.= "AND Email = " . $dbh->quote($email);
755 $result = $dbh->exec($q);
757 if (!$result) {
758 $error = __('Invalid e-mail and reset key combination.');
759 return $error;
760 } else {
761 header('Location: ' . get_uri('/passreset/') . '?step=complete');
762 exit();
767 * Determine if the password is longer than the minimum length
769 * @param string $passwd The password to check
771 * @return bool True if longer than minimum length, otherwise false
773 function good_passwd($passwd) {
774 $length_min = config_get_int('options', 'passwd_min_len');
775 return (strlen($passwd) >= $length_min);
779 * Determine if the password is correct and salt it if it hasn't been already
781 * @param string $userID The user ID to check the password against
782 * @param string $passwd The password the visitor sent
784 * @return bool True if password was correct and properly salted, otherwise false
786 function valid_passwd($userID, $passwd) {
787 $dbh = DB::connect();
788 if ($passwd == "") {
789 return false;
792 /* Get salt for this user. */
793 $salt = get_salt($userID);
794 if ($salt) {
795 $q = "SELECT ID FROM Users ";
796 $q.= "WHERE ID = " . $userID . " ";
797 $q.= "AND Passwd = " . $dbh->quote(salted_hash($passwd, $salt));
798 $result = $dbh->query($q);
799 if (!$result) {
800 return false;
803 $row = $result->fetch(PDO::FETCH_NUM);
804 return ($row[0] > 0);
805 } else {
806 /* Check password without using salt. */
807 $q = "SELECT ID FROM Users ";
808 $q.= "WHERE ID = " . $userID . " ";
809 $q.= "AND Passwd = " . $dbh->quote(md5($passwd));
810 $result = $dbh->query($q);
811 if (!$result) {
812 return false;
815 $row = $result->fetch(PDO::FETCH_NUM);
816 if (!$row[0]) {
817 return false;
820 /* Password correct, but salt it first! */
821 if (!save_salt($userID, $passwd)) {
822 trigger_error("Unable to salt user's password;" .
823 " ID " . $userID, E_USER_WARNING);
824 return false;
827 return true;
832 * Determine if a user's password is empty
834 * @param string $uid The user ID to check for an empty password
836 * @return bool True if the user's password is empty, otherwise false
838 function passwd_is_empty($uid) {
839 $dbh = DB::connect();
841 $q = "SELECT * FROM Users WHERE ID = " . $dbh->quote($uid) . " ";
842 $q .= "AND Passwd = " . $dbh->quote('');
843 $result = $dbh->query($q);
845 if ($result->fetchColumn()) {
846 return true;
847 } else {
848 return false;
853 * Determine if the PGP key fingerprint is valid (must be 40 hexadecimal digits)
855 * @param string $fingerprint PGP fingerprint to check if valid
857 * @return bool True if the fingerprint is 40 hexadecimal digits, otherwise false
859 function valid_pgp_fingerprint($fingerprint) {
860 $fingerprint = str_replace(" ", "", $fingerprint);
861 return (strlen($fingerprint) == 40 && ctype_xdigit($fingerprint));
865 * Determine if the SSH public key is valid
867 * @param string $pubkey SSH public key to check
869 * @return bool True if the SSH public key is valid, otherwise false
871 function valid_ssh_pubkey($pubkey) {
872 $valid_prefixes = array(
873 "ssh-rsa", "ssh-dss", "ecdsa-sha2-nistp256",
874 "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521", "ssh-ed25519"
877 $has_valid_prefix = false;
878 foreach ($valid_prefixes as $prefix) {
879 if (strpos($pubkey, $prefix . " ") === 0) {
880 $has_valid_prefix = true;
881 break;
884 if (!$has_valid_prefix) {
885 return false;
888 $tokens = explode(" ", $pubkey);
889 if (empty($tokens[1])) {
890 return false;
893 return (base64_encode(base64_decode($tokens[1], true)) == $tokens[1]);
897 * Determine if the user account has been suspended
899 * @param string $id The ID of user to check if suspended
901 * @return bool True if the user is suspended, otherwise false
903 function user_suspended($id) {
904 $dbh = DB::connect();
905 if (!$id) {
906 return false;
908 $q = "SELECT Suspended FROM Users WHERE ID = " . $id;
909 $result = $dbh->query($q);
910 if ($result) {
911 $row = $result->fetch(PDO::FETCH_NUM);
912 if ($row[0]) {
913 return true;
916 return false;
920 * Delete a specified user account from the database
922 * @param int $id The user ID of the account to be deleted
924 * @return void
926 function user_delete($id) {
927 $dbh = DB::connect();
928 $id = intval($id);
931 * These are normally already taken care of by propagation constraints
932 * but it is better to be explicit here.
934 $fields_delete = array(
935 array("Sessions", "UsersID"),
936 array("PackageVotes", "UsersID"),
937 array("CommentNotify", "UsersID")
940 $fields_set_null = array(
941 array("PackageBases", "SubmitterUID"),
942 array("PackageBases", "MaintainerUID"),
943 array("PackageBases", "SubmitterUID"),
944 array("PackageComments", "UsersID"),
945 array("PackageComments", "DelUsersID"),
946 array("PackageRequests", "UsersID"),
947 array("TU_VoteInfo", "SubmitterID"),
948 array("TU_Votes", "UserID")
951 foreach($fields_delete as list($table, $field)) {
952 $q = "DELETE FROM " . $table . " ";
953 $q.= "WHERE " . $field . " = " . $id;
954 $dbh->query($q);
957 foreach($fields_set_null as list($table, $field)) {
958 $q = "UPDATE " . $table . " SET " . $field . " = NULL ";
959 $q.= "WHERE " . $field . " = " . $id;
960 $dbh->query($q);
963 $q = "DELETE FROM Users WHERE ID = " . $id;
964 $dbh->query($q);
965 return;
969 * Remove the session from the database on logout
971 * @param string $sid User's session ID
973 * @return void
975 function delete_session_id($sid) {
976 $dbh = DB::connect();
978 $q = "DELETE FROM Sessions WHERE SessionID = " . $dbh->quote($sid);
979 $dbh->query($q);
983 * Remove all sessions belonging to a particular user
985 * @param int $uid ID of user to remove all sessions for
987 * @return void
989 function delete_user_sessions($uid) {
990 $dbh = DB::connect();
992 $q = "DELETE FROM Sessions WHERE UsersID = " . intval($uid);
993 $dbh->exec($q);
997 * Remove sessions from the database that have exceed the timeout
999 * @return void
1001 function clear_expired_sessions() {
1002 $dbh = DB::connect();
1004 $timeout = config_get_int('options', 'login_timeout');
1005 $q = "DELETE FROM Sessions WHERE LastUpdateTS < (UNIX_TIMESTAMP() - " . $timeout . ")";
1006 $dbh->query($q);
1008 return;
1012 * Get account details for a specific user
1014 * @param string $uid The User ID of account to get information for
1015 * @param string $username The username of the account to get for
1017 * @return array Account details for the specified user
1019 function account_details($uid, $username) {
1020 $dbh = DB::connect();
1021 $q = "SELECT Users.*, AccountTypes.AccountType ";
1022 $q.= "FROM Users, AccountTypes ";
1023 $q.= "WHERE AccountTypes.ID = Users.AccountTypeID ";
1024 if (!empty($uid)) {
1025 $q.= "AND Users.ID = ".intval($uid);
1026 } else {
1027 $q.= "AND Users.Username = " . $dbh->quote($username);
1029 $result = $dbh->query($q);
1031 if ($result) {
1032 $row = $result->fetch(PDO::FETCH_ASSOC);
1035 return $row;
1039 * Determine if a user has already voted on a specific proposal
1041 * @param string $voteid The ID of the Trusted User proposal
1042 * @param string $uid The ID to check if the user already voted
1044 * @return bool True if the user has already voted, otherwise false
1046 function tu_voted($voteid, $uid) {
1047 $dbh = DB::connect();
1049 $q = "SELECT COUNT(*) FROM TU_Votes ";
1050 $q.= "WHERE VoteID = " . intval($voteid) . " AND UserID = " . intval($uid);
1051 $result = $dbh->query($q);
1052 if ($result->fetchColumn() > 0) {
1053 return true;
1055 else {
1056 return false;
1061 * Get all current Trusted User proposals from the database
1063 * @param string $order Ascending or descending order for the proposal listing
1065 * @return array The details for all current Trusted User proposals
1067 function current_proposal_list($order) {
1068 $dbh = DB::connect();
1070 $q = "SELECT * FROM TU_VoteInfo WHERE End > " . time() . " ORDER BY Submitted " . $order;
1071 $result = $dbh->query($q);
1073 $details = array();
1074 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
1075 $details[] = $row;
1078 return $details;
1082 * Get a subset of all past Trusted User proposals from the database
1084 * @param string $order Ascending or descending order for the proposal listing
1085 * @param string $lim The number of proposals to list with the offset
1087 * @return array The details for the subset of past Trusted User proposals
1089 function past_proposal_list($order, $lim) {
1090 $dbh = DB::connect();
1092 $q = "SELECT * FROM TU_VoteInfo WHERE End < " . time() . " ORDER BY Submitted " . $order . $lim;
1093 $result = $dbh->query($q);
1095 $details = array();
1096 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
1097 $details[] = $row;
1100 return $details;
1104 * Get the vote ID of the last vote of all Trusted Users
1106 * @return array The vote ID of the last vote of each Trusted User
1108 function last_votes_list() {
1109 $dbh = DB::connect();
1111 $q = "SELECT UserID, MAX(VoteID) AS LastVote FROM TU_Votes, ";
1112 $q .= "TU_VoteInfo, Users WHERE TU_VoteInfo.ID = TU_Votes.VoteID AND ";
1113 $q .= "TU_VoteInfo.End < UNIX_TIMESTAMP() AND ";
1114 $q .= "Users.ID = TU_Votes.UserID AND (Users.AccountTypeID = 2 OR Users.AccountTypeID = 4) ";
1115 $q .= "GROUP BY UserID ORDER BY LastVote DESC, UserName ASC";
1116 $result = $dbh->query($q);
1118 $details = array();
1119 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
1120 $details[] = $row;
1123 return $details;
1127 * Determine the total number of Trusted User proposals
1129 * @return string The total number of Trusted User proposals
1131 function proposal_count() {
1132 $dbh = DB::connect();
1133 $q = "SELECT COUNT(*) FROM TU_VoteInfo";
1134 $result = $dbh->query($q);
1135 $row = $result->fetch(PDO::FETCH_NUM);
1137 return $row[0];
1141 * Get all details related to a specific vote from the database
1143 * @param string $voteid The ID of the Trusted User proposal
1145 * @return array All stored details for a specific vote
1147 function vote_details($voteid) {
1148 $dbh = DB::connect();
1150 $q = "SELECT * FROM TU_VoteInfo ";
1151 $q.= "WHERE ID = " . intval($voteid);
1153 $result = $dbh->query($q);
1154 $row = $result->fetch(PDO::FETCH_ASSOC);
1156 return $row;
1160 * Get an alphabetical list of users who voted for a proposal with HTML links
1162 * @param string $voteid The ID of the Trusted User proposal
1164 * @return array All users who voted for a specific proposal
1166 function voter_list($voteid) {
1167 $dbh = DB::connect();
1169 $whovoted = array();
1171 $q = "SELECT tv.UserID,U.Username ";
1172 $q.= "FROM TU_Votes tv, Users U ";
1173 $q.= "WHERE tv.VoteID = " . intval($voteid);
1174 $q.= " AND tv.UserID = U.ID ";
1175 $q.= "ORDER BY Username";
1177 $result = $dbh->query($q);
1178 if ($result) {
1179 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
1180 $whovoted[] = $row['Username'];
1183 return $whovoted;
1187 * Cast a vote for a specific user proposal
1189 * @param string $voteid The ID of the proposal being voted on
1190 * @param string $uid The user ID of the individual voting
1191 * @param string $vote Vote position, either "Yes", "No", or "Abstain"
1192 * @param int $newtotal The total number of votes after the user has voted
1194 * @return void
1196 function cast_proposal_vote($voteid, $uid, $vote, $newtotal) {
1197 $dbh = DB::connect();
1199 $q = "UPDATE TU_VoteInfo SET " . $vote . " = (" . $newtotal . ") WHERE ID = " . $voteid;
1200 $result = $dbh->exec($q);
1202 $q = "INSERT INTO TU_Votes (VoteID, UserID) VALUES (" . intval($voteid) . ", " . intval($uid) . ")";
1203 $result = $dbh->exec($q);
1207 * Verify a user has the proper permissions to edit an account
1209 * @param array $acctinfo User account information for edited account
1211 * @return bool True if permission to edit the account, otherwise false
1213 function can_edit_account($acctinfo) {
1214 if ($acctinfo['AccountType'] == 'Developer' ||
1215 $acctinfo['AccountType'] == 'Trusted User & Developer') {
1216 return has_credential(CRED_ACCOUNT_EDIT_DEV);
1219 $uid = $acctinfo['ID'];
1220 return has_credential(CRED_ACCOUNT_EDIT, array($uid));
1224 * Compute the fingerprint of an SSH key.
1226 * @param string $ssh_key The SSH public key to retrieve the fingerprint for
1228 * @return string The SSH key fingerprint
1230 function ssh_key_fingerprint($ssh_key) {
1231 $tmpfile = tempnam(sys_get_temp_dir(), "aurweb");
1232 file_put_contents($tmpfile, $ssh_key);
1235 * The -l option of ssh-keygen can be used to show the fingerprint of
1236 * the specified public key file. Expected output format:
1238 * 2048 SHA256:uBBTXmCNjI2CnLfkuz9sG8F+e9/T4C+qQQwLZWIODBY user@host (RSA)
1240 * ... where 2048 is the key length, the second token is the actual
1241 * fingerprint, followed by the key comment and the key type.
1244 $cmd = "/usr/bin/ssh-keygen -l -f " . escapeshellarg($tmpfile);
1245 exec($cmd, $out, $ret);
1246 if ($ret !== 0 || count($out) !== 1) {
1247 return false;
1250 unlink($tmpfile);
1252 $tokens = explode(' ', $out[0]);
1253 if (count($tokens) != 4) {
1254 return false;
1257 $tokens = explode(':', $tokens[1]);
1258 if (count($tokens) != 2 || $tokens[0] != 'SHA256') {
1259 return false;
1262 return $tokens[1];
1266 * Get the SSH public keys associated with an account.
1268 * @param int $uid The user ID of the account to retrieve the keys for.
1270 * @return array An array representing the keys
1272 function account_get_ssh_keys($uid) {
1273 $dbh = DB::connect();
1274 $q = "SELECT PubKey FROM SSHPubKeys WHERE UserID = " . intval($uid);
1275 $result = $dbh->query($q);
1277 if ($result) {
1278 return $result->fetchAll(PDO::FETCH_COLUMN, 0);
1279 } else {
1280 return array();
1285 * Set the SSH public keys associated with an account.
1287 * @param int $uid The user ID of the account to assign the keys to.
1288 * @param array $ssh_keys The SSH public keys.
1289 * @param array $ssh_fingerprints The corresponding SSH key fingerprints.
1291 * @return bool Boolean flag indicating success or failure.
1293 function account_set_ssh_keys($uid, $ssh_keys, $ssh_fingerprints) {
1294 $dbh = DB::connect();
1296 $q = sprintf("DELETE FROM SSHPubKeys WHERE UserID = %d", $uid);
1297 $dbh->exec($q);
1299 $ssh_fingerprint = reset($ssh_fingerprints);
1300 foreach ($ssh_keys as $ssh_key) {
1301 $q = sprintf(
1302 "INSERT INTO SSHPubKeys (UserID, Fingerprint, PubKey) " .
1303 "VALUES (%d, %s, %s)", $uid,
1304 $dbh->quote($ssh_fingerprint), $dbh->quote($ssh_key)
1306 $dbh->exec($q);
1307 $ssh_fingerprint = next($ssh_fingerprints);
1310 return true;