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
10 function in_request($name) {
11 if (isset($_REQUEST[$name])) {
12 return $_REQUEST[$name];
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)) {
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
);
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 SSH public key of the displayed user
57 * @param string $J The inactivity status of the displayed user
58 * @param string $UID The user ID of the displayed user
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");
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 SSH public key of the user
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;
99 $error = __('Account registration has been disabled ' .
100 'for your IP address, probably due ' .
101 'to sustained spam attacks. Sorry for the ' .
105 $dbh = DB
::connect();
107 if(isset($_COOKIE['AURSID'])) {
108 $editor_user = uid_from_sid($_COOKIE['AURSID']);
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)
129 . "<li>" . __("Start and end with a letter or number") . "</li>"
130 . "<li>" . __("Can contain only one period, underscore or hyphen.")
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.",
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 if (valid_ssh_pubkey($PK)) {
153 $tokens = explode(" ", $PK);
154 $PK = $tokens[0] . " " . $tokens[1];
156 $error = __("The SSH public key is invalid.");
160 if (isset($_COOKIE['AURSID'])) {
161 $atype = account_from_sid($_COOKIE['AURSID']);
162 if (($atype == "User" && $T > 1) ||
($atype == "Trusted User" && $T > 2)) {
163 $error = __("Cannot increase account permissions.");
167 if (!$error && !array_key_exists($L, $SUPPORTED_LANGS)) {
168 $error = __("Language is not currently supported.");
172 * Check whether the user name is available.
173 * TODO: Fix race condition.
175 $q = "SELECT COUNT(*) AS CNT FROM Users ";
176 $q.= "WHERE Username = " . $dbh->quote($U);
177 if ($TYPE == "edit") {
178 $q.= " AND ID != ".intval($UID);
180 $result = $dbh->query($q);
181 $row = $result->fetch(PDO
::FETCH_NUM
);
184 $error = __("The username, %s%s%s, is already in use.",
185 "<strong>", htmlspecialchars($U,ENT_QUOTES
), "</strong>");
190 * Check whether the e-mail address is available.
191 * TODO: Fix race condition.
193 $q = "SELECT COUNT(*) AS CNT FROM Users ";
194 $q.= "WHERE Email = " . $dbh->quote($E);
195 if ($TYPE == "edit") {
196 $q.= " AND ID != ".intval($UID);
198 $result = $dbh->query($q);
199 $row = $result->fetch(PDO
::FETCH_NUM
);
202 $error = __("The address, %s%s%s, is already in use.",
203 "<strong>", htmlspecialchars($E,ENT_QUOTES
), "</strong>");
206 if (!$error && !empty($PK)) {
208 * Check whether the SSH public key is available.
209 * TODO: Fix race condition.
211 $q = "SELECT COUNT(*) FROM Users ";
212 $q.= "WHERE SSHPubKey = " . $dbh->quote($PK);
213 if ($TYPE == "edit") {
214 $q.= " AND ID != " . intval($UID);
216 $result = $dbh->query($q);
217 $row = $result->fetch(PDO
::FETCH_NUM
);
220 $error = __("The SSH public key, %s%s%s, is already in use.",
221 "<strong>", htmlspecialchars($PK, ENT_QUOTES
), "</strong>");
226 print "<ul class='errorlist'><li>".$error."</li></ul>\n";
227 display_account_form($A, $U, $T, $S, $E, "", "",
228 $R, $L, $I, $K, $PK, $J, $UID);
232 if ($TYPE == "new") {
233 /* Create an unprivileged user. */
234 $salt = generate_salt();
236 $send_resetkey = true;
239 $send_resetkey = false;
240 $P = salted_hash($P, $salt);
242 $U = $dbh->quote($U);
243 $E = $dbh->quote($E);
244 $P = $dbh->quote($P);
245 $salt = $dbh->quote($salt);
246 $R = $dbh->quote($R);
247 $L = $dbh->quote($L);
248 $I = $dbh->quote($I);
249 $K = $dbh->quote(str_replace(" ", "", $K));
250 $PK = empty($PK) ?
"NULL" : $dbh->quote($PK);
251 $q = "INSERT INTO Users (AccountTypeID, Suspended, ";
252 $q.= "InactivityTS, Username, Email, Passwd, Salt, ";
253 $q.= "RealName, LangPreference, IRCNick, PGPKey, ";
255 $q.= "VALUES (1, 0, 0, $U, $E, $P, $salt, $R, $L, ";
257 $result = $dbh->exec($q);
259 print __("Error trying to create account, %s%s%s.",
260 "<strong>", htmlspecialchars($U,ENT_QUOTES
), "</strong>");
264 print __("The account, %s%s%s, has been successfully created.",
265 "<strong>", htmlspecialchars($U,ENT_QUOTES
), "</strong>");
268 if (!$send_resetkey) {
269 print __("Click on the Login link above to use your account.");
274 $subject = 'Welcome to the Arch User Repository';
275 $body = __('Welcome to %s! In order ' .
276 'to set an initial password ' .
277 'for your new account, ' .
278 'please click the link ' .
279 'below. If the link does ' .
280 'not work try copying and ' .
281 'pasting it into your ' .
284 send_resetkey($email, $subject, $body);
286 print __("A password reset key has been sent to your e-mail address.");
289 /* Modify an existing account. */
290 $q = "SELECT InactivityTS FROM Users WHERE ";
291 $q.= "ID = " . intval($UID);
292 $result = $dbh->query($q);
293 $row = $result->fetch(PDO
::FETCH_NUM
);
295 $inactivity_ts = $row[0];
297 $inactivity_ts = time();
302 $q = "UPDATE Users SET ";
303 $q.= "Username = " . $dbh->quote($U);
305 $q.= ", AccountTypeID = ".intval($T);
308 /* Ensure suspended users can't keep an active session */
309 delete_user_sessions($UID);
310 $q.= ", Suspended = 1";
312 $q.= ", Suspended = 0";
314 $q.= ", Email = " . $dbh->quote($E);
316 $salt = generate_salt();
317 $hash = salted_hash($P, $salt);
318 $q .= ", Passwd = '$hash', Salt = '$salt'";
320 $q.= ", RealName = " . $dbh->quote($R);
321 $q.= ", LangPreference = " . $dbh->quote($L);
322 $q.= ", IRCNick = " . $dbh->quote($I);
323 $q.= ", PGPKey = " . $dbh->quote(str_replace(" ", "", $K));
324 $q.= ", SSHPubKey = " . $dbh->quote($PK);
325 $q.= ", InactivityTS = " . $inactivity_ts;
326 $q.= " WHERE ID = ".intval($UID);
327 $result = $dbh->exec($q);
329 print __("No changes were made to the account, %s%s%s.",
330 "<strong>", htmlspecialchars($U,ENT_QUOTES
), "</strong>");
332 print __("The account, %s%s%s, has been successfully modified.",
333 "<strong>", htmlspecialchars($U,ENT_QUOTES
), "</strong>");
339 * Display the search results page
341 * @param string $O The offset for the results page
342 * @param string $SB The column to sort the results page by
343 * @param string $U The username search criteria
344 * @param string $T The account type search criteria
345 * @param string $S Whether the account is suspended search criteria
346 * @param string $E The e-mail address search criteria
347 * @param string $R The real name search criteria
348 * @param string $I The IRC nickname search criteria
349 * @param string $K The PGP key fingerprint search criteria
353 function search_results_page($O=0,$SB="",$U="",$T="",
354 $S="",$E="",$R="",$I="",$K="") {
358 $OFFSET = intval($O);
365 $search_vars = array();
367 $dbh = DB
::connect();
369 $q = "SELECT Users.*, AccountTypes.AccountType ";
370 $q.= "FROM Users, AccountTypes ";
371 $q.= "WHERE AccountTypes.ID = Users.AccountTypeID ";
373 $q.= "AND AccountTypes.ID = 1 ";
374 $search_vars[] = "T";
375 } elseif ($T == "t") {
376 $q.= "AND AccountTypes.ID = 2 ";
377 $search_vars[] = "T";
378 } elseif ($T == "d") {
379 $q.= "AND AccountTypes.ID = 3 ";
380 $search_vars[] = "T";
381 } elseif ($T == "td") {
382 $q.= "AND AccountTypes.ID = 4 ";
383 $search_vars[] = "T";
386 $q.= "AND Users.Suspended = 1 ";
387 $search_vars[] = "S";
390 $U = "%" . addcslashes($U, '%_') . "%";
391 $q.= "AND Username LIKE " . $dbh->quote($U) . " ";
392 $search_vars[] = "U";
395 $E = "%" . addcslashes($E, '%_') . "%";
396 $q.= "AND Email LIKE " . $dbh->quote($E) . " ";
397 $search_vars[] = "E";
400 $R = "%" . addcslashes($R, '%_') . "%";
401 $q.= "AND RealName LIKE " . $dbh->quote($R) . " ";
402 $search_vars[] = "R";
405 $I = "%" . addcslashes($I, '%_') . "%";
406 $q.= "AND IRCNick LIKE " . $dbh->quote($I) . " ";
407 $search_vars[] = "I";
410 $K = "%" . addcslashes(str_replace(" ", "", $K), '%_') . "%";
411 $q.= "AND PGPKey LIKE " . $dbh->quote($K) . " ";
412 $search_vars[] = "K";
416 $q.= "ORDER BY AccountTypeID, Username ";
419 $q.= "ORDER BY RealName, AccountTypeID ";
422 $q.= "ORDER BY IRCNick, AccountTypeID ";
425 $q.= "ORDER BY Username, AccountTypeID ";
428 $search_vars[] = "SB";
429 $q.= "LIMIT " . $HITS_PER_PAGE . " OFFSET " . $OFFSET;
431 $dbh = DB
::connect();
433 $result = $dbh->query($q);
435 while ($row = $result->fetch(PDO
::FETCH_ASSOC
)) {
439 include("account_search_results.php");
444 * Attempt to login and generate a session
446 * @return array Session ID for user, error message if applicable
448 function try_login() {
453 if (!isset($_REQUEST['user']) && !isset($_REQUEST['passwd'])) {
454 return array('SID' => '', 'error' => null);
458 $login_error = __('The login form is currently disabled ' .
459 'for your IP address, probably due ' .
460 'to sustained spam attacks. Sorry for the ' .
462 return array('SID' => '', 'error' => $login_error);
465 $dbh = DB
::connect();
466 $userID = valid_user($_REQUEST['user']);
468 if (user_suspended($userID)) {
469 $login_error = __('Account suspended');
470 return array('SID' => '', 'error' => $login_error);
471 } elseif (passwd_is_empty($userID)) {
472 $login_error = __('Your password has been reset. ' .
473 'If you just created a new account, please ' .
474 'use the link from the confirmation email ' .
475 'to set an initial password. Otherwise, ' .
476 'please request a reset key on the %s' .
477 'Password Reset%s page.', '<a href="' .
478 htmlspecialchars(get_uri('/passreset')) . '">',
480 return array('SID' => '', 'error' => $login_error);
481 } elseif (!valid_passwd($userID, $_REQUEST['passwd'])) {
482 $login_error = __("Bad username or password.");
483 return array('SID' => '', 'error' => $login_error);
489 /* Generate a session ID and store it. */
490 while (!$logged_in && $num_tries < 5) {
491 $session_limit = config_get_int('options', 'max_sessions_per_user');
492 if ($session_limit) {
494 * Delete all user sessions except the
495 * last ($session_limit - 1).
497 $q = "DELETE s.* FROM Sessions s ";
498 $q.= "LEFT JOIN (SELECT SessionID FROM Sessions ";
499 $q.= "WHERE UsersId = " . $userID . " ";
500 $q.= "ORDER BY LastUpdateTS DESC ";
501 $q.= "LIMIT " . ($session_limit - 1) . ") q ";
502 $q.= "ON s.SessionID = q.SessionID ";
503 $q.= "WHERE s.UsersId = " . $userID . " ";
504 $q.= "AND q.SessionID IS NULL;";
508 $new_sid = new_sid();
509 $q = "INSERT INTO Sessions (UsersID, SessionID, LastUpdateTS)"
510 ." VALUES (" . $userID . ", '" . $new_sid . "', UNIX_TIMESTAMP())";
511 $result = $dbh->exec($q);
513 /* Query will fail if $new_sid is not unique. */
523 $login_error = __('An error occurred trying to generate a user session.');
524 return array('SID' => $new_sid, 'error' => $login_error);
527 $q = "UPDATE Users SET LastLogin = UNIX_TIMESTAMP(), ";
528 $q.= "LastLoginIPAddress = " . $dbh->quote(ip2long($_SERVER['REMOTE_ADDR'])) . " ";
529 $q.= "WHERE ID = '$userID'";
532 /* Set the SID cookie. */
533 if (isset($_POST['remember_me']) && $_POST['remember_me'] == "on") {
534 /* Set cookies for 30 days. */
535 $timeout = config_get_int('options', 'persistent_cookie_timeout');
536 $cookie_time = time() +
$timeout;
538 /* Set session for 30 days. */
539 $q = "UPDATE Sessions SET LastUpdateTS = $cookie_time ";
540 $q.= "WHERE SessionID = '$new_sid'";
546 setcookie("AURSID", $new_sid, $cookie_time, "/", null, !empty($_SERVER['HTTPS']), true);
547 header("Location: " . get_uri('/'));
552 * Determine if the user is using a banned IP address
554 * @return bool True if IP address is banned, otherwise false
556 function is_ipbanned() {
557 $dbh = DB
::connect();
559 $q = "SELECT * FROM Bans WHERE IPAddress = " . $dbh->quote(ip2long($_SERVER['REMOTE_ADDR']));
560 $result = $dbh->query($q);
562 return ($result->fetchColumn() ?
true : false);
566 * Validate a username against a collection of rules
568 * The username must be longer or equal to the configured minimum length. It
569 * must be shorter or equal to the configured maximum length. It must start and
570 * end with either a letter or a number. It can contain one period, hypen, or
571 * underscore. Returns boolean of whether name is valid.
573 * @param string $user Username to validate
575 * @return bool True if username meets criteria, otherwise false
577 function valid_username($user) {
578 $length_min = config_get_int('options', 'username_min_len');
579 $length_max = config_get_int('options', 'username_max_len');
581 if (strlen($user) < $length_min ||
strlen($user) > $length_max) {
583 } else if (!preg_match("/^[a-z0-9]+[.\-_]?[a-z0-9]+$/Di", $user)) {
591 * Determine if a username exists in the database
593 * @param string $user Username to check in the database
595 * @return string|void Return user ID if in database, otherwise void
597 function valid_user($user) {
602 $dbh = DB
::connect();
604 $q = "SELECT ID FROM Users WHERE ";
605 $q.= "Username = " . $dbh->quote($user);
606 $result = $dbh->query($q);
611 $row = $result->fetch(PDO
::FETCH_NUM
);
616 * Determine if a user already has a proposal open about themselves
618 * @param string $user Username to checkout for open proposal
620 * @return bool True if there is an open proposal about the user, otherwise false
622 function open_user_proposals($user) {
623 $dbh = DB
::connect();
624 $q = "SELECT * FROM TU_VoteInfo WHERE User = " . $dbh->quote($user) . " ";
625 $q.= "AND End > UNIX_TIMESTAMP()";
626 $result = $dbh->query($q);
628 return ($result->fetchColumn() ?
true : false);
632 * Add a new Trusted User proposal to the database
634 * @param string $agenda The agenda of the vote
635 * @param string $user The use the vote is about
636 * @param int $votelength The length of time for the vote to last
637 * @param string $submitteruid The user ID of the individual who submitted the proposal
641 function add_tu_proposal($agenda, $user, $votelength, $quorum, $submitteruid) {
642 $dbh = DB
::connect();
644 $q = "SELECT COUNT(*) FROM Users WHERE (AccountTypeID = 2 OR AccountTypeID = 4)";
645 $result = $dbh->query($q);
646 $row = $result->fetch(PDO
::FETCH_NUM
);
647 $active_tus = $row[0];
649 $q = "INSERT INTO TU_VoteInfo (Agenda, User, Submitted, End, Quorum, ";
650 $q.= "SubmitterID, ActiveTUs) VALUES ";
651 $q.= "(" . $dbh->quote($agenda) . ", " . $dbh->quote($user) . ", ";
652 $q.= "UNIX_TIMESTAMP(), UNIX_TIMESTAMP() + " . $dbh->quote($votelength);
653 $q.= ", " . $dbh->quote($quorum) . ", " . $submitteruid . ", ";
654 $q.= $active_tus . ")";
655 $result = $dbh->exec($q);
659 * Add a reset key to the database for a specified user
661 * @param string $resetkey A password reset key to be stored in database
662 * @param string $uid The user ID to store the reset key for
666 function create_resetkey($resetkey, $uid) {
667 $dbh = DB
::connect();
668 $q = "UPDATE Users ";
669 $q.= "SET ResetKey = '" . $resetkey . "' ";
670 $q.= "WHERE ID = " . $uid;
675 * Send a reset key to a specific e-mail address
677 * @param string $email E-mail address of the user resetting their password
678 * @param string $subject Subject of the email
679 * @param string $body Body of the email
683 function send_resetkey($email, $subject, $body) {
684 $uid = uid_from_email($email);
689 /* We (ab)use new_sid() to get a random 32 characters long string. */
690 $resetkey = new_sid();
691 create_resetkey($resetkey, $uid);
693 /* Send e-mail with confirmation link. */
694 $body = wordwrap($body, 70);
695 $body .= "\n\n". get_uri('/passreset/', true) .
696 "?resetkey={$resetkey}";
697 $headers = "MIME-Version: 1.0\r\n" .
698 "Content-type: text/plain; charset=UTF-8\r\n" .
699 "Reply-to: noreply@aur.archlinux.org\r\n" .
700 "From: notify@aur.archlinux.org\r\n" .
701 "X-Mailer: PHP\r\n" .
702 "X-MimeOLE: Produced By AUR";
703 @mail
($email, $subject, $body, $headers);
707 * Change a user's password in the database if reset key and e-mail are correct
709 * @param string $hash New MD5 hash of a user's password
710 * @param string $salt New salt for the user's password
711 * @param string $resetkey Code e-mailed to a user to reset a password
712 * @param string $email E-mail address of the user resetting their password
714 * @return string|void Redirect page if successful, otherwise return error message
716 function password_reset($hash, $salt, $resetkey, $email) {
717 $dbh = DB
::connect();
718 $q = "UPDATE Users ";
719 $q.= "SET Passwd = '$hash', ";
720 $q.= "Salt = '$salt', ";
721 $q.= "ResetKey = '' ";
722 $q.= "WHERE ResetKey != '' ";
723 $q.= "AND ResetKey = " . $dbh->quote($resetkey) . " ";
724 $q.= "AND Email = " . $dbh->quote($email);
725 $result = $dbh->exec($q);
728 $error = __('Invalid e-mail and reset key combination.');
731 header('Location: ' . get_uri('/passreset/') . '?step=complete');
737 * Determine if the password is longer than the minimum length
739 * @param string $passwd The password to check
741 * @return bool True if longer than minimum length, otherwise false
743 function good_passwd($passwd) {
744 $length_min = config_get_int('options', 'passwd_min_len');
745 return (strlen($passwd) >= $length_min);
749 * Determine if the password is correct and salt it if it hasn't been already
751 * @param string $userID The user ID to check the password against
752 * @param string $passwd The password the visitor sent
754 * @return bool True if password was correct and properly salted, otherwise false
756 function valid_passwd($userID, $passwd) {
757 $dbh = DB
::connect();
762 /* Get salt for this user. */
763 $salt = get_salt($userID);
765 $q = "SELECT ID FROM Users ";
766 $q.= "WHERE ID = " . $userID . " ";
767 $q.= "AND Passwd = " . $dbh->quote(salted_hash($passwd, $salt));
768 $result = $dbh->query($q);
773 $row = $result->fetch(PDO
::FETCH_NUM
);
774 return ($row[0] > 0);
776 /* Check password without using salt. */
777 $q = "SELECT ID FROM Users ";
778 $q.= "WHERE ID = " . $userID . " ";
779 $q.= "AND Passwd = " . $dbh->quote(md5($passwd));
780 $result = $dbh->query($q);
785 $row = $result->fetch(PDO
::FETCH_NUM
);
790 /* Password correct, but salt it first! */
791 if (!save_salt($userID, $passwd)) {
792 trigger_error("Unable to salt user's password;" .
793 " ID " . $userID, E_USER_WARNING
);
802 * Determine if a user's password is empty
804 * @param string $uid The user ID to check for an empty password
806 * @return bool True if the user's password is empty, otherwise false
808 function passwd_is_empty($uid) {
809 $dbh = DB
::connect();
811 $q = "SELECT * FROM Users WHERE ID = " . $dbh->quote($uid) . " ";
812 $q .= "AND Passwd = " . $dbh->quote('');
813 $result = $dbh->query($q);
815 if ($result->fetchColumn()) {
823 * Determine if the PGP key fingerprint is valid (must be 40 hexadecimal digits)
825 * @param string $fingerprint PGP fingerprint to check if valid
827 * @return bool True if the fingerprint is 40 hexadecimal digits, otherwise false
829 function valid_pgp_fingerprint($fingerprint) {
830 $fingerprint = str_replace(" ", "", $fingerprint);
831 return (strlen($fingerprint) == 40 && ctype_xdigit($fingerprint));
835 * Determine if the SSH public key is valid
837 * @param string $pubkey SSH public key to check
839 * @return bool True if the SSH public key is valid, otherwise false
841 function valid_ssh_pubkey($pubkey) {
842 $valid_prefixes = array(
843 "ssh-rsa", "ssh-dss", "ecdsa-sha2-nistp256",
844 "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521", "ssh-ed25519"
847 $has_valid_prefix = false;
848 foreach ($valid_prefixes as $prefix) {
849 if (strpos($pubkey, $prefix . " ") === 0) {
850 $has_valid_prefix = true;
854 if (!$has_valid_prefix) {
858 $tokens = explode(" ", $pubkey);
859 if (empty($tokens[1])) {
863 return (base64_encode(base64_decode($tokens[1], true)) == $tokens[1]);
867 * Determine if the user account has been suspended
869 * @param string $id The ID of user to check if suspended
871 * @return bool True if the user is suspended, otherwise false
873 function user_suspended($id) {
874 $dbh = DB
::connect();
878 $q = "SELECT Suspended FROM Users WHERE ID = " . $id;
879 $result = $dbh->query($q);
881 $row = $result->fetch(PDO
::FETCH_NUM
);
890 * Delete a specified user account from the database
892 * @param int $id The user ID of the account to be deleted
896 function user_delete($id) {
897 $dbh = DB
::connect();
901 * These are normally already taken care of by propagation constraints
902 * but it is better to be explicit here.
904 $fields_delete = array(
905 array("Sessions", "UsersID"),
906 array("PackageVotes", "UsersID"),
907 array("CommentNotify", "UsersID")
910 $fields_set_null = array(
911 array("PackageBases", "SubmitterUID"),
912 array("PackageBases", "MaintainerUID"),
913 array("PackageBases", "SubmitterUID"),
914 array("PackageComments", "UsersID"),
915 array("PackageComments", "DelUsersID"),
916 array("PackageRequests", "UsersID"),
917 array("TU_VoteInfo", "SubmitterID"),
918 array("TU_Votes", "UserID")
921 foreach($fields_delete as list($table, $field)) {
922 $q = "DELETE FROM " . $table . " ";
923 $q.= "WHERE " . $field . " = " . $id;
927 foreach($fields_set_null as list($table, $field)) {
928 $q = "UPDATE " . $table . " SET " . $field . " = NULL ";
929 $q.= "WHERE " . $field . " = " . $id;
933 $q = "DELETE FROM Users WHERE ID = " . $id;
939 * Remove the session from the database on logout
941 * @param string $sid User's session ID
945 function delete_session_id($sid) {
946 $dbh = DB
::connect();
948 $q = "DELETE FROM Sessions WHERE SessionID = " . $dbh->quote($sid);
953 * Remove all sessions belonging to a particular user
955 * @param int $uid ID of user to remove all sessions for
959 function delete_user_sessions($uid) {
960 $dbh = DB
::connect();
962 $q = "DELETE FROM Sessions WHERE UsersID = " . intval($uid);
967 * Remove sessions from the database that have exceed the timeout
971 function clear_expired_sessions() {
972 $dbh = DB
::connect();
974 $timeout = config_get_int('options', 'login_timeout');
975 $q = "DELETE FROM Sessions WHERE LastUpdateTS < (UNIX_TIMESTAMP() - " . $timeout . ")";
982 * Get account details for a specific user
984 * @param string $uid The User ID of account to get information for
985 * @param string $username The username of the account to get for
987 * @return array Account details for the specified user
989 function account_details($uid, $username) {
990 $dbh = DB
::connect();
991 $q = "SELECT Users.*, AccountTypes.AccountType ";
992 $q.= "FROM Users, AccountTypes ";
993 $q.= "WHERE AccountTypes.ID = Users.AccountTypeID ";
995 $q.= "AND Users.ID = ".intval($uid);
997 $q.= "AND Users.Username = " . $dbh->quote($username);
999 $result = $dbh->query($q);
1002 $row = $result->fetch(PDO
::FETCH_ASSOC
);
1009 * Determine if a user has already voted on a specific proposal
1011 * @param string $voteid The ID of the Trusted User proposal
1012 * @param string $uid The ID to check if the user already voted
1014 * @return bool True if the user has already voted, otherwise false
1016 function tu_voted($voteid, $uid) {
1017 $dbh = DB
::connect();
1019 $q = "SELECT COUNT(*) FROM TU_Votes ";
1020 $q.= "WHERE VoteID = " . intval($voteid) . " AND UserID = " . intval($uid);
1021 $result = $dbh->query($q);
1022 if ($result->fetchColumn() > 0) {
1031 * Get all current Trusted User proposals from the database
1033 * @param string $order Ascending or descending order for the proposal listing
1035 * @return array The details for all current Trusted User proposals
1037 function current_proposal_list($order) {
1038 $dbh = DB
::connect();
1040 $q = "SELECT * FROM TU_VoteInfo WHERE End > " . time() . " ORDER BY Submitted " . $order;
1041 $result = $dbh->query($q);
1044 while ($row = $result->fetch(PDO
::FETCH_ASSOC
)) {
1052 * Get a subset of all past Trusted User proposals from the database
1054 * @param string $order Ascending or descending order for the proposal listing
1055 * @param string $lim The number of proposals to list with the offset
1057 * @return array The details for the subset of past Trusted User proposals
1059 function past_proposal_list($order, $lim) {
1060 $dbh = DB
::connect();
1062 $q = "SELECT * FROM TU_VoteInfo WHERE End < " . time() . " ORDER BY Submitted " . $order . $lim;
1063 $result = $dbh->query($q);
1066 while ($row = $result->fetch(PDO
::FETCH_ASSOC
)) {
1074 * Get the vote ID of the last vote of all Trusted Users
1076 * @return array The vote ID of the last vote of each Trusted User
1078 function last_votes_list() {
1079 $dbh = DB
::connect();
1081 $q = "SELECT UserID, MAX(VoteID) AS LastVote FROM TU_Votes, ";
1082 $q .= "TU_VoteInfo, Users WHERE TU_VoteInfo.ID = TU_Votes.VoteID AND ";
1083 $q .= "TU_VoteInfo.End < UNIX_TIMESTAMP() AND ";
1084 $q .= "Users.ID = TU_Votes.UserID AND (Users.AccountTypeID = 2 OR Users.AccountTypeID = 4) ";
1085 $q .= "GROUP BY UserID ORDER BY LastVote DESC, UserName ASC";
1086 $result = $dbh->query($q);
1089 while ($row = $result->fetch(PDO
::FETCH_ASSOC
)) {
1097 * Determine the total number of Trusted User proposals
1099 * @return string The total number of Trusted User proposals
1101 function proposal_count() {
1102 $dbh = DB
::connect();
1103 $q = "SELECT COUNT(*) FROM TU_VoteInfo";
1104 $result = $dbh->query($q);
1105 $row = $result->fetch(PDO
::FETCH_NUM
);
1111 * Get all details related to a specific vote from the database
1113 * @param string $voteid The ID of the Trusted User proposal
1115 * @return array All stored details for a specific vote
1117 function vote_details($voteid) {
1118 $dbh = DB
::connect();
1120 $q = "SELECT * FROM TU_VoteInfo ";
1121 $q.= "WHERE ID = " . intval($voteid);
1123 $result = $dbh->query($q);
1124 $row = $result->fetch(PDO
::FETCH_ASSOC
);
1130 * Get an alphabetical list of users who voted for a proposal with HTML links
1132 * @param string $voteid The ID of the Trusted User proposal
1134 * @return array All users who voted for a specific proposal
1136 function voter_list($voteid) {
1137 $dbh = DB
::connect();
1139 $whovoted = array();
1141 $q = "SELECT tv.UserID,U.Username ";
1142 $q.= "FROM TU_Votes tv, Users U ";
1143 $q.= "WHERE tv.VoteID = " . intval($voteid);
1144 $q.= " AND tv.UserID = U.ID ";
1145 $q.= "ORDER BY Username";
1147 $result = $dbh->query($q);
1149 while ($row = $result->fetch(PDO
::FETCH_ASSOC
)) {
1150 $whovoted[] = $row['Username'];
1157 * Cast a vote for a specific user proposal
1159 * @param string $voteid The ID of the proposal being voted on
1160 * @param string $uid The user ID of the individual voting
1161 * @param string $vote Vote position, either "Yes", "No", or "Abstain"
1162 * @param int $newtotal The total number of votes after the user has voted
1166 function cast_proposal_vote($voteid, $uid, $vote, $newtotal) {
1167 $dbh = DB
::connect();
1169 $q = "UPDATE TU_VoteInfo SET " . $vote . " = (" . $newtotal . ") WHERE ID = " . $voteid;
1170 $result = $dbh->exec($q);
1172 $q = "INSERT INTO TU_Votes (VoteID, UserID) VALUES (" . intval($voteid) . ", " . intval($uid) . ")";
1173 $result = $dbh->exec($q);
1177 * Verify a user has the proper permissions to edit an account
1179 * @param array $acctinfo User account information for edited account
1181 * @return bool True if permission to edit the account, otherwise false
1183 function can_edit_account($acctinfo) {
1184 if ($acctinfo['AccountType'] == 'Developer' ||
1185 $acctinfo['AccountType'] == 'Trusted User & Developer') {
1186 return has_credential(CRED_ACCOUNT_EDIT_DEV
);
1189 $uid = $acctinfo['ID'];
1190 return has_credential(CRED_ACCOUNT_EDIT
, array($uid));