Clear a user's active sessions following account suspension
[aur.git] / web / lib / acctfuncs.inc.php
blob002042d194c730a9762a614ffccf5ed41e57d71d
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 $UTYPE User type of the account accessing the form
46 * @param string $A Form to use, either UpdateAccount or NewAccount
47 * @param string $U The username to display
48 * @param string $T The account type of the displayed user
49 * @param string $S Whether the displayed user has a suspended account
50 * @param string $E The e-mail address of the displayed user
51 * @param string $P The password value of the displayed user
52 * @param string $C The confirmed password value of the displayed user
53 * @param string $R The real name of the displayed user
54 * @param string $L The language preference of the displayed user
55 * @param string $I The IRC nickname of the displayed user
56 * @param string $K The PGP key fingerprint of the displayed user
57 * @param string $UID The user ID of the displayed user
59 * @return void
61 function display_account_form($UTYPE,$A,$U="",$T="",$S="",
62 $E="",$P="",$C="",$R="",$L="",$I="",$K="",$UID=0) {
63 global $SUPPORTED_LANGS;
65 include("account_edit_form.php");
66 return;
67 } # function display_account_form()
69 /**
70 * Process information given to new/edit account form
72 * @global array $SUPPORTED_LANGS Languages that are supported by the AUR
73 * @param string $UTYPE The account type of the user modifying the account
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 $UID The user ID of the modified account
87 * @param \PDO $dbh An already established database connection
89 * @return string|void Return void if successful, otherwise return error
91 function process_account_form($UTYPE,$TYPE,$A,$U="",$T="",$S="",$E="",
92 $P="",$C="",$R="",$L="",$I="",$K="",$UID=0,$dbh=NULL) {
94 # error check and process request for a new/modified account
95 global $SUPPORTED_LANGS;
97 if (!$dbh) {
98 $dbh = db_connect();
101 if(isset($_COOKIE['AURSID'])) {
102 $editor_user = uid_from_sid($_COOKIE['AURSID'], $dbh);
104 else {
105 $editor_user = null;
108 $error = "";
109 if (empty($E) || empty($U)) {
110 $error = __("Missing a required field.");
113 if ($TYPE == "new") {
114 # they need password fields for this type of action
116 if (empty($P) || empty($C)) {
117 $error = __("Missing a required field.");
119 } else {
120 if (!$UID) {
121 $error = __("Missing User ID");
125 if (!$error && !valid_username($U) && !user_is_privileged($editor_user, $dbh))
126 $error = __("The username is invalid.") . "<ul>\n"
127 ."<li>" . __("It must be between %s and %s characters long",
128 USERNAME_MIN_LEN, USERNAME_MAX_LEN )
129 . "</li>"
130 . "<li>" . __("Start and end with a letter or number") . "</li>"
131 . "<li>" . __("Can contain only one period, underscore or hyphen.")
132 . "</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 $error = __("Your password must be at least %s characters.",PASSWD_MIN_LEN);
140 if (!$error && !valid_email($E)) {
141 $error = __("The email address is invalid.");
144 if (!$error && $K != '' && !valid_pgp_fingerprint($K)) {
145 $error = __("The PGP key fingerprint is invalid.");
148 if (($UTYPE == "User" && $T > 1) || ($UTYPE == "Trusted User" && $T > 2)) {
149 $error = __("Cannot increase account permissions.");
151 if (!$error && !array_key_exists($L, $SUPPORTED_LANGS)) {
152 $error = __("Language is not currently supported.");
154 if (!$error) {
155 # check to see if this username is available
156 # NOTE: a race condition exists here if we care...
158 $q = "SELECT COUNT(*) AS CNT FROM Users ";
159 $q.= "WHERE Username = " . $dbh->quote($U);
160 if ($TYPE == "edit") {
161 $q.= " AND ID != ".intval($UID);
163 $result = $dbh->query($q);
164 $row = $result->fetch(PDO::FETCH_NUM);
166 if ($row[0]) {
167 $error = __("The username, %s%s%s, is already in use.",
168 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
171 if (!$error) {
172 # check to see if this email address is available
173 # NOTE: a race condition exists here if we care...
175 $q = "SELECT COUNT(*) AS CNT FROM Users ";
176 $q.= "WHERE Email = " . $dbh->quote($E);
177 if ($TYPE == "edit") {
178 $q.= " AND ID != ".intval($UID);
180 $result = $dbh->query($q);
181 $row = $result->fetch(PDO::FETCH_NUM);
183 if ($row[0]) {
184 $error = __("The address, %s%s%s, is already in use.",
185 "<strong>", htmlspecialchars($E,ENT_QUOTES), "</strong>");
188 if ($error) {
189 print "<span class='error'>".$error."</span><br/>\n";
190 display_account_form($UTYPE, $A, $U, $T, $S, $E, "", "",
191 $R, $L, $I, $K, $UID);
192 } else {
193 if ($TYPE == "new") {
194 # no errors, go ahead and create the unprivileged user
195 $salt = generate_salt();
196 $P = salted_hash($P, $salt);
197 $U = $dbh->quote($U);
198 $E = $dbh->quote($E);
199 $P = $dbh->quote($P);
200 $salt = $dbh->quote($salt);
201 $R = $dbh->quote($R);
202 $L = $dbh->quote($L);
203 $I = $dbh->quote($I);
204 $K = $dbh->quote(str_replace(" ", "", $K));
205 $q = "INSERT INTO Users (AccountTypeID, Suspended, ";
206 $q.= "Username, Email, Passwd, Salt, RealName, ";
207 $q.= "LangPreference, IRCNick, PGPKey) VALUES (1, 0, ";
208 $q.= "$U, $E, $P, $salt, $R, $L, $I, $K)";
209 $result = $dbh->exec($q);
210 if (!$result) {
211 print __("Error trying to create account, %s%s%s.",
212 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
213 } else {
214 # account created/modified, tell them so.
216 print __("The account, %s%s%s, has been successfully created.",
217 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
218 print "<p>\n";
219 print __("Click on the Login link above to use your account.");
220 print "</p>\n";
223 } else {
224 # no errors, go ahead and modify the user account
226 $q = "UPDATE Users SET ";
227 $q.= "Username = " . $dbh->quote($U);
228 if ($T) {
229 $q.= ", AccountTypeID = ".intval($T);
231 if ($S) {
232 /* Ensure suspended users can't keep an active session */
233 delete_user_sessions($UID, $dbh);
234 $q.= ", Suspended = 1";
235 } else {
236 $q.= ", Suspended = 0";
238 $q.= ", Email = " . $dbh->quote($E);
239 if ($P) {
240 $salt = generate_salt();
241 $hash = salted_hash($P, $salt);
242 $q .= ", Passwd = '$hash', Salt = '$salt'";
244 $q.= ", RealName = " . $dbh->quote($R);
245 $q.= ", LangPreference = " . $dbh->quote($L);
246 $q.= ", IRCNick = " . $dbh->quote($I);
247 $q.= ", PGPKey = " . $dbh->quote(str_replace(" ", "", $K));
248 $q.= " WHERE ID = ".intval($UID);
249 $result = $dbh->exec($q);
250 if (!$result) {
251 print __("Error trying to modify account, %s%s%s.",
252 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
253 } else {
254 print __("The account, %s%s%s, has been successfully modified.",
255 "<strong>", htmlspecialchars($U,ENT_QUOTES), "</strong>");
259 return;
263 * Include the search accounts form
265 * @return void
267 function search_accounts_form() {
268 include("search_accounts_form.php");
269 return;
273 * Display the search results page
275 * @param string $UTYPE User type of the account accessing the form
276 * @param string $O The offset for the results page
277 * @param string $SB The column to sort the results page by
278 * @param string $U The username search criteria
279 * @param string $T The account type search criteria
280 * @param string $S Whether the account is suspended search criteria
281 * @param string $E The e-mail address search criteria
282 * @param string $R The real name search criteria
283 * @param string $I The IRC nickname search criteria
284 * @param string $K The PGP key fingerprint search criteria
285 * @param \PDO $dbh An already established database connection
287 * @return void
289 function search_results_page($UTYPE,$O=0,$SB="",$U="",$T="",
290 $S="",$E="",$R="",$I="",$K="",$dbh=NULL) {
292 $HITS_PER_PAGE = 50;
293 if ($O) {
294 $OFFSET = intval($O);
295 } else {
296 $OFFSET = 0;
298 if ($OFFSET < 0) {
299 $OFFSET = 0;
301 $search_vars = array();
303 if (!$dbh) {
304 $dbh = db_connect();
307 $q = "SELECT Users.*, AccountTypes.AccountType ";
308 $q.= "FROM Users, AccountTypes ";
309 $q.= "WHERE AccountTypes.ID = Users.AccountTypeID ";
310 if ($T == "u") {
311 $q.= "AND AccountTypes.ID = 1 ";
312 $search_vars[] = "T";
313 } elseif ($T == "t") {
314 $q.= "AND AccountTypes.ID = 2 ";
315 $search_vars[] = "T";
316 } elseif ($T == "d") {
317 $q.= "AND AccountTypes.ID = 3 ";
318 $search_vars[] = "T";
320 if ($S) {
321 $q.= "AND Users.Suspended = 1 ";
322 $search_vars[] = "S";
324 if ($U) {
325 $U = "%" . addcslashes($U, '%_') . "%";
326 $q.= "AND Username LIKE " . $dbh->quote($U) . " ";
327 $search_vars[] = "U";
329 if ($E) {
330 $E = "%" . addcslashes($E, '%_') . "%";
331 $q.= "AND Email LIKE " . $dbh->quote($E) . " ";
332 $search_vars[] = "E";
334 if ($R) {
335 $R = "%" . addcslashes($R, '%_') . "%";
336 $q.= "AND RealName LIKE " . $dbh->quote($R) . " ";
337 $search_vars[] = "R";
339 if ($I) {
340 $I = "%" . addcslashes($I, '%_') . "%";
341 $q.= "AND IRCNick LIKE " . $dbh->quote($I) . " ";
342 $search_vars[] = "I";
344 if ($K) {
345 $K = "%" . addcslashes(str_replace(" ", "", $K), '%_') . "%";
346 $q.= "AND PGPKey LIKE " . $dbh->quote($K) . " ";
347 $search_vars[] = "K";
349 switch ($SB) {
350 case 't':
351 $q.= "ORDER BY AccountTypeID, Username ";
352 break;
353 case 'r':
354 $q.= "ORDER BY RealName, AccountTypeID ";
355 break;
356 case 'i':
357 $q.= "ORDER BY IRCNick, AccountTypeID ";
358 break;
359 case 'v':
360 $q.= "ORDER BY LastVoted, Username ";
361 break;
362 default:
363 $q.= "ORDER BY Username, AccountTypeID ";
364 break;
366 $search_vars[] = "SB";
367 $q.= "LIMIT " . $HITS_PER_PAGE . " OFFSET " . $OFFSET;
369 if (!$dbh) {
370 $dbh = db_connect();
373 $result = $dbh->query($q);
375 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
376 $userinfo[] = $row;
379 include("account_search_results.php");
380 return;
384 * Attempt to login and generate a session
386 * @global int $MAX_SESSIONS_PER_USER Maximum sessions a single user may have open
387 * @global int $PERSISTENT_COOKIE_TIMEOUT Time until cookie expires
388 * @param \PDO $dbh An already established database connection
390 * @return array Session ID for user, error message if applicable
392 function try_login($dbh=NULL) {
393 global $MAX_SESSIONS_PER_USER, $PERSISTENT_COOKIE_TIMEOUT;
395 $login_error = "";
396 $new_sid = "";
397 $userID = null;
399 if ( isset($_REQUEST['user']) || isset($_REQUEST['passwd']) ) {
400 if (!$dbh) {
401 $dbh = db_connect();
403 $userID = valid_user($_REQUEST['user'], $dbh);
405 if ( user_suspended($userID, $dbh) ) {
406 $login_error = "Account Suspended.";
408 elseif ( $userID && isset($_REQUEST['passwd'])
409 && valid_passwd($userID, $_REQUEST['passwd'], $dbh) ) {
411 $logged_in = 0;
412 $num_tries = 0;
414 # Account looks good. Generate a SID and store it.
416 while (!$logged_in && $num_tries < 5) {
417 if ($MAX_SESSIONS_PER_USER) {
418 # Delete all user sessions except the
419 # last ($MAX_SESSIONS_PER_USER - 1).
420 $q = "DELETE s.* FROM Sessions s ";
421 $q.= "LEFT JOIN (SELECT SessionID FROM Sessions ";
422 $q.= "WHERE UsersId = " . $userID . " ";
423 $q.= "ORDER BY LastUpdateTS DESC ";
424 $q.= "LIMIT " . ($MAX_SESSIONS_PER_USER - 1) . ") q ";
425 $q.= "ON s.SessionID = q.SessionID ";
426 $q.= "WHERE s.UsersId = " . $userID . " ";
427 $q.= "AND q.SessionID IS NULL;";
428 $dbh->query($q);
431 $new_sid = new_sid();
432 $q = "INSERT INTO Sessions (UsersID, SessionID, LastUpdateTS)"
433 ." VALUES (" . $userID . ", '" . $new_sid . "', UNIX_TIMESTAMP())";
434 $result = $dbh->exec($q);
436 # Query will fail if $new_sid is not unique
437 if ($result) {
438 $logged_in = 1;
439 break;
442 $num_tries++;
445 if ($logged_in) {
446 $q = "UPDATE Users SET LastLogin = UNIX_TIMESTAMP() ";
447 $q.= "WHERE ID = '$userID'";
448 $dbh->exec($q);
450 # set our SID cookie
451 if (isset($_POST['remember_me']) &&
452 $_POST['remember_me'] == "on") {
453 # Set cookies for 30 days.
454 $cookie_time = time() + $PERSISTENT_COOKIE_TIMEOUT;
456 # Set session for 30 days.
457 $q = "UPDATE Sessions SET LastUpdateTS = $cookie_time ";
458 $q.= "WHERE SessionID = '$new_sid'";
459 $dbh->exec($q);
461 else
462 $cookie_time = 0;
464 setcookie("AURSID", $new_sid, $cookie_time, "/", null, !empty($_SERVER['HTTPS']), true);
465 header("Location: " . get_uri('/'));
466 $login_error = "";
469 else {
470 $login_error = "Error trying to generate session id.";
473 else {
474 $login_error = __("Bad username or password.");
477 return array('SID' => $new_sid, 'error' => $login_error);
481 * Validate a username against a collection of rules
483 * The username must be longer or equal to USERNAME_MIN_LEN. It must be shorter
484 * or equal to USERNAME_MAX_LEN. It must start and end with either a letter or
485 * a number. It can contain one period, hypen, or underscore. Returns boolean
486 * of whether name is valid.
488 * @param string $user Username to validate
490 * @return bool True if username meets criteria, otherwise false
492 function valid_username($user) {
493 if (!empty($user)) {
495 #Is username at not too short or too long?
496 if ( strlen($user) >= USERNAME_MIN_LEN &&
497 strlen($user) <= USERNAME_MAX_LEN ) {
499 $user = strtolower($user);
500 # Does username:
501 # start and end with a letter or number
502 # contain only letters and numbers,
503 # and at most has one dash, period, or underscore
504 if ( preg_match("/^[a-z0-9]+[.\-_]?[a-z0-9]+$/", $user) ) {
505 return true;
510 return false;
514 * Determine if a username exists in the database
516 * @param string $user Username to check in the database
517 * @param \PDO $dbh An already established database connection
519 * @return string|void Return user ID if in database, otherwise void
521 function valid_user($user, $dbh=NULL) {
522 /* if ( $user = valid_username($user) ) { */
524 if(!$dbh) {
525 $dbh = db_connect();
528 if ( $user ) {
529 $q = "SELECT ID FROM Users ";
530 $q.= "WHERE Username = " . $dbh->quote($user);
532 $result = $dbh->query($q);
533 # Is the username in the database?
534 if ($result) {
535 $row = $result->fetch(PDO::FETCH_NUM);
536 return $row[0];
539 return;
543 * Determine if a user already has a proposal open about themselves
545 * @param string $user Username to checkout for open proposal
546 * @param \PDO $dbh An already established database connection
548 * @return bool True if there is an open proposal about the user, otherwise false
550 function open_user_proposals($user, $dbh=NULL) {
551 if(!$dbh) {
552 $dbh = db_connect();
554 $q = "SELECT * FROM TU_VoteInfo WHERE User = " . $dbh->quote($user) . " ";
555 $q.= "AND End > UNIX_TIMESTAMP()";
556 $result = $dbh->query($q);
557 if ($result->fetchColumn()) {
558 return true;
560 else {
561 return false;
566 * Add a new Trusted User proposal to the database
568 * @param string $agenda The agenda of the vote
569 * @param string $user The use the vote is about
570 * @param int $votelength The length of time for the vote to last
571 * @param string $submitteruid The user ID of the individual who submitted the proposal
572 * @param \PDO $dbh An already established database connection
574 * @return void
576 function add_tu_proposal($agenda, $user, $votelength, $submitteruid, $dbh=NULL) {
577 if(!$dbh) {
578 $dbh = db_connect();
581 $q = "INSERT INTO TU_VoteInfo (Agenda, User, Submitted, End, SubmitterID) VALUES ";
582 $q.= "(" . $dbh->quote($agenda) . ", " . $dbh->quote($user) . ", ";
583 $q.= "UNIX_TIMESTAMP(), UNIX_TIMESTAMP() + " . $dbh->quote($votelength);
584 $q.= ", " . $submitteruid . ")";
585 $result = $dbh->exec($q);
589 * Add a reset key to the database for a specified user
591 * @param string $resetkey A password reset key to be stored in database
592 * @param string $uid The user ID to store the reset key for
593 * @param \PDO $dbh An already established database connection
595 * @return void
597 function create_resetkey($resetkey, $uid, $dbh=NULL) {
598 if(!$dbh) {
599 $dbh = db_connect();
601 $q = "UPDATE Users ";
602 $q.= "SET ResetKey = '" . $resetkey . "' ";
603 $q.= "WHERE ID = " . $uid;
604 $dbh->exec($q);
608 * Change a user's password in the database if reset key and e-mail are correct
610 * @param string $hash New MD5 hash of a user's password
611 * @param string $salt New salt for the user's password
612 * @param string $resetkey Code e-mailed to a user to reset a password
613 * @param string $email E-mail address of the user resetting their password
614 * @param \PDO $dbh An already established database connection
616 * @return string|void Redirect page if successful, otherwise return error message
618 function password_reset($hash, $salt, $resetkey, $email, $dbh=NULL) {
619 if(!$dbh) {
620 $dbh = db_connect();
622 $q = "UPDATE Users ";
623 $q.= "SET Passwd = '$hash', ";
624 $q.= "Salt = '$salt', ";
625 $q.= "ResetKey = '' ";
626 $q.= "WHERE ResetKey != '' ";
627 $q.= "AND ResetKey = " . $dbh->quote($resetkey) . " ";
628 $q.= "AND Email = " . $dbh->quote($email);
629 $result = $dbh->exec($q);
631 if (!$result) {
632 $error = __('Invalid e-mail and reset key combination.');
633 return $error;
634 } else {
635 header('Location: ' . get_uri('/passreset/') . '?step=complete');
636 exit();
641 * Determine if the password is longer than the minimum length
643 * @param string $passwd The password to check
645 * @return bool True if longer than minimum length, otherwise false
647 function good_passwd($passwd) {
648 if ( strlen($passwd) >= PASSWD_MIN_LEN ) {
649 return true;
651 return false;
655 * Determine if the password is correct and salt it if it hasn't been already
657 * @param string $userID The user ID to check the password against
658 * @param string $passwd The password the visitor sent
659 * @param \PDO $dbh An already established database connection
661 * @return bool True if password was correct and properly salted, otherwise false
663 function valid_passwd($userID, $passwd, $dbh=NULL) {
664 if (!$dbh) {
665 $dbh = db_connect();
667 if ( strlen($passwd) > 0 ) {
668 # get salt for this user
669 $salt = get_salt($userID);
670 if ($salt) {
671 # use salt
672 $q = "SELECT ID FROM Users ";
673 $q.= "WHERE ID = " . $userID . " ";
674 $q.= "AND Passwd = " . $dbh->quote(salted_hash($passwd, $salt));
675 $result = $dbh->query($q);
676 if ($result) {
677 $row = $result->fetch(PDO::FETCH_NUM);
678 if ($row[0]) {
679 return true;
682 } else {
683 # check without salt
684 $q = "SELECT ID FROM Users ";
685 $q.= "WHERE ID = " . $userID . " ";
686 $q.= "AND Passwd = " . $dbh->quote(md5($passwd));
687 $result = $dbh->query($q);
688 if ($result) {
689 $row = $result->fetch(PDO::FETCH_NUM);
690 if ($row[0]) {
691 # password correct, but salt it first
692 if (!save_salt($userID, $passwd)) {
693 trigger_error("Unable to salt user's password;" .
694 " ID " . $userID, E_USER_WARNING);
695 return false;
697 return true;
702 return false;
706 * Determine if the PGP key fingerprint is valid (must be 40 hexadecimal digits)
708 * @param string $fingerprint PGP fingerprint to check if valid
710 * @return bool True if the fingerprint is 40 hexadecimal digits, otherwise false
712 function valid_pgp_fingerprint($fingerprint) {
713 $fingerprint = str_replace(" ", "", $fingerprint);
714 return (strlen($fingerprint) == 40 && ctype_xdigit($fingerprint));
718 * Determine if the user account has been suspended
720 * @param string $id The ID of user to check if suspended
721 * @param \PDO $dbh An already established database connection
723 * @return bool True if the user is suspended, otherwise false
725 function user_suspended($id, $dbh=NULL) {
726 if (!$dbh) {
727 $dbh = db_connect();
729 if (!$id) {
730 return false;
732 $q = "SELECT Suspended FROM Users WHERE ID = " . $id;
733 $result = $dbh->query($q);
734 if ($result) {
735 $row = $result->fetch(PDO::FETCH_NUM);
736 if ($row[0]) {
737 return true;
740 return false;
744 * Delete a specified user account from the database
746 * @param int $id The user ID of the account to be deleted
747 * @param \PDO $dbh An already established database connection
749 * @return void
751 function user_delete($id, $dbh=NULL) {
752 if (!$dbh) {
753 $dbh = db_connect();
755 $q = "DELETE FROM Users WHERE ID = " . $id;
756 $dbh->query($q);
757 return;
761 * Determine if a user is either a Trusted User or Developer
763 * @param string $id The ID of the user to check if privileged
764 * @param \PDO $dbh An already established database connection
766 * @return int|string Return 0 if un-privileged, "2" if Trusted User, "3" if Developer
768 function user_is_privileged($id, $dbh=NULL) {
769 if (!$dbh) {
770 $dbh = db_connect();
772 $q = "SELECT AccountTypeID FROM Users WHERE ID = " . $id;
773 $result = $dbh->query($q);
774 if ($result) {
775 $row = $result->fetch(PDO::FETCH_NUM);
776 if($row[0] > 1) {
777 return $row[0];
780 return 0;
785 * Remove the session from the database on logout
787 * @param string $sid User's session ID
788 * @param \PDO $dbh An already established database connection
790 * @return void
792 function delete_session_id($sid, $dbh=NULL) {
793 if(!$dbh) {
794 $dbh = db_connect();
797 $q = "DELETE FROM Sessions WHERE SessionID = " . $dbh->quote($sid);
798 $dbh->query($q);
802 * Remove all sessions belonging to a particular user
804 * @param int $uid ID of user to remove all sessions for
805 * @param \PDO $dbh An already established database connection
807 * @return void
809 function delete_user_sessions($uid, $dbh=NULL) {
810 if (!$dbh) {
811 $dbh = db_connect();
814 $q = "DELETE FROM Sessions WHERE UsersID = " . intval($uid);
815 $dbh->exec($q);
819 * Remove sessions from the database that have exceed the timeout
821 * @global int $LOGIN_TIMEOUT Time until session expires
822 * @param \PDO $dbh An already established database connection
824 * @return void
826 function clear_expired_sessions($dbh=NULL) {
827 global $LOGIN_TIMEOUT;
829 if(!$dbh) {
830 $dbh = db_connect();
833 $q = "DELETE FROM Sessions WHERE LastUpdateTS < (UNIX_TIMESTAMP() - $LOGIN_TIMEOUT)";
834 $dbh->query($q);
836 return;
840 * Get account details for a specific user
842 * @param string $uid The User ID of account to get information for
843 * @param string $username The username of the account to get for
844 * @param \PDO $dbh An already established database connection
846 * @return array Account details for the specified user
848 function account_details($uid, $username, $dbh=NULL) {
849 if(!$dbh) {
850 $dbh = db_connect();
852 $q = "SELECT Users.*, AccountTypes.AccountType ";
853 $q.= "FROM Users, AccountTypes ";
854 $q.= "WHERE AccountTypes.ID = Users.AccountTypeID ";
855 if (!empty($uid)) {
856 $q.= "AND Users.ID = ".intval($uid);
857 } else {
858 $q.= "AND Users.Username = " . $dbh->quote($username);
860 $result = $dbh->query($q);
862 if ($result) {
863 $row = $result->fetch(PDO::FETCH_ASSOC);
866 return $row;
870 * Determine if a user has already voted on a specific proposal
872 * @param string $voteid The ID of the Trusted User proposal
873 * @param string $uid The ID to check if the user already voted
874 * @param \PDO $dbh An already established database connection
876 * @return bool True if the user has already voted, otherwise false
878 function tu_voted($voteid, $uid, $dbh=NULL) {
879 if (!$dbh) {
880 $dbh = db_connect();
883 $q = "SELECT COUNT(*) FROM TU_Votes ";
884 $q.= "WHERE VoteID = " . intval($voteid) . " AND UserID = " . intval($uid);
885 $result = $dbh->query($q);
886 if ($result->fetchColumn() > 0) {
887 return true;
889 else {
890 return false;
895 * Get all current Trusted User proposals from the database
897 * @param string $order Ascending or descending order for the proposal listing
898 * @param \PDO $dbh An already established database connection
900 * @return array The details for all current Trusted User proposals
902 function current_proposal_list($order, $dbh=NULL) {
903 if (!$dbh) {
904 $dbh = db_connect();
907 $q = "SELECT * FROM TU_VoteInfo WHERE End > " . time() . " ORDER BY Submitted " . $order;
908 $result = $dbh->query($q);
910 $details = array();
911 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
912 $details[] = $row;
915 return $details;
919 * Get a subset of all past Trusted User proposals from the database
921 * @param string $order Ascending or descending order for the proposal listing
922 * @param string $lim The number of proposals to list with the offset
923 * @param \PDO $dbh An already established database connection
925 * @return array The details for the subset of past Trusted User proposals
927 function past_proposal_list($order, $lim, $dbh=NULL) {
928 if (!$dbh) {
929 $dbh = db_connect();
932 $q = "SELECT * FROM TU_VoteInfo WHERE End < " . time() . " ORDER BY Submitted " . $order . $lim;
933 $result = $dbh->query($q);
935 $details = array();
936 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
937 $details[] = $row;
940 return $details;
944 * Determine the total number of Trusted User proposals
946 * @param \PDO $dbh An already established database connection
948 * @return string The total number of Trusted User proposals
950 function proposal_count($dbh=NULL) {
951 if (!$dbh) {
952 $dbh = db_connect();
955 $q = "SELECT COUNT(*) FROM TU_VoteInfo";
956 $result = $dbh->query($q);
957 $row = $result->fetch(PDO::FETCH_NUM);
959 return $row[0];
963 * Get all details related to a specific vote from the database
965 * @param string $voteid The ID of the Trusted User proposal
966 * @param \PDO $dbh An already established database connection
968 * @return array All stored details for a specific vote
970 function vote_details($voteid, $dbh=NULL) {
971 if (!$dbh) {
972 $dbh = db_connect();
975 $q = "SELECT * FROM TU_VoteInfo ";
976 $q.= "WHERE ID = " . intval($voteid);
978 $result = $dbh->query($q);
979 $row = $result->fetch(PDO::FETCH_ASSOC);
981 return $row;
985 * Get an alphabetical list of users who voted for a proposal with HTML links
987 * @param string $voteid The ID of the Trusted User proposal
988 * @param \PDO $dbh An already established database connection
990 * @return array All users who voted for a specific proposal
992 function voter_list($voteid, $dbh=NULL) {
993 if (!$dbh) {
994 $dbh = db_connect();
997 $whovoted = array();
999 $q = "SELECT tv.UserID,U.Username ";
1000 $q.= "FROM TU_Votes tv, Users U ";
1001 $q.= "WHERE tv.VoteID = " . intval($voteid);
1002 $q.= " AND tv.UserID = U.ID ";
1003 $q.= "ORDER BY Username";
1005 $result = $dbh->query($q);
1006 if ($result) {
1007 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
1008 $whovoted[] = $row['Username'];
1011 return $whovoted;
1015 * Cast a vote for a specific user proposal
1017 * @param string $voteid The ID of the proposal being voted on
1018 * @param string $uid The user ID of the individual voting
1019 * @param string $vote Vote position, either "Yes", "No", or "Abstain"
1020 * @param int $newtotal The total number of votes after the user has voted
1021 * @param \PDO $dbh An already established database connection
1023 * @return void
1025 function cast_proposal_vote($voteid, $uid, $vote, $newtotal, $dbh=NULL) {
1026 if (!$dbh) {
1027 $dbh = db_connect();
1030 $q = "UPDATE TU_VoteInfo SET " . $vote . " = (" . $newtotal . ") WHERE ID = " . $voteid;
1031 $result = $dbh->exec($q);
1033 $q = "INSERT INTO TU_Votes (VoteID, UserID) VALUES (" . intval($voteid) . ", " . intval($uid) . ")";
1034 $result = $dbh->exec($q);
1038 * Verify a user has the proper permissions to edit an account
1040 * @param string $atype Account type of the editing user
1041 * @param array $acctinfo User account information for edited account
1042 * @param int $uid User ID of the editing user
1044 * @return bool True if permission to edit the account, otherwise false
1046 function can_edit_account($atype, $acctinfo, $uid) {
1047 /* Developers can edit any account */
1048 if ($atype == 'Developer') {
1049 return true;
1052 /* Trusted Users can edit all accounts except Developer accounts */
1053 if ($atype == 'Trusted User' &&
1054 $acctinfo['AccountType'] != 'Developer') {
1055 return true;
1058 /* Users can edit only their own account */
1059 if ($acctinfo['ID'] == $uid) {
1060 return true;
1063 return false;