Update wiki links to the new short URL
[aur.git] / web / lib / acctfuncs.inc.php
blobdf016c6d8882af561f3e2fbedb06ea7706b6d131
1 <?php
2 /**
3 * Determine if an HTTP request variable is set
5 * @param string $name The request variable to test for
7 * @return string Return the value of the request variable, otherwise blank
8 */
9 function in_request($name) {
10 if (isset($_REQUEST[$name])) {
11 return $_REQUEST[$name];
13 return "";
16 /**
17 * Format the PGP key fingerprint
19 * @param string $fingerprint An unformatted PGP key fingerprint
21 * @return string PGP fingerprint with spaces every 4 characters
23 function html_format_pgp_fingerprint($fingerprint) {
24 if (strlen($fingerprint) != 40 || !ctype_xdigit($fingerprint)) {
25 return $fingerprint;
28 return htmlspecialchars(substr($fingerprint, 0, 4) . " " .
29 substr($fingerprint, 4, 4) . " " .
30 substr($fingerprint, 8, 4) . " " .
31 substr($fingerprint, 12, 4) . " " .
32 substr($fingerprint, 16, 4) . " " .
33 substr($fingerprint, 20, 4) . " " .
34 substr($fingerprint, 24, 4) . " " .
35 substr($fingerprint, 28, 4) . " " .
36 substr($fingerprint, 32, 4) . " " .
37 substr($fingerprint, 36, 4) . " ", ENT_QUOTES);
40 /**
41 * Loads the account editing form, with any values that are already saved
43 * @global array $SUPPORTED_LANGS Languages that are supported by the AUR
44 * @param string $A Form to use, either UpdateAccount or NewAccount
45 * @param string $U The username to display
46 * @param string $T The account type of the displayed user
47 * @param string $S Whether the displayed user has a suspended account
48 * @param string $E The e-mail address of the displayed user
49 * @param string $BE The backup 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 $TZ The timezone preference of the displayed user
56 * @param string $HP The homepage of the displayed user
57 * @param string $I The IRC nickname of the displayed user
58 * @param string $K The PGP key fingerprint of the displayed user
59 * @param string $PK The list of SSH public keys
60 * @param string $J The inactivity status of the displayed user
61 * @param string $CN Whether to notify of new comments
62 * @param string $UN Whether to notify of package updates
63 * @param string $ON Whether to notify of ownership changes
64 * @param string $UID The user ID of the displayed user
65 * @param string $N The username as present in the database
66 * @param string $captcha_salt The salt used for the CAPTCHA.
67 * @param string $captcha The CAPTCHA answer.
69 * @return void
71 function display_account_form($A,$U="",$T="",$S="",$E="",$BE="",$H="",$P="",$C="",$R="",
72 $L="",$TZ="",$HP="",$I="",$K="",$PK="",$J="",$CN="",$UN="",$ON="",$UID=0,$N="",$captcha_salt="",$captcha="") {
73 global $SUPPORTED_LANGS;
75 if ($TZ == "") {
76 $TZ = config_get("options", "default_timezone");
79 if (!in_array($captcha_salt, get_captcha_salts())) {
80 $captcha_salt = get_captcha_salts()[0];
81 $captcha = "";
83 $captcha_challenge = get_captcha_challenge($captcha_salt);
85 include("account_edit_form.php");
86 return;
89 /**
90 * Process information given to new/edit account form
92 * @global array $SUPPORTED_LANGS Languages that are supported by the AUR
93 * @param string $TYPE Either "edit" for editing or "new" for registering an account
94 * @param string $A Form to use, either UpdateAccount or NewAccount
95 * @param string $U The username for the account
96 * @param string $T The account type for the user
97 * @param string $S Whether or not the account is suspended
98 * @param string $E The e-mail address for the user
99 * @param string $BE The backup e-mail address for the user
100 * @param string $H Whether or not the e-mail address should be hidden
101 * @param string $P The password for the user
102 * @param string $C The confirmed password for the user
103 * @param string $R The real name of the user
104 * @param string $L The language preference of the user
105 * @param string $TZ The timezone preference of the user
106 * @param string $HP The homepage of the displayed user
107 * @param string $I The IRC nickname of the user
108 * @param string $K The PGP fingerprint of the user
109 * @param string $PK The list of public SSH keys
110 * @param string $J The inactivity status of the user
111 * @param string $CN Whether to notify of new comments
112 * @param string $UN Whether to notify of package updates
113 * @param string $ON Whether to notify of ownership changes
114 * @param string $UID The user ID of the modified account
115 * @param string $N The username as present in the database
116 * @param string $passwd The password of the logged in user.
117 * @param string $captcha_salt The salt used for the CAPTCHA.
118 * @param string $captcha The CAPTCHA answer.
120 * @return array Boolean indicating success and message to be printed
122 function process_account_form($TYPE,$A,$U="",$T="",$S="",$E="",$BE="",$H="",$P="",$C="",
123 $R="",$L="",$TZ="",$HP="",$I="",$K="",$PK="",$J="",$CN="",$UN="",$ON="",$UID=0,$N="",$passwd="",$captcha_salt="",$captcha="") {
124 global $SUPPORTED_LANGS;
126 $error = '';
127 $message = '';
129 if (is_ipbanned()) {
130 $error = __('Account registration has been disabled ' .
131 'for your IP address, probably due ' .
132 'to sustained spam attacks. Sorry for the ' .
133 'inconvenience.');
136 $dbh = DB::connect();
138 if (isset($_COOKIE['AURSID'])) {
139 $uid_session = uid_from_sid($_COOKIE['AURSID']);
140 if (!$error && check_passwd($uid_session, $passwd) != 1) {
141 $error = __("Invalid password.");
145 if (empty($E) || empty($U)) {
146 $error = __("Missing a required field.");
149 if ($TYPE != "new" && !$UID) {
150 $error = __("Missing User ID");
153 if (!$error && !valid_username($U)) {
154 $length_min = config_get_int('options', 'username_min_len');
155 $length_max = config_get_int('options', 'username_max_len');
157 $error = __("The username is invalid.") . "<ul>\n"
158 . "<li>" . __("It must be between %s and %s characters long", $length_min, $length_max)
159 . "</li>"
160 . "<li>" . __("Start and end with a letter or number") . "</li>"
161 . "<li>" . __("Can contain only one period, underscore or hyphen.")
162 . "</li>\n</ul>";
165 if (!$error && $P && !$C) {
166 $error = __("Please confirm your new password.");
168 if (!$error && $P && $P != $C) {
169 $error = __("Password fields do not match.");
171 if (!$error && $P != '' && !good_passwd($P)) {
172 $length_min = config_get_int('options', 'passwd_min_len');
173 $error = __("Your password must be at least %s characters.",
174 $length_min);
177 if (!$error && !valid_email($E)) {
178 $error = __("The email address is invalid.");
180 if (!$error && $BE && !valid_email($BE)) {
181 $error = __("The backup email address is invalid.");
184 if (!$error && !empty($HP) && !valid_homepage($HP)) {
185 $error = __("The home page is invalid, please specify the full HTTP(s) URL.");
188 if (!$error && $K != '' && !valid_pgp_fingerprint($K)) {
189 $error = __("The PGP key fingerprint is invalid.");
192 if (!$error && !empty($PK)) {
193 $ssh_keys = array_filter(array_map('trim', explode("\n", $PK)));
194 $ssh_fingerprints = array();
196 foreach ($ssh_keys as &$ssh_key) {
197 if (!valid_ssh_pubkey($ssh_key)) {
198 $error = __("The SSH public key is invalid.");
199 break;
202 $ssh_fingerprint = ssh_key_fingerprint($ssh_key);
203 if (!$ssh_fingerprint) {
204 $error = __("The SSH public key is invalid.");
205 break;
208 $tokens = explode(" ", $ssh_key);
209 $ssh_key = $tokens[0] . " " . $tokens[1];
211 $ssh_fingerprints[] = $ssh_fingerprint;
215 * Destroy last reference to prevent accidentally overwriting
216 * an array element.
218 unset($ssh_key);
221 if (isset($_COOKIE['AURSID'])) {
222 $atype = account_from_sid($_COOKIE['AURSID']);
223 if (($atype == "User" && $T > 1) || ($atype == "Trusted User" && $T > 2)) {
224 $error = __("Cannot increase account permissions.");
228 if (!$error && !array_key_exists($L, $SUPPORTED_LANGS)) {
229 $error = __("Language is not currently supported.");
231 if (!$error && !array_key_exists($TZ, generate_timezone_list())) {
232 $error = __("Timezone is not currently supported.");
234 if (!$error) {
236 * Check whether the user name is available.
237 * TODO: Fix race condition.
239 $q = "SELECT COUNT(*) AS CNT FROM Users ";
240 $q.= "WHERE Username = " . $dbh->quote($U);
241 if ($TYPE == "edit") {
242 $q.= " AND ID != ".intval($UID);
244 $result = $dbh->query($q);
245 $row = $result->fetch(PDO::FETCH_NUM);
247 if ($row[0]) {
248 $error = __("The username, %s%s%s, is already in use.",
249 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
252 if (!$error) {
254 * Check whether the e-mail address is available.
255 * TODO: Fix race condition.
257 $q = "SELECT COUNT(*) AS CNT FROM Users ";
258 $q.= "WHERE Email = " . $dbh->quote($E);
259 if ($TYPE == "edit") {
260 $q.= " AND ID != ".intval($UID);
262 $result = $dbh->query($q);
263 $row = $result->fetch(PDO::FETCH_NUM);
265 if ($row[0]) {
266 $error = __("The address, %s%s%s, is already in use.",
267 "<strong>", htmlspecialchars($E,ENT_QUOTES), "</strong>");
270 if (!$error && isset($ssh_keys) && count($ssh_keys) > 0) {
272 * Check whether any of the SSH public keys is already in use.
273 * TODO: Fix race condition.
275 $q = "SELECT Fingerprint FROM SSHPubKeys ";
276 $q.= "WHERE Fingerprint IN (";
277 $q.= implode(',', array_map(array($dbh, 'quote'), $ssh_fingerprints));
278 $q.= ")";
279 if ($TYPE == "edit") {
280 $q.= " AND UserID != " . intval($UID);
282 $result = $dbh->query($q);
283 $row = $result->fetch(PDO::FETCH_NUM);
285 if ($row) {
286 $error = __("The SSH public key, %s%s%s, is already in use.",
287 "<strong>", htmlspecialchars($row[0], ENT_QUOTES), "</strong>");
291 if (!$error && $TYPE == "new" && empty($captcha)) {
292 $error = __("The CAPTCHA is missing.");
295 if (!$error && $TYPE == "new" && !in_array($captcha_salt, get_captcha_salts())) {
296 $error = __("This CAPTCHA has expired. Please try again.");
299 if (!$error && $TYPE == "new" && $captcha != get_captcha_answer($captcha_salt)) {
300 $error = __("The entered CAPTCHA answer is invalid.");
303 if ($error) {
304 $message = "<ul class='errorlist'><li>".$error."</li></ul>\n";
305 return array(false, $message);
308 if ($TYPE == "new") {
309 /* Create an unprivileged user. */
310 if (empty($P)) {
311 $send_resetkey = true;
312 $email = $E;
313 } else {
314 $send_resetkey = false;
315 $P = password_hash($P, PASSWORD_DEFAULT);
317 $U = $dbh->quote($U);
318 $E = $dbh->quote($E);
319 $BE = $dbh->quote($BE);
320 $P = $dbh->quote($P);
321 $R = $dbh->quote($R);
322 $L = $dbh->quote($L);
323 $TZ = $dbh->quote($TZ);
324 $HP = $dbh->quote($HP);
325 $I = $dbh->quote($I);
326 $K = $dbh->quote(str_replace(" ", "", $K));
327 $q = "INSERT INTO Users (AccountTypeID, Suspended, ";
328 $q.= "InactivityTS, Username, Email, BackupEmail, Passwd , ";
329 $q.= "RealName, LangPreference, Timezone, Homepage, IRCNick, PGPKey) ";
330 $q.= "VALUES (1, 0, 0, $U, $E, $BE, $P, $R, $L, $TZ, ";
331 $q.= "$HP, $I, $K)";
332 $result = $dbh->exec($q);
333 if (!$result) {
334 $message = __("Error trying to create account, %s%s%s.",
335 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
336 return array(false, $message);
339 $uid = $dbh->lastInsertId();
340 if (isset($ssh_keys) && count($ssh_keys) > 0) {
341 account_set_ssh_keys($uid, $ssh_keys, $ssh_fingerprints);
344 $message = __("The account, %s%s%s, has been successfully created.",
345 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
346 $message .= "<p>\n";
348 if ($send_resetkey) {
349 send_resetkey($email, true);
350 $message .= __("A password reset key has been sent to your e-mail address.");
351 $message .= "</p>\n";
352 } else {
353 $message .= __("Click on the Login link above to use your account.");
354 $message .= "</p>\n";
356 } else {
357 /* Modify an existing account. */
358 $q = "SELECT InactivityTS FROM Users WHERE ";
359 $q.= "ID = " . intval($UID);
360 $result = $dbh->query($q);
361 $row = $result->fetch(PDO::FETCH_NUM);
362 if ($row[0] && $J) {
363 $inactivity_ts = $row[0];
364 } elseif ($J) {
365 $inactivity_ts = time();
366 } else {
367 $inactivity_ts = 0;
370 $q = "UPDATE Users SET ";
371 $q.= "Username = " . $dbh->quote($U);
372 if ($T) {
373 $q.= ", AccountTypeID = ".intval($T);
375 if ($S) {
376 /* Ensure suspended users can't keep an active session */
377 delete_user_sessions($UID);
378 $q.= ", Suspended = 1";
379 } else {
380 $q.= ", Suspended = 0";
382 $q.= ", Email = " . $dbh->quote($E);
383 $q.= ", BackupEmail = " . $dbh->quote($BE);
384 if ($H) {
385 $q.= ", HideEmail = 1";
386 } else {
387 $q.= ", HideEmail = 0";
389 if ($P) {
390 $hash = password_hash($P, PASSWORD_DEFAULT);
391 $q .= ", Passwd = " . $dbh->quote($hash);
393 $q.= ", RealName = " . $dbh->quote($R);
394 $q.= ", LangPreference = " . $dbh->quote($L);
395 $q.= ", Timezone = " . $dbh->quote($TZ);
396 $q.= ", Homepage = " . $dbh->quote($HP);
397 $q.= ", IRCNick = " . $dbh->quote($I);
398 $q.= ", PGPKey = " . $dbh->quote(str_replace(" ", "", $K));
399 $q.= ", InactivityTS = " . $inactivity_ts;
400 $q.= ", CommentNotify = " . ($CN ? "1" : "0");
401 $q.= ", UpdateNotify = " . ($UN ? "1" : "0");
402 $q.= ", OwnershipNotify = " . ($ON ? "1" : "0");
403 $q.= " WHERE ID = ".intval($UID);
404 $result = $dbh->exec($q);
406 if (isset($ssh_keys) && count($ssh_keys) > 0) {
407 $ssh_key_result = account_set_ssh_keys($UID, $ssh_keys, $ssh_fingerprints);
408 } else {
409 $ssh_key_result = true;
412 if (isset($_COOKIE["AURTZ"]) && ($_COOKIE["AURTZ"] != $TZ)) {
413 /* set new cookie for timezone */
414 $timeout = intval(config_get("options", "persistent_cookie_timeout"));
415 $cookie_time = time() + $timeout;
416 setcookie("AURTZ", $TZ, $cookie_time, "/");
419 if (isset($_COOKIE["AURLANG"]) && ($_COOKIE["AURLANG"] != $L)) {
420 /* set new cookie for language */
421 $timeout = intval(config_get("options", "persistent_cookie_timeout"));
422 $cookie_time = time() + $timeout;
423 setcookie("AURLANG", $L, $cookie_time, "/");
426 if ($result === false || $ssh_key_result === false) {
427 $message = __("No changes were made to the account, %s%s%s.",
428 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
429 } else {
430 $message = __("The account, %s%s%s, has been successfully modified.",
431 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
435 return array(true, $message);
439 * Display the search results page
441 * @param string $O The offset for the results page
442 * @param string $SB The column to sort the results page by
443 * @param string $U The username search criteria
444 * @param string $T The account type search criteria
445 * @param string $S Whether the account is suspended search criteria
446 * @param string $E The e-mail address search criteria
447 * @param string $R The real name search criteria
448 * @param string $I The IRC nickname search criteria
449 * @param string $K The PGP key fingerprint search criteria
451 * @return void
453 function search_results_page($O=0,$SB="",$U="",$T="",
454 $S="",$E="",$R="",$I="",$K="") {
456 $HITS_PER_PAGE = 50;
457 if ($O) {
458 $OFFSET = intval($O);
459 } else {
460 $OFFSET = 0;
462 if ($OFFSET < 0) {
463 $OFFSET = 0;
465 $search_vars = array();
467 $dbh = DB::connect();
469 $q = "SELECT Users.*, AccountTypes.AccountType ";
470 $q.= "FROM Users, AccountTypes ";
471 $q.= "WHERE AccountTypes.ID = Users.AccountTypeID ";
472 if ($T == "u") {
473 $q.= "AND AccountTypes.ID = 1 ";
474 $search_vars[] = "T";
475 } elseif ($T == "t") {
476 $q.= "AND AccountTypes.ID = 2 ";
477 $search_vars[] = "T";
478 } elseif ($T == "d") {
479 $q.= "AND AccountTypes.ID = 3 ";
480 $search_vars[] = "T";
481 } elseif ($T == "td") {
482 $q.= "AND AccountTypes.ID = 4 ";
483 $search_vars[] = "T";
485 if ($S) {
486 $q.= "AND Users.Suspended = 1 ";
487 $search_vars[] = "S";
489 if ($U) {
490 $U = "%" . addcslashes($U, '%_') . "%";
491 $q.= "AND Username LIKE " . $dbh->quote($U) . " ";
492 $search_vars[] = "U";
494 if ($E) {
495 $E = "%" . addcslashes($E, '%_') . "%";
496 $q.= "AND Email LIKE " . $dbh->quote($E) . " ";
497 $search_vars[] = "E";
499 if ($R) {
500 $R = "%" . addcslashes($R, '%_') . "%";
501 $q.= "AND RealName LIKE " . $dbh->quote($R) . " ";
502 $search_vars[] = "R";
504 if ($I) {
505 $I = "%" . addcslashes($I, '%_') . "%";
506 $q.= "AND IRCNick LIKE " . $dbh->quote($I) . " ";
507 $search_vars[] = "I";
509 if ($K) {
510 $K = "%" . addcslashes(str_replace(" ", "", $K), '%_') . "%";
511 $q.= "AND PGPKey LIKE " . $dbh->quote($K) . " ";
512 $search_vars[] = "K";
514 switch ($SB) {
515 case 't':
516 $q.= "ORDER BY AccountTypeID, Username ";
517 break;
518 case 'r':
519 $q.= "ORDER BY RealName, AccountTypeID ";
520 break;
521 case 'i':
522 $q.= "ORDER BY IRCNick, AccountTypeID ";
523 break;
524 default:
525 $q.= "ORDER BY Username, AccountTypeID ";
526 break;
528 $search_vars[] = "SB";
529 $q.= "LIMIT " . $HITS_PER_PAGE . " OFFSET " . $OFFSET;
531 $dbh = DB::connect();
533 $result = $dbh->query($q);
535 $userinfo = array();
536 if ($result) {
537 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
538 $userinfo[] = $row;
542 include("account_search_results.php");
543 return;
547 * Attempt to login and generate a session
549 * @return array Session ID for user, error message if applicable
551 function try_login() {
552 $login_error = "";
553 $new_sid = "";
554 $userID = null;
556 if (!isset($_REQUEST['user']) && !isset($_REQUEST['passwd'])) {
557 return array('SID' => '', 'error' => null);
560 if (is_ipbanned()) {
561 $login_error = __('The login form is currently disabled ' .
562 'for your IP address, probably due ' .
563 'to sustained spam attacks. Sorry for the ' .
564 'inconvenience.');
565 return array('SID' => '', 'error' => $login_error);
568 $dbh = DB::connect();
569 $userID = uid_from_loginname($_REQUEST['user']);
571 if (user_suspended($userID)) {
572 $login_error = __('Account suspended');
573 return array('SID' => '', 'error' => $login_error);
576 switch (check_passwd($userID, $_REQUEST['passwd'])) {
577 case -1:
578 $login_error = __('Your password has been reset. ' .
579 'If you just created a new account, please ' .
580 'use the link from the confirmation email ' .
581 'to set an initial password. Otherwise, ' .
582 'please request a reset key on the %s' .
583 'Password Reset%s page.', '<a href="' .
584 htmlspecialchars(get_uri('/passreset')) . '">',
585 '</a>');
586 return array('SID' => '', 'error' => $login_error);
587 case 0:
588 $login_error = __("Bad username or password.");
589 return array('SID' => '', 'error' => $login_error);
590 case 1:
591 break;
594 $logged_in = 0;
595 $num_tries = 0;
597 /* Generate a session ID and store it. */
598 while (!$logged_in && $num_tries < 5) {
599 $new_sid = new_sid();
600 $q = "INSERT INTO Sessions (UsersID, SessionID, LastUpdateTS)"
601 ." VALUES (" . $userID . ", '" . $new_sid . "', " . strval(time()) . ")";
602 $result = $dbh->exec($q);
604 /* Query will fail if $new_sid is not unique. */
605 if ($result) {
606 $logged_in = 1;
607 break;
610 $num_tries++;
613 if (!$logged_in) {
614 $login_error = __('An error occurred trying to generate a user session.');
615 return array('SID' => $new_sid, 'error' => $login_error);
618 $q = "UPDATE Users SET LastLogin = " . strval(time()) . ", ";
619 $q.= "LastLoginIPAddress = " . $dbh->quote($_SERVER['REMOTE_ADDR']) . " ";
620 $q.= "WHERE ID = $userID";
621 $dbh->exec($q);
623 /* Set the SID cookie. */
624 if (isset($_POST['remember_me']) && $_POST['remember_me'] == "on") {
625 /* Set cookies for 30 days. */
626 $timeout = config_get_int('options', 'persistent_cookie_timeout');
627 $cookie_time = time() + $timeout;
629 /* Set session for 30 days. */
630 $q = "UPDATE Sessions SET LastUpdateTS = $cookie_time ";
631 $q.= "WHERE SessionID = '$new_sid'";
632 $dbh->exec($q);
633 } else {
634 $cookie_time = 0;
637 setcookie("AURSID", $new_sid, $cookie_time, "/", null, !empty($_SERVER['HTTPS']), true);
639 $referer = in_request('referer');
640 if (strpos($referer, aur_location()) !== 0) {
641 $referer = '/';
643 header("Location: " . get_uri($referer));
644 $login_error = "";
645 return array('SID' => $new_sid, 'error' => null);
649 * Determine if the user is using a banned IP address
651 * @return bool True if IP address is banned, otherwise false
653 function is_ipbanned() {
654 $dbh = DB::connect();
656 $q = "SELECT * FROM Bans WHERE IPAddress = " . $dbh->quote($_SERVER['REMOTE_ADDR']);
657 $result = $dbh->query($q);
659 return ($result->fetchColumn() ? true : false);
663 * Validate a username against a collection of rules
665 * The username must be longer or equal to the configured minimum length. It
666 * must be shorter or equal to the configured maximum length. It must start and
667 * end with either a letter or a number. It can contain one period, hypen, or
668 * underscore. Returns boolean of whether name is valid.
670 * @param string $user Username to validate
672 * @return bool True if username meets criteria, otherwise false
674 function valid_username($user) {
675 $length_min = config_get_int('options', 'username_min_len');
676 $length_max = config_get_int('options', 'username_max_len');
678 if (strlen($user) < $length_min || strlen($user) > $length_max) {
679 return false;
680 } else if (!preg_match("/^[a-z0-9]+[.\-_]?[a-z0-9]+$/Di", $user)) {
681 return false;
684 return true;
688 * Determine if a user already has a proposal open about themselves
690 * @param string $user Username to checkout for open proposal
692 * @return bool True if there is an open proposal about the user, otherwise false
694 function open_user_proposals($user) {
695 $dbh = DB::connect();
696 $q = "SELECT * FROM TU_VoteInfo WHERE User = " . $dbh->quote($user) . " ";
697 $q.= "AND End > " . strval(time());
698 $result = $dbh->query($q);
700 return ($result->fetchColumn() ? true : false);
704 * Add a new Trusted User proposal to the database
706 * @param string $agenda The agenda of the vote
707 * @param string $user The use the vote is about
708 * @param int $votelength The length of time for the vote to last
709 * @param string $submitteruid The user ID of the individual who submitted the proposal
711 * @return void
713 function add_tu_proposal($agenda, $user, $votelength, $quorum, $submitteruid) {
714 $dbh = DB::connect();
716 $q = "SELECT COUNT(*) FROM Users WHERE (AccountTypeID = 2 OR AccountTypeID = 4)";
717 $result = $dbh->query($q);
718 $row = $result->fetch(PDO::FETCH_NUM);
719 $active_tus = $row[0];
721 $q = "INSERT INTO TU_VoteInfo (Agenda, User, Submitted, End, Quorum, ";
722 $q.= "SubmitterID, ActiveTUs) VALUES ";
723 $q.= "(" . $dbh->quote($agenda) . ", " . $dbh->quote($user) . ", ";
724 $q.= strval(time()) . ", " . strval(time()) . " + " . $dbh->quote($votelength);
725 $q.= ", " . $dbh->quote($quorum) . ", " . $submitteruid . ", ";
726 $q.= $active_tus . ")";
727 $result = $dbh->exec($q);
731 * Add a reset key to the database for a specified user
733 * @param string $resetkey A password reset key to be stored in database
734 * @param string $uid The user ID to store the reset key for
736 * @return void
738 function create_resetkey($resetkey, $uid) {
739 $dbh = DB::connect();
740 $q = "UPDATE Users ";
741 $q.= "SET ResetKey = '" . $resetkey . "' ";
742 $q.= "WHERE ID = " . $uid;
743 $dbh->exec($q);
747 * Send a reset key to a specific e-mail address
749 * @param string $user User name or email address of the user
750 * @param bool $welcome Whether to use the welcome message
752 * @return void
754 function send_resetkey($user, $welcome=false) {
755 $uid = uid_from_loginname($user);
756 if ($uid == null) {
757 return;
760 /* We (ab)use new_sid() to get a random 32 characters long string. */
761 $resetkey = new_sid();
762 create_resetkey($resetkey, $uid);
764 /* Send e-mail with confirmation link. */
765 notify(array($welcome ? 'welcome' : 'send-resetkey', $uid));
769 * Change a user's password in the database if reset key and e-mail are correct
771 * @param string $password The new password
772 * @param string $resetkey Code e-mailed to a user to reset a password
773 * @param string $user User name or email address of the user
775 * @return string|void Redirect page if successful, otherwise return error message
777 function password_reset($password, $resetkey, $user) {
778 $hash = password_hash($password, PASSWORD_DEFAULT);
780 $dbh = DB::connect();
781 $q = "UPDATE Users SET ";
782 $q.= "Passwd = " . $dbh->quote($hash) . ", ";
783 $q.= "ResetKey = '' ";
784 $q.= "WHERE ResetKey != '' ";
785 $q.= "AND ResetKey = " . $dbh->quote($resetkey) . " ";
786 $q.= "AND (Email = " . $dbh->quote($user) . " OR ";
787 $q.= "UserName = " . $dbh->quote($user) . ")";
788 $result = $dbh->exec($q);
790 if (!$result) {
791 $error = __('Invalid e-mail and reset key combination.');
792 return $error;
793 } else {
794 header('Location: ' . get_uri('/passreset/') . '?step=complete');
795 exit();
800 * Determine if the password is longer than the minimum length
802 * @param string $passwd The password to check
804 * @return bool True if longer than minimum length, otherwise false
806 function good_passwd($passwd) {
807 $length_min = config_get_int('options', 'passwd_min_len');
808 return (strlen($passwd) >= $length_min);
812 * Determine if the password is correct and salt it if it hasn't been already
814 * @param int $user_id The user ID to check the password against
815 * @param string $passwd The password the visitor sent
817 * @return int Positive if password is correct, negative if password is unset
819 function check_passwd($user_id, $passwd) {
820 $dbh = DB::connect();
822 /* Get password hash and salt. */
823 $q = "SELECT Passwd, Salt FROM Users WHERE ID = " . intval($user_id);
824 $result = $dbh->query($q);
825 if (!$result) {
826 return 0;
828 $row = $result->fetch(PDO::FETCH_ASSOC);
829 if (!$row) {
830 return 0;
832 $hash = $row['Passwd'];
833 $salt = $row['Salt'];
834 if (!$hash) {
835 return -1;
838 /* Verify the password hash. */
839 if (!password_verify($passwd, $hash)) {
840 /* Invalid password, fall back to MD5. */
841 if (md5($salt . $passwd) != $hash) {
842 return 0;
846 /* Password correct, migrate the hash if necessary. */
847 if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
848 $hash = password_hash($passwd, PASSWORD_DEFAULT);
850 $q = "UPDATE Users SET Passwd = " . $dbh->quote($hash) . " ";
851 $q.= "WHERE ID = " . intval($user_id);
852 $dbh->query($q);
855 return 1;
859 * Determine if the PGP key fingerprint is valid (must be 40 hexadecimal digits)
861 * @param string $fingerprint PGP fingerprint to check if valid
863 * @return bool True if the fingerprint is 40 hexadecimal digits, otherwise false
865 function valid_pgp_fingerprint($fingerprint) {
866 $fingerprint = str_replace(" ", "", $fingerprint);
867 return (strlen($fingerprint) == 40 && ctype_xdigit($fingerprint));
871 * Determine if the SSH public key is valid
873 * @param string $pubkey SSH public key to check
875 * @return bool True if the SSH public key is valid, otherwise false
877 function valid_ssh_pubkey($pubkey) {
878 $valid_prefixes = array(
879 "ssh-rsa", "ssh-dss", "ecdsa-sha2-nistp256",
880 "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521", "ssh-ed25519"
883 $has_valid_prefix = false;
884 foreach ($valid_prefixes as $prefix) {
885 if (strpos($pubkey, $prefix . " ") === 0) {
886 $has_valid_prefix = true;
887 break;
890 if (!$has_valid_prefix) {
891 return false;
894 $tokens = explode(" ", $pubkey);
895 if (empty($tokens[1])) {
896 return false;
899 return (base64_encode(base64_decode($tokens[1], true)) == $tokens[1]);
903 * Determine if the user account has been suspended
905 * @param string $id The ID of user to check if suspended
907 * @return bool True if the user is suspended, otherwise false
909 function user_suspended($id) {
910 $dbh = DB::connect();
911 if (!$id) {
912 return false;
914 $q = "SELECT Suspended FROM Users WHERE ID = " . $id;
915 $result = $dbh->query($q);
916 if ($result) {
917 $row = $result->fetch(PDO::FETCH_NUM);
918 if ($row[0]) {
919 return true;
922 return false;
926 * Delete a specified user account from the database
928 * @param int $id The user ID of the account to be deleted
930 * @return void
932 function user_delete($id) {
933 $dbh = DB::connect();
934 $id = intval($id);
937 * These are normally already taken care of by propagation constraints
938 * but it is better to be explicit here.
940 $fields_delete = array(
941 array("Sessions", "UsersID"),
942 array("PackageVotes", "UsersID"),
943 array("PackageNotifications", "UserID")
946 $fields_set_null = array(
947 array("PackageBases", "SubmitterUID"),
948 array("PackageBases", "MaintainerUID"),
949 array("PackageBases", "PackagerUID"),
950 array("PackageComments", "UsersID"),
951 array("PackageComments", "DelUsersID"),
952 array("PackageRequests", "UsersID"),
953 array("TU_VoteInfo", "SubmitterID"),
954 array("TU_Votes", "UserID")
957 foreach($fields_delete as list($table, $field)) {
958 $q = "DELETE FROM " . $table . " ";
959 $q.= "WHERE " . $field . " = " . $id;
960 $dbh->query($q);
963 foreach($fields_set_null as list($table, $field)) {
964 $q = "UPDATE " . $table . " SET " . $field . " = NULL ";
965 $q.= "WHERE " . $field . " = " . $id;
966 $dbh->query($q);
969 $q = "DELETE FROM Users WHERE ID = " . $id;
970 $dbh->query($q);
971 return;
975 * Remove the session from the database on logout
977 * @param string $sid User's session ID
979 * @return void
981 function delete_session_id($sid) {
982 $dbh = DB::connect();
984 $q = "DELETE FROM Sessions WHERE SessionID = " . $dbh->quote($sid);
985 $dbh->query($q);
989 * Remove all sessions belonging to a particular user
991 * @param int $uid ID of user to remove all sessions for
993 * @return void
995 function delete_user_sessions($uid) {
996 $dbh = DB::connect();
998 $q = "DELETE FROM Sessions WHERE UsersID = " . intval($uid);
999 $dbh->exec($q);
1003 * Remove sessions from the database that have exceed the timeout
1005 * @return void
1007 function clear_expired_sessions() {
1008 $dbh = DB::connect();
1010 $timeout = config_get_int('options', 'login_timeout');
1011 $q = "DELETE FROM Sessions WHERE LastUpdateTS < (" . strval(time()) . " - " . $timeout . ")";
1012 $dbh->query($q);
1014 return;
1018 * Get account details for a specific user
1020 * @param string $uid The User ID of account to get information for
1021 * @param string $username The username of the account to get for
1023 * @return array Account details for the specified user
1025 function account_details($uid, $username) {
1026 $dbh = DB::connect();
1027 $q = "SELECT Users.*, AccountTypes.AccountType ";
1028 $q.= "FROM Users, AccountTypes ";
1029 $q.= "WHERE AccountTypes.ID = Users.AccountTypeID ";
1030 if (!empty($uid)) {
1031 $q.= "AND Users.ID = ".intval($uid);
1032 } else {
1033 $q.= "AND Users.Username = " . $dbh->quote($username);
1035 $result = $dbh->query($q);
1037 if ($result) {
1038 $row = $result->fetch(PDO::FETCH_ASSOC);
1041 return $row;
1045 * Determine if a user has already voted on a specific proposal
1047 * @param string $voteid The ID of the Trusted User proposal
1048 * @param string $uid The ID to check if the user already voted
1050 * @return bool True if the user has already voted, otherwise false
1052 function tu_voted($voteid, $uid) {
1053 $dbh = DB::connect();
1055 $q = "SELECT COUNT(*) FROM TU_Votes ";
1056 $q.= "WHERE VoteID = " . intval($voteid) . " AND UserID = " . intval($uid);
1057 $result = $dbh->query($q);
1058 if ($result->fetchColumn() > 0) {
1059 return true;
1061 else {
1062 return false;
1067 * Get all current Trusted User proposals from the database
1069 * @param string $order Ascending or descending order for the proposal listing
1071 * @return array The details for all current Trusted User proposals
1073 function current_proposal_list($order) {
1074 $dbh = DB::connect();
1076 $q = "SELECT * FROM TU_VoteInfo WHERE End > " . time() . " ORDER BY Submitted " . $order;
1077 $result = $dbh->query($q);
1079 $details = array();
1080 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
1081 $details[] = $row;
1084 return $details;
1088 * Get a subset of all past Trusted User proposals from the database
1090 * @param string $order Ascending or descending order for the proposal listing
1091 * @param string $lim The number of proposals to list with the offset
1093 * @return array The details for the subset of past Trusted User proposals
1095 function past_proposal_list($order, $lim) {
1096 $dbh = DB::connect();
1098 $q = "SELECT * FROM TU_VoteInfo WHERE End < " . time() . " ORDER BY Submitted " . $order . $lim;
1099 $result = $dbh->query($q);
1101 $details = array();
1102 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
1103 $details[] = $row;
1106 return $details;
1110 * Get the vote ID of the last vote of all Trusted Users
1112 * @return array The vote ID of the last vote of each Trusted User
1114 function last_votes_list() {
1115 $dbh = DB::connect();
1117 $q = "SELECT UserID, MAX(VoteID) AS LastVote FROM TU_Votes, ";
1118 $q .= "TU_VoteInfo, Users WHERE TU_VoteInfo.ID = TU_Votes.VoteID AND ";
1119 $q .= "TU_VoteInfo.End < " . strval(time()) . " AND ";
1120 $q .= "Users.ID = TU_Votes.UserID AND (Users.AccountTypeID = 2 OR Users.AccountTypeID = 4) ";
1121 $q .= "GROUP BY UserID ORDER BY LastVote DESC, UserName ASC";
1122 $result = $dbh->query($q);
1124 $details = array();
1125 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
1126 $details[] = $row;
1129 return $details;
1133 * Determine the total number of Trusted User proposals
1135 * @return string The total number of Trusted User proposals
1137 function proposal_count() {
1138 $dbh = DB::connect();
1139 $q = "SELECT COUNT(*) FROM TU_VoteInfo";
1140 $result = $dbh->query($q);
1141 $row = $result->fetch(PDO::FETCH_NUM);
1143 return $row[0];
1147 * Get all details related to a specific vote from the database
1149 * @param string $voteid The ID of the Trusted User proposal
1151 * @return array All stored details for a specific vote
1153 function vote_details($voteid) {
1154 $dbh = DB::connect();
1156 $q = "SELECT * FROM TU_VoteInfo ";
1157 $q.= "WHERE ID = " . intval($voteid);
1159 $result = $dbh->query($q);
1160 $row = $result->fetch(PDO::FETCH_ASSOC);
1162 return $row;
1166 * Get an alphabetical list of users who voted for a proposal with HTML links
1168 * @param string $voteid The ID of the Trusted User proposal
1170 * @return array All users who voted for a specific proposal
1172 function voter_list($voteid) {
1173 $dbh = DB::connect();
1175 $whovoted = array();
1177 $q = "SELECT tv.UserID,U.Username ";
1178 $q.= "FROM TU_Votes tv, Users U ";
1179 $q.= "WHERE tv.VoteID = " . intval($voteid);
1180 $q.= " AND tv.UserID = U.ID ";
1181 $q.= "ORDER BY Username";
1183 $result = $dbh->query($q);
1184 if ($result) {
1185 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
1186 $whovoted[] = $row['Username'];
1189 return $whovoted;
1193 * Cast a vote for a specific user proposal
1195 * @param string $voteid The ID of the proposal being voted on
1196 * @param string $uid The user ID of the individual voting
1197 * @param string $vote Vote position, either "Yes", "No", or "Abstain"
1198 * @param int $newtotal The total number of votes after the user has voted
1200 * @return void
1202 function cast_proposal_vote($voteid, $uid, $vote, $newtotal) {
1203 $dbh = DB::connect();
1205 $q = "UPDATE TU_VoteInfo SET " . $vote . " = (" . $newtotal . ") WHERE ID = " . $voteid;
1206 $result = $dbh->exec($q);
1208 $q = "INSERT INTO TU_Votes (VoteID, UserID) VALUES (" . intval($voteid) . ", " . intval($uid) . ")";
1209 $result = $dbh->exec($q);
1213 * Verify a user has the proper permissions to edit an account
1215 * @param array $acctinfo User account information for edited account
1217 * @return bool True if permission to edit the account, otherwise false
1219 function can_edit_account($acctinfo) {
1220 if ($acctinfo['AccountType'] == 'Developer' ||
1221 $acctinfo['AccountType'] == 'Trusted User & Developer') {
1222 return has_credential(CRED_ACCOUNT_EDIT_DEV);
1225 $uid = $acctinfo['ID'];
1226 return has_credential(CRED_ACCOUNT_EDIT, array($uid));
1230 * Compute the fingerprint of an SSH key.
1232 * @param string $ssh_key The SSH public key to retrieve the fingerprint for
1234 * @return string The SSH key fingerprint
1236 function ssh_key_fingerprint($ssh_key) {
1237 $tmpfile = tempnam(sys_get_temp_dir(), "aurweb");
1238 file_put_contents($tmpfile, $ssh_key);
1241 * The -l option of ssh-keygen can be used to show the fingerprint of
1242 * the specified public key file. Expected output format:
1244 * 2048 SHA256:uBBTXmCNjI2CnLfkuz9sG8F+e9/T4C+qQQwLZWIODBY user@host (RSA)
1246 * ... where 2048 is the key length, the second token is the actual
1247 * fingerprint, followed by the key comment and the key type.
1250 $cmd = "/usr/bin/ssh-keygen -l -f " . escapeshellarg($tmpfile);
1251 exec($cmd, $out, $ret);
1252 if ($ret !== 0 || count($out) !== 1) {
1253 return false;
1256 unlink($tmpfile);
1258 $tokens = explode(' ', $out[0]);
1259 if (count($tokens) < 4) {
1260 return false;
1263 $tokens = explode(':', $tokens[1]);
1264 if (count($tokens) != 2 || $tokens[0] != 'SHA256') {
1265 return false;
1268 return $tokens[1];
1272 * Get the SSH public keys associated with an account.
1274 * @param int $uid The user ID of the account to retrieve the keys for.
1276 * @return array An array representing the keys
1278 function account_get_ssh_keys($uid) {
1279 $dbh = DB::connect();
1280 $q = "SELECT PubKey FROM SSHPubKeys WHERE UserID = " . intval($uid);
1281 $result = $dbh->query($q);
1283 if ($result) {
1284 return $result->fetchAll(PDO::FETCH_COLUMN, 0);
1285 } else {
1286 return array();
1291 * Set the SSH public keys associated with an account.
1293 * @param int $uid The user ID of the account to assign the keys to.
1294 * @param array $ssh_keys The SSH public keys.
1295 * @param array $ssh_fingerprints The corresponding SSH key fingerprints.
1297 * @return bool Boolean flag indicating success or failure.
1299 function account_set_ssh_keys($uid, $ssh_keys, $ssh_fingerprints) {
1300 $dbh = DB::connect();
1302 $q = sprintf("DELETE FROM SSHPubKeys WHERE UserID = %d", $uid);
1303 $dbh->exec($q);
1305 $ssh_fingerprint = reset($ssh_fingerprints);
1306 foreach ($ssh_keys as $ssh_key) {
1307 $q = sprintf(
1308 "INSERT INTO SSHPubKeys (UserID, Fingerprint, PubKey) " .
1309 "VALUES (%d, %s, %s)", $uid,
1310 $dbh->quote($ssh_fingerprint), $dbh->quote($ssh_key)
1312 $dbh->exec($q);
1313 $ssh_fingerprint = next($ssh_fingerprints);
1316 return true;
1320 * Invoke the email notification script.
1322 * @param string $params Command line parameters for the script.
1324 * @return void
1326 function notify($params) {
1327 $cmd = config_get('notifications', 'notify-cmd');
1328 foreach ($params as $param) {
1329 $cmd .= ' ' . escapeshellarg($param);
1332 $descspec = array(
1333 0 => array('pipe', 'r'),
1334 1 => array('pipe', 'w'),
1337 $p = proc_open($cmd, $descspec, $pipes);
1339 if (!is_resource($p)) {
1340 return false;
1343 fclose($pipes[0]);
1344 fclose($pipes[1]);
1346 return proc_close($p);
1350 * Obtain a list of terms a given user has not yet accepted.
1352 * @param int $uid The ID of the user to obtain terms for.
1354 * @return array A list of terms the user has not yet accepted.
1356 function fetch_updated_terms($uid) {
1357 $dbh = DB::connect();
1359 $q = "SELECT ID, Terms.Revision, Description, URL ";
1360 $q .= "FROM Terms LEFT JOIN AcceptedTerms ";
1361 $q .= "ON AcceptedTerms.TermsID = Terms.ID ";
1362 $q .= "AND AcceptedTerms.UsersID = " . intval($uid) . " ";
1363 $q .= "WHERE AcceptedTerms.Revision IS NULL OR ";
1364 $q .= "AcceptedTerms.Revision < Terms.Revision";
1366 $result = $dbh->query($q);
1368 if ($result) {
1369 return $result->fetchAll();
1370 } else {
1371 return array();
1376 * Accept a list of given terms.
1378 * @param int $uid The ID of the user to accept the terms.
1379 * @param array $termrev An array mapping each term to the accepted revision.
1381 * @return void
1383 function accept_terms($uid, $termrev) {
1384 $dbh = DB::connect();
1386 $q = "SELECT TermsID, Revision FROM AcceptedTerms ";
1387 $q .= "WHERE UsersID = " . intval($uid);
1389 $result = $dbh->query($q);
1391 if (!$result) {
1392 return;
1395 $termrev_update = array();
1396 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
1397 $id = $row['TermsID'];
1398 if (!array_key_exists($id, $termrev)) {
1399 continue;
1401 if ($row['Revision'] < $termrev[$id]) {
1402 $termrev_update[$id] = $termrev[$id];
1405 $termrev_add = array_diff_key($termrev, $termrev_update);
1407 foreach ($termrev_add as $id => $rev) {
1408 $q = "INSERT INTO AcceptedTerms (TermsID, UsersID, Revision) ";
1409 $q .= "VALUES (" . intval($id) . ", " . intval($uid) . ", ";
1410 $q .= intval($rev) . ")";
1411 $dbh->exec($q);
1414 foreach ($termrev_update as $id => $rev) {
1415 $q = "UPDATE AcceptedTerms ";
1416 $q .= "SET Revision = " . intval($rev) . " ";
1417 $q .= "WHERE TermsID = " . intval($id) . " AND ";
1418 $q .= "UsersID = " . intval($uid);
1419 $dbh->exec($q);
1423 function account_comments($uid, $limit, $offset=0) {
1424 $dbh = DB::connect();
1425 $q = "SELECT PackageComments.ID, Comments, UsersID, ";
1426 $q.= "PackageBaseId, CommentTS, DelTS, EditedTS, B.UserName AS EditUserName, ";
1427 $q.= "PinnedTS, ";
1428 $q.= "C.UserName as DelUserName, RenderedComment, ";
1429 $q.= "PB.ID as PackageBaseID, PB.Name as PackageBaseName ";
1430 $q.= "FROM PackageComments ";
1431 $q.= "LEFT JOIN PackageBases PB ON PackageComments.PackageBaseID = PB.ID ";
1432 $q.= "LEFT JOIN Users A ON PackageComments.UsersID = A.ID ";
1433 $q.= "LEFT JOIN Users B ON PackageComments.EditedUsersID = B.ID ";
1434 $q.= "LEFT JOIN Users C ON PackageComments.DelUsersID = C.ID ";
1435 $q.= "WHERE A.ID = " . $dbh->quote($uid) . " ";
1436 $q.= "ORDER BY CommentTS DESC";
1438 if ($limit > 0) {
1439 $q.=" LIMIT " . intval($limit);
1442 if ($offset > 0) {
1443 $q.=" OFFSET " . intval($offset);
1446 $result = $dbh->query($q);
1447 if (!$result) {
1448 return null;
1451 return $result->fetchAll();
1454 function account_comments_count($uid) {
1455 $dbh = DB::connect();
1456 $q = "SELECT COUNT(*) ";
1457 $q.= "FROM PackageComments ";
1458 $q.= "LEFT JOIN Users A ON PackageComments.UsersID = A.ID ";
1459 $q.= "WHERE A.ID = " . $dbh->quote($uid);
1461 $result = $dbh->query($q);
1462 return $result->fetchColumn();
1466 * Compute the list of active CAPTCHA salts. The salt changes based on the
1467 * number of registered users. This ensures that new users always use a
1468 * different salt and protects against hardcoding the CAPTCHA response.
1470 * The first CAPTCHA in the list is the most recent one and should be used for
1471 * new CAPTCHA challenges. The other ones are slightly outdated but may still
1472 * be valid for recent challenges that were created before the number of users
1473 * increased. The current implementation ensures that we can still use our
1474 * CAPTCHA salt, even if five new users registered since the CAPTCHA challenge
1475 * was created.
1477 * @return string The list of active salts, the first being the most recent
1478 * one.
1480 function get_captcha_salts() {
1481 $dbh = DB::connect();
1482 $q = "SELECT count(*) FROM Users";
1483 $result = $dbh->query($q);
1484 $user_count = $result->fetchColumn();
1486 $ret = array();
1487 for ($i = 0; $i <= 5; $i++) {
1488 array_push($ret, 'aurweb-' . ($user_count - $i));
1490 return $ret;
1494 * Return the CAPTCHA challenge for a given salt.
1496 * @param string $salt The salt to be used for the CAPTCHA computation.
1498 * @return string The challenge as a string.
1500 function get_captcha_challenge($salt) {
1501 $token = substr(md5($salt), 0, 3);
1502 return "LC_ALL=C pacman -V|sed -r 's#[0-9]+#" . $token . "#g'|md5sum|cut -c1-6";
1506 * Compute CAPTCHA answer for a given salt.
1508 * @param string $salt The salt to be used for the CAPTCHA computation.
1510 * @return string The correct answer as a string.
1512 function get_captcha_answer($salt) {
1513 $token = substr(md5($salt), 0, 3);
1514 $text = <<<EOD
1516 .--. Pacman v$token.$token.$token - libalpm v$token.$token.$token
1517 / _.-' .-. .-. .-. Copyright (C) $token-$token Pacman Development Team
1518 \ '-. '-' '-' '-' Copyright (C) $token-$token Judd Vinet
1519 '--'
1520 This program may be freely redistributed under
1521 the terms of the GNU General Public License.
1523 EOD;
1524 return substr(md5($text . "\n"), 0, 6);