acctfuncs.inc.php: Document all functions using PHPDoc format
[aur.git] / web / lib / acctfuncs.inc.php
blob44cbfbd81ae763e3eab9d9fc1488c580c2ac41a2
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 == "Trusted User" && $T == 3) {
149 $error = __("A Trusted User cannot assign Developer status.");
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 "<b>", htmlspecialchars($U,ENT_QUOTES), "</b>");
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 "<b>", htmlspecialchars($E,ENT_QUOTES), "</b>");
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 "<b>", htmlspecialchars($U,ENT_QUOTES), "</b>");
213 } else {
214 # account created/modified, tell them so.
216 print __("The account, %s%s%s, has been successfully created.",
217 "<b>", htmlspecialchars($U,ENT_QUOTES), "</b>");
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 $q.= ", Suspended = 1";
233 } else {
234 $q.= ", Suspended = 0";
236 $q.= ", Email = " . $dbh->quote($E);
237 if ($P) {
238 $salt = generate_salt();
239 $hash = salted_hash($P, $salt);
240 $q .= ", Passwd = '$hash', Salt = '$salt'";
242 $q.= ", RealName = " . $dbh->quote($R);
243 $q.= ", LangPreference = " . $dbh->quote($L);
244 $q.= ", IRCNick = " . $dbh->quote($I);
245 $q.= ", PGPKey = " . $dbh->quote(str_replace(" ", "", $K));
246 $q.= " WHERE ID = ".intval($UID);
247 $result = $dbh->exec($q);
248 if (!$result) {
249 print __("Error trying to modify account, %s%s%s.",
250 "<b>", htmlspecialchars($U,ENT_QUOTES), "</b>");
251 } else {
252 print __("The account, %s%s%s, has been successfully modified.",
253 "<b>", htmlspecialchars($U,ENT_QUOTES), "</b>");
257 return;
261 * Include the search accounts form
263 * @return void
265 function search_accounts_form() {
266 include("search_accounts_form.php");
267 return;
271 * Display the search results page
273 * @param string $UTYPE User type of the account accessing the form
274 * @param string $O The offset for the results page
275 * @param string $SB The column to sort the results page by
276 * @param string $U The username search criteria
277 * @param string $T The account type search criteria
278 * @param string $S Whether the account is suspended search criteria
279 * @param string $E The e-mail address search criteria
280 * @param string $R The real name search criteria
281 * @param string $I The IRC nickname search criteria
282 * @param string $K The PGP key fingerprint search criteria
283 * @param \PDO $dbh An already established database connection
285 * @return void
287 function search_results_page($UTYPE,$O=0,$SB="",$U="",$T="",
288 $S="",$E="",$R="",$I="",$K="",$dbh=NULL) {
290 $HITS_PER_PAGE = 50;
291 if ($O) {
292 $OFFSET = intval($O);
293 } else {
294 $OFFSET = 0;
296 if ($OFFSET < 0) {
297 $OFFSET = 0;
299 $search_vars = array();
301 if (!$dbh) {
302 $dbh = db_connect();
305 $q = "SELECT Users.*, AccountTypes.AccountType ";
306 $q.= "FROM Users, AccountTypes ";
307 $q.= "WHERE AccountTypes.ID = Users.AccountTypeID ";
308 if ($T == "u") {
309 $q.= "AND AccountTypes.ID = 1 ";
310 $search_vars[] = "T";
311 } elseif ($T == "t") {
312 $q.= "AND AccountTypes.ID = 2 ";
313 $search_vars[] = "T";
314 } elseif ($T == "d") {
315 $q.= "AND AccountTypes.ID = 3 ";
316 $search_vars[] = "T";
318 if ($S) {
319 $q.= "AND Users.Suspended = 1 ";
320 $search_vars[] = "S";
322 if ($U) {
323 $U = "%" . addcslashes($U, '%_') . "%";
324 $q.= "AND Username LIKE " . $dbh->quote($U) . " ";
325 $search_vars[] = "U";
327 if ($E) {
328 $E = "%" . addcslashes($E, '%_') . "%";
329 $q.= "AND Email LIKE " . $dbh->quote($E) . " ";
330 $search_vars[] = "E";
332 if ($R) {
333 $R = "%" . addcslashes($R, '%_') . "%";
334 $q.= "AND RealName LIKE " . $dbh->quote($R) . " ";
335 $search_vars[] = "R";
337 if ($I) {
338 $I = "%" . addcslashes($I, '%_') . "%";
339 $q.= "AND IRCNick LIKE " . $dbh->quote($I) . " ";
340 $search_vars[] = "I";
342 if ($K) {
343 $K = "%" . addcslashes(str_replace(" ", "", $K), '%_') . "%";
344 $q.= "AND PGPKey LIKE " . $dbh->quote($K) . " ";
345 $search_vars[] = "K";
347 switch ($SB) {
348 case 't':
349 $q.= "ORDER BY AccountTypeID, Username ";
350 break;
351 case 'r':
352 $q.= "ORDER BY RealName, AccountTypeID ";
353 break;
354 case 'i':
355 $q.= "ORDER BY IRCNick, AccountTypeID ";
356 break;
357 case 'v':
358 $q.= "ORDER BY LastVoted, Username ";
359 break;
360 default:
361 $q.= "ORDER BY Username, AccountTypeID ";
362 break;
364 $search_vars[] = "SB";
365 $q.= "LIMIT " . $HITS_PER_PAGE . " OFFSET " . $OFFSET;
367 if (!$dbh) {
368 $dbh = db_connect();
371 $result = $dbh->query($q);
373 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
374 $userinfo[] = $row;
377 include("account_search_results.php");
378 return;
382 * Attempt to login and generate a session
384 * @global int $MAX_SESSIONS_PER_USER Maximum sessions a single user may have open
385 * @global int $PERSISTENT_COOKIE_TIMEOUT Time until cookie expires
386 * @param \PDO $dbh An already established database connection
388 * @return array Session ID for user, error message if applicable
390 function try_login($dbh=NULL) {
391 global $MAX_SESSIONS_PER_USER, $PERSISTENT_COOKIE_TIMEOUT;
393 $login_error = "";
394 $new_sid = "";
395 $userID = null;
397 if ( isset($_REQUEST['user']) || isset($_REQUEST['passwd']) ) {
398 if (!$dbh) {
399 $dbh = db_connect();
401 $userID = valid_user($_REQUEST['user'], $dbh);
403 if ( user_suspended($userID, $dbh) ) {
404 $login_error = "Account Suspended.";
406 elseif ( $userID && isset($_REQUEST['passwd'])
407 && valid_passwd($userID, $_REQUEST['passwd'], $dbh) ) {
409 $logged_in = 0;
410 $num_tries = 0;
412 # Account looks good. Generate a SID and store it.
414 while (!$logged_in && $num_tries < 5) {
415 if ($MAX_SESSIONS_PER_USER) {
416 # Delete all user sessions except the
417 # last ($MAX_SESSIONS_PER_USER - 1).
418 $q = "DELETE s.* FROM Sessions s ";
419 $q.= "LEFT JOIN (SELECT SessionID FROM Sessions ";
420 $q.= "WHERE UsersId = " . $userID . " ";
421 $q.= "ORDER BY LastUpdateTS DESC ";
422 $q.= "LIMIT " . ($MAX_SESSIONS_PER_USER - 1) . ") q ";
423 $q.= "ON s.SessionID = q.SessionID ";
424 $q.= "WHERE s.UsersId = " . $userID . " ";
425 $q.= "AND q.SessionID IS NULL;";
426 $dbh->query($q);
429 $new_sid = new_sid();
430 $q = "INSERT INTO Sessions (UsersID, SessionID, LastUpdateTS)"
431 ." VALUES (" . $userID . ", '" . $new_sid . "', UNIX_TIMESTAMP())";
432 $result = $dbh->exec($q);
434 # Query will fail if $new_sid is not unique
435 if ($result) {
436 $logged_in = 1;
437 break;
440 $num_tries++;
443 if ($logged_in) {
444 $q = "UPDATE Users SET LastLogin = UNIX_TIMESTAMP() ";
445 $q.= "WHERE ID = '$userID'";
446 $dbh->exec($q);
448 # set our SID cookie
449 if (isset($_POST['remember_me']) &&
450 $_POST['remember_me'] == "on") {
451 # Set cookies for 30 days.
452 $cookie_time = time() + $PERSISTENT_COOKIE_TIMEOUT;
454 # Set session for 30 days.
455 $q = "UPDATE Sessions SET LastUpdateTS = $cookie_time ";
456 $q.= "WHERE SessionID = '$new_sid'";
457 $dbh->exec($q);
459 else
460 $cookie_time = 0;
462 setcookie("AURSID", $new_sid, $cookie_time, "/", null, !empty($_SERVER['HTTPS']), true);
463 header("Location: " . get_uri('/'));
464 $login_error = "";
467 else {
468 $login_error = "Error trying to generate session id.";
471 else {
472 $login_error = __("Bad username or password.");
475 return array('SID' => $new_sid, 'error' => $login_error);
479 * Validate a username against a collection of rules
481 * The username must be longer or equal to USERNAME_MIN_LEN. It must be shorter
482 * or equal to USERNAME_MAX_LEN. It must start and end with either a letter or
483 * a number. It can contain one period, hypen, or underscore. Returns username
484 * if it meets all of those rules.
486 * @param string $user Username to validate
488 * @return string|void Return username if it meets criteria, otherwise void
490 function valid_username($user) {
491 if (!empty($user)) {
493 #Is username at not too short or too long?
494 if ( strlen($user) >= USERNAME_MIN_LEN &&
495 strlen($user) <= USERNAME_MAX_LEN ) {
497 $user = strtolower($user);
498 # Does username:
499 # start and end with a letter or number
500 # contain only letters and numbers,
501 # and at most has one dash, period, or underscore
502 if ( preg_match("/^[a-z0-9]+[.\-_]?[a-z0-9]+$/", $user) ) {
503 #All is good return the username
504 return $user;
509 return;
513 * Determine if a username exists in the database
515 * @param string $user Username to check in the database
516 * @param \PDO $dbh An already established database connection
518 * @return string|void Return user ID if in database, otherwise void
520 function valid_user($user, $dbh=NULL) {
521 /* if ( $user = valid_username($user) ) { */
523 if(!$dbh) {
524 $dbh = db_connect();
527 if ( $user ) {
528 $q = "SELECT ID FROM Users ";
529 $q.= "WHERE Username = " . $dbh->quote($user);
531 $result = $dbh->query($q);
532 # Is the username in the database?
533 if ($result) {
534 $row = $result->fetch(PDO::FETCH_NUM);
535 return $row[0];
538 return;
542 * Determine if a user already has a proposal open about themselves
544 * @param string $user Username to checkout for open proposal
545 * @param \PDO $dbh An already established database connection
547 * @return bool True if there is an open proposal about the user, otherwise false
549 function open_user_proposals($user, $dbh=NULL) {
550 if(!$dbh) {
551 $dbh = db_connect();
553 $q = "SELECT * FROM TU_VoteInfo WHERE User = " . $dbh->quote($user) . " ";
554 $q.= "AND End > UNIX_TIMESTAMP()";
555 $result = $dbh->query($q);
556 if ($result->fetchColumn()) {
557 return true;
559 else {
560 return false;
565 * Add a new Trusted User proposal to the database
567 * @param string $agenda The agenda of the vote
568 * @param string $user The use the vote is about
569 * @param int $votelength The length of time for the vote to last
570 * @param string $submitteruid The user ID of the individual who submitted the proposal
571 * @param \PDO $dbh An already established database connection
573 * @return void
575 function add_tu_proposal($agenda, $user, $votelength, $submitteruid, $dbh=NULL) {
576 if(!$dbh) {
577 $dbh = db_connect();
580 $q = "INSERT INTO TU_VoteInfo (Agenda, User, Submitted, End, SubmitterID) VALUES ";
581 $q.= "(" . $dbh->quote($agenda) . ", " . $dbh->quote($user) . ", ";
582 $q.= "UNIX_TIMESTAMP(), UNIX_TIMESTAMP() + " . $dbh->quote($votelength);
583 $q.= ", " . $submitteruid . ")";
584 $result = $dbh->exec($q);
588 * Add a reset key to the database for a specified user
590 * @param string $resetkey A password reset key to be stored in database
591 * @param string $uid The user ID to store the reset key for
592 * @param \PDO $dbh An already established database connection
594 * @return void
596 function create_resetkey($resetkey, $uid, $dbh=NULL) {
597 if(!$dbh) {
598 $dbh = db_connect();
600 $q = "UPDATE Users ";
601 $q.= "SET ResetKey = '" . $resetkey . "' ";
602 $q.= "WHERE ID = " . $uid;
603 $dbh->exec($q);
607 * Change a user's password in the database if reset key and e-mail are correct
609 * @param string $hash New MD5 hash of a user's password
610 * @param string $salt New salt for the user's password
611 * @param string $resetkey Code e-mailed to a user to reset a password
612 * @param string $email E-mail address of the user resetting their password
613 * @param \PDO $dbh An already established database connection
615 * @return string|void Redirect page if successful, otherwise return error message
617 function password_reset($hash, $salt, $resetkey, $email, $dbh=NULL) {
618 if(!$dbh) {
619 $dbh = db_connect();
621 $q = "UPDATE Users ";
622 $q.= "SET Passwd = '$hash', ";
623 $q.= "Salt = '$salt', ";
624 $q.= "ResetKey = '' ";
625 $q.= "WHERE ResetKey != '' ";
626 $q.= "AND ResetKey = " . $dbh->quote($resetkey) . " ";
627 $q.= "AND Email = " . $dbh->quote($email);
628 $result = $dbh->exec($q);
630 if (!$result) {
631 $error = __('Invalid e-mail and reset key combination.');
632 return $error;
633 } else {
634 header('Location: ' . get_uri('/passreset/') . '?step=complete');
635 exit();
640 * Determine if the password is longer than the minimum length
642 * @param string $passwd The password to check
644 * @return bool True if longer than minimum length, otherwise false
646 function good_passwd($passwd) {
647 if ( strlen($passwd) >= PASSWD_MIN_LEN ) {
648 return true;
650 return false;
654 * Determine if the password is correct and salt it if it hasn't been already
656 * @param string $userID The user ID to check the password against
657 * @param string $passwd The password the visitor sent
658 * @param \PDO $dbh An already established database connection
660 * @return bool True if password was correct and properly salted, otherwise false
662 function valid_passwd($userID, $passwd, $dbh=NULL) {
663 if (!$dbh) {
664 $dbh = db_connect();
666 if ( strlen($passwd) > 0 ) {
667 # get salt for this user
668 $salt = get_salt($userID);
669 if ($salt) {
670 # use salt
671 $q = "SELECT ID FROM Users ";
672 $q.= "WHERE ID = " . $userID . " ";
673 $q.= "AND Passwd = " . $dbh->quote(salted_hash($passwd, $salt));
674 $result = $dbh->query($q);
675 if ($result) {
676 $row = $result->fetch(PDO::FETCH_NUM);
677 if ($row[0]) {
678 return true;
681 } else {
682 # check without salt
683 $q = "SELECT ID FROM Users ";
684 $q.= "WHERE ID = " . $userID . " ";
685 $q.= "AND Passwd = " . $dbh->quote(md5($passwd));
686 $result = $dbh->query($q);
687 if ($result) {
688 $row = $result->fetch(PDO::FETCH_NUM);
689 if ($row[0]) {
690 # password correct, but salt it first
691 if (!save_salt($userID, $passwd)) {
692 trigger_error("Unable to salt user's password;" .
693 " ID " . $userID, E_USER_WARNING);
694 return false;
696 return true;
701 return false;
705 * Determine if the PGP key fingerprint is valid (must be 40 hexadecimal digits)
707 * @param string $fingerprint PGP fingerprint to check if valid
709 * @return bool True if the fingerprint is 40 hexadecimal digits, otherwise false
711 function valid_pgp_fingerprint($fingerprint) {
712 $fingerprint = str_replace(" ", "", $fingerprint);
713 return (strlen($fingerprint) == 40 && ctype_xdigit($fingerprint));
717 * Determine if the user account has been suspended
719 * @param string $id The ID of user to check if suspended
720 * @param \PDO $dbh An already established database connection
722 * @return bool True if the user is suspended, otherwise false
724 function user_suspended($id, $dbh=NULL) {
725 if (!$dbh) {
726 $dbh = db_connect();
728 if (!$id) {
729 return false;
731 $q = "SELECT Suspended FROM Users WHERE ID = " . $id;
732 $result = $dbh->query($q);
733 if ($result) {
734 $row = $result->fetch(PDO::FETCH_NUM);
735 if ($row[0]) {
736 return true;
739 return false;
743 * Delete a specified user account from the database
745 * @param int $id The user ID of the account to be deleted
746 * @param \PDO $dbh An already established database connection
748 * @return void
750 function user_delete($id, $dbh=NULL) {
751 if (!$dbh) {
752 $dbh = db_connect();
754 $q = "DELETE FROM Users WHERE ID = " . $id;
755 $dbh->query($q);
756 return;
760 * Determine if a user is either a Trusted User or Developer
762 * @param string $id The ID of the user to check if privileged
763 * @param \PDO $dbh An already established database connection
765 * @return int|string Return 0 if un-privileged, "2" if Trusted User, "3" if Developer
767 function user_is_privileged($id, $dbh=NULL) {
768 if (!$dbh) {
769 $dbh = db_connect();
771 $q = "SELECT AccountTypeID FROM Users WHERE ID = " . $id;
772 $result = $dbh->query($q);
773 if ($result) {
774 $row = $result->fetch(PDO::FETCH_NUM);
775 if($row[0] > 1) {
776 return $row[0];
779 return 0;
784 * Remove the session from the database on logout
786 * @param string $sid User's session ID
787 * @param \PDO $dbh An already established database connection
789 * @return void
791 function delete_session_id($sid, $dbh=NULL) {
792 if(!$dbh) {
793 $dbh = db_connect();
796 $q = "DELETE FROM Sessions WHERE SessionID = " . $dbh->quote($sid);
797 $dbh->query($q);
801 * Remove sessions from the database that have exceed the timeout
803 * @global int $LOGIN_TIMEOUT Time until session expires
804 * @param \PDO $dbh An already established database connection
806 * @return void
808 function clear_expired_sessions($dbh=NULL) {
809 global $LOGIN_TIMEOUT;
811 if(!$dbh) {
812 $dbh = db_connect();
815 $q = "DELETE FROM Sessions WHERE LastUpdateTS < (UNIX_TIMESTAMP() - $LOGIN_TIMEOUT)";
816 $dbh->query($q);
818 return;
822 * Get account details for a specific user
824 * @param string $uid The User ID of account to get information for
825 * @param string $username The username of the account to get for
826 * @param \PDO $dbh An already established database connection
828 * @return array Account details for the specified user
830 function account_details($uid, $username, $dbh=NULL) {
831 if(!$dbh) {
832 $dbh = db_connect();
834 $q = "SELECT Users.*, AccountTypes.AccountType ";
835 $q.= "FROM Users, AccountTypes ";
836 $q.= "WHERE AccountTypes.ID = Users.AccountTypeID ";
837 if (!empty($uid)) {
838 $q.= "AND Users.ID = ".intval($uid);
839 } else {
840 $q.= "AND Users.Username = " . $dbh->quote($username);
842 $result = $dbh->query($q);
844 if ($result) {
845 $row = $result->fetch(PDO::FETCH_ASSOC);
848 return $row;
852 * Determine if a user has already voted on a specific proposal
854 * @param string $voteid The ID of the Trusted User proposal
855 * @param string $uid The ID to check if the user already voted
856 * @param \PDO $dbh An already established database connection
858 * @return bool True if the user has already voted, otherwise false
860 function tu_voted($voteid, $uid, $dbh=NULL) {
861 if (!$dbh) {
862 $dbh = db_connect();
865 $q = "SELECT COUNT(*) FROM TU_Votes ";
866 $q.= "WHERE VoteID = " . intval($voteid) . " AND UserID = " . intval($uid);
867 $result = $dbh->query($q);
868 if ($result->fetchColumn() > 0) {
869 return true;
871 else {
872 return false;
877 * Get all current Trusted User proposals from the database
879 * @param string $order Ascending or descending order for the proposal listing
880 * @param \PDO $dbh An already established database connection
882 * @return array The details for all current Trusted User proposals
884 function current_proposal_list($order, $dbh=NULL) {
885 if (!$dbh) {
886 $dbh = db_connect();
889 $q = "SELECT * FROM TU_VoteInfo WHERE End > " . time() . " ORDER BY Submitted " . $order;
890 $result = $dbh->query($q);
892 $details = array();
893 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
894 $details[] = $row;
897 return $details;
901 * Get a subset of all past Trusted User proposals from the database
903 * @param string $order Ascending or descending order for the proposal listing
904 * @param string $lim The number of proposals to list with the offset
905 * @param \PDO $dbh An already established database connection
907 * @return array The details for the subset of past Trusted User proposals
909 function past_proposal_list($order, $lim, $dbh=NULL) {
910 if (!$dbh) {
911 $dbh = db_connect();
914 $q = "SELECT * FROM TU_VoteInfo WHERE End < " . time() . " ORDER BY Submitted " . $order . $lim;
915 $result = $dbh->query($q);
917 $details = array();
918 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
919 $details[] = $row;
922 return $details;
926 * Determine the total number of Trusted User proposals
928 * @param \PDO $dbh An already established database connection
930 * @return string The total number of Trusted User proposals
932 function proposal_count($dbh=NULL) {
933 if (!$dbh) {
934 $dbh = db_connect();
937 $q = "SELECT COUNT(*) FROM TU_VoteInfo";
938 $result = $dbh->query($q);
939 $row = $result->fetch(PDO::FETCH_NUM);
941 return $row[0];
945 * Get all details related to a specific vote from the database
947 * @param string $voteid The ID of the Trusted User proposal
948 * @param \PDO $dbh An already established database connection
950 * @return array All stored details for a specific vote
952 function vote_details($voteid, $dbh=NULL) {
953 if (!$dbh) {
954 $dbh = db_connect();
957 $q = "SELECT * FROM TU_VoteInfo ";
958 $q.= "WHERE ID = " . intval($voteid);
960 $result = $dbh->query($q);
961 $row = $result->fetch(PDO::FETCH_ASSOC);
963 return $row;
967 * Get an alphabetical list of users who voted for a proposal with HTML links
969 * @param string $voteid The ID of the Trusted User proposal
970 * @param \PDO $dbh An already established database connection
972 * @return array All users (and HTML links) who voted for a specific proposal
974 function voter_list($voteid, $dbh=NULL) {
975 if (!$dbh) {
976 $dbh = db_connect();
979 $whovoted = '';
981 $q = "SELECT tv.UserID,U.Username ";
982 $q.= "FROM TU_Votes tv, Users U ";
983 $q.= "WHERE tv.VoteID = " . intval($voteid);
984 $q.= " AND tv.UserID = U.ID ";
985 $q.= "ORDER BY Username";
987 $result = $dbh->query($q);
988 if ($result) {
989 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
990 $whovoted.= '<a href="' . get_user_uri($row['Username']) . '">'.$row['Username'].'</a> ';
993 return $whovoted;
997 * Cast a vote for a specific user proposal
999 * @param string $voteid The ID of the proposal being voted on
1000 * @param string $uid The user ID of the individual voting
1001 * @param string $vote Vote position, either "Yes", "No", or "Abstain"
1002 * @param int $newtotal The total number of votes after the user has voted
1003 * @param \PDO $dbh An already established database connection
1005 * @return void
1007 function cast_proposal_vote($voteid, $uid, $vote, $newtotal, $dbh=NULL) {
1008 if (!$dbh) {
1009 $dbh = db_connect();
1012 $q = "UPDATE TU_VoteInfo SET " . $vote . " = (" . $newtotal . ") WHERE ID = " . $voteid;
1013 $result = $dbh->exec($q);
1015 $q = "INSERT INTO TU_Votes (VoteID, UserID) VALUES (" . intval($voteid) . ", " . intval($uid) . ")";
1016 $result = $dbh->exec($q);