Fix duplicate escaping of action links
[aur.git] / web / lib / aur.inc.php
blob7d6591325ad0f7354cdaebdf569c5afcd3480202
1 <?php
2 set_include_path(get_include_path() . PATH_SEPARATOR . '../lib' . PATH_SEPARATOR . '../template');
3 header('Content-Type: text/html; charset=utf-8');
4 header('Cache-Control: no-cache, must-revalidate');
5 header('Expires: Tue, 11 Oct 1988 22:00:00 GMT'); // quite a special day
6 header('Pragma: no-cache');
8 date_default_timezone_set('UTC');
10 include_once('translator.inc.php');
11 set_lang();
13 include_once("DB.class.php");
14 include_once("routing.inc.php");
15 include_once("version.inc.php");
16 include_once("acctfuncs.inc.php");
17 include_once("cachefuncs.inc.php");
18 include_once("confparser.inc.php");
19 include_once("credentials.inc.php");
21 /**
22 * Check if a visitor is logged in
24 * Query "Sessions" table with supplied cookie. Determine if the cookie is valid
25 * or not. Unset the cookie if invalid or session timeout reached. Update the
26 * session timeout if it is still valid.
28 * @global array $_COOKIE User cookie values
30 * @return void
32 function check_sid() {
33 global $_COOKIE;
35 if (isset($_COOKIE["AURSID"])) {
36 $failed = 0;
37 $timeout = config_get_int('options', 'login_timeout');
38 # the visitor is logged in, try and update the session
40 $dbh = DB::connect();
41 $q = "SELECT LastUpdateTS, UNIX_TIMESTAMP() FROM Sessions ";
42 $q.= "WHERE SessionID = " . $dbh->quote($_COOKIE["AURSID"]);
43 $result = $dbh->query($q);
44 $row = $result->fetch(PDO::FETCH_NUM);
46 if (!$row[0]) {
47 # Invalid SessionID - hacker alert!
49 $failed = 1;
50 } else {
51 $last_update = $row[0];
52 if ($last_update + $timeout <= $row[1]) {
53 $failed = 2;
57 if ($failed == 1) {
58 # clear out the hacker's cookie, and send them to a naughty page
59 # why do you have to be so harsh on these people!?
61 setcookie("AURSID", "", 1, "/", null, !empty($_SERVER['HTTPS']), true);
62 unset($_COOKIE['AURSID']);
63 } elseif ($failed == 2) {
64 # session id timeout was reached and they must login again.
66 delete_session_id($_COOKIE["AURSID"]);
68 setcookie("AURSID", "", 1, "/", null, !empty($_SERVER['HTTPS']), true);
69 unset($_COOKIE['AURSID']);
70 } else {
71 # still logged in and haven't reached the timeout, go ahead
72 # and update the idle timestamp
74 # Only update the timestamp if it is less than the
75 # current time plus $timeout.
77 # This keeps 'remembered' sessions from being
78 # overwritten.
79 if ($last_update < time() + $timeout) {
80 $q = "UPDATE Sessions SET LastUpdateTS = UNIX_TIMESTAMP() ";
81 $q.= "WHERE SessionID = " . $dbh->quote($_COOKIE["AURSID"]);
82 $dbh->exec($q);
86 return;
89 /**
90 * Verify the supplied CSRF token matches expected token
92 * @return bool True if the CSRF token is the same as the cookie SID, otherwise false
94 function check_token() {
95 if (isset($_POST['token']) && isset($_COOKIE['AURSID'])) {
96 return ($_POST['token'] == $_COOKIE['AURSID']);
97 } else {
98 return false;
103 * Verify a user supplied e-mail against RFC 3696 and DNS records
105 * @param string $addy E-mail address being validated in foo@example.com format
107 * @return bool True if e-mail passes validity checks, otherwise false
109 function valid_email($addy) {
110 // check against RFC 3696
111 if (filter_var($addy, FILTER_VALIDATE_EMAIL) === false) {
112 return false;
115 // check dns for mx, a, aaaa records
116 list($local, $domain) = explode('@', $addy);
117 if (!(checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A') || checkdnsrr($domain, 'AAAA'))) {
118 return false;
121 return true;
125 * Generate a unique session ID
127 * @return string MD5 hash of the concatenated user IP, random number, and current time
129 function new_sid() {
130 return md5($_SERVER['REMOTE_ADDR'] . uniqid(mt_rand(), true));
134 * Determine the user's username in the database using a user ID
136 * @param string $id User's ID
138 * @return string Username if it exists, otherwise null
140 function username_from_id($id) {
141 $id = intval($id);
143 $dbh = DB::connect();
144 $q = "SELECT Username FROM Users WHERE ID = " . $dbh->quote($id);
145 $result = $dbh->query($q);
146 if (!$result) {
147 return null;
150 $row = $result->fetch(PDO::FETCH_NUM);
151 return $row[0];
155 * Determine the user's username in the database using a session ID
157 * @param string $sid User's session ID
159 * @return string Username of the visitor
161 function username_from_sid($sid="") {
162 if (!$sid) {
163 return "";
165 $dbh = DB::connect();
166 $q = "SELECT Username ";
167 $q.= "FROM Users, Sessions ";
168 $q.= "WHERE Users.ID = Sessions.UsersID ";
169 $q.= "AND Sessions.SessionID = " . $dbh->quote($sid);
170 $result = $dbh->query($q);
171 if (!$result) {
172 return "";
174 $row = $result->fetch(PDO::FETCH_NUM);
176 return $row[0];
180 * Format a user name for inclusion in HTML data
182 * @param string $username The user name to format
184 * @return string The generated HTML code for the account link
186 function html_format_username($username) {
187 $username_fmt = $username ? htmlspecialchars($username, ENT_QUOTES) : __("None");
189 if ($username && isset($_COOKIE["AURSID"])) {
190 $link = '<a href="' . get_uri('/account/') . $username_fmt;
191 $link .= '" title="' . __('View account information for %s', $username_fmt);
192 $link .= '">' . $username_fmt . '</a>';
193 return $link;
194 } else {
195 return $username_fmt;
200 * Format the maintainer and co-maintainers for inclusion in HTML data
202 * @param string $maintainer The user name of the maintainer
203 * @param array $comaintainers The list of co-maintainer user names
205 * @return string The generated HTML code for the account links
207 function html_format_maintainers($maintainer, $comaintainers) {
208 $code = html_format_username($maintainer);
210 if (count($comaintainers) > 0) {
211 $code .= ' (';
212 foreach ($comaintainers as $comaintainer) {
213 $code .= html_format_username($comaintainer);
214 if ($comaintainer !== end($comaintainers)) {
215 $code .= ', ';
218 $code .= ')';
221 return $code;
225 * Format a link in the package actions box
227 * @param string $uri The link target
228 * @param string $inner The HTML code to use for the link label
230 * @return string The generated HTML code for the action link
232 function html_action_link($uri, $inner) {
233 if (isset($_COOKIE["AURSID"])) {
234 $code = '<a href="' . htmlspecialchars($uri, ENT_QUOTES) . '">';
235 } else {
236 $code = '<a href="' . get_uri('/login/', true) . '?referer=';
237 $code .= urlencode(rtrim(aur_location(), '/') . $uri) . '">';
239 $code .= $inner . '</a>';
241 return $code;
245 * Format a form in the package actions box
247 * @param string $uri The link target
248 * @param string $action The action name (passed as HTTP POST parameter)
249 * @param string $inner The HTML code to use for the link label
251 * @return string The generated HTML code for the action link
253 function html_action_form($uri, $action, $inner) {
254 if (isset($_COOKIE["AURSID"])) {
255 $code = '<form action="' . htmlspecialchars($uri, ENT_QUOTES) . '" ';
256 $code .= 'method="post">';
257 $code .= '<input type="hidden" name="token" value="';
258 $code .= htmlspecialchars($_COOKIE['AURSID'], ENT_QUOTES) . '" />';
259 $code .= '<input type="submit" class="button text-button" name="';
260 $code .= htmlspecialchars($action, ENT_QUOTES) . '" ';
261 $code .= 'value="' . $inner . '" />';
262 $code .= '</form>';
263 } else {
264 $code = '<a href="' . get_uri('/login/', true) . '">';
265 $code .= $inner . '</a>';
268 return $code;
272 * Determine the user's e-mail address in the database using a session ID
274 * @param string $sid User's session ID
276 * @return string User's e-mail address as given during registration
278 function email_from_sid($sid="") {
279 if (!$sid) {
280 return "";
282 $dbh = DB::connect();
283 $q = "SELECT Email ";
284 $q.= "FROM Users, Sessions ";
285 $q.= "WHERE Users.ID = Sessions.UsersID ";
286 $q.= "AND Sessions.SessionID = " . $dbh->quote($sid);
287 $result = $dbh->query($q);
288 if (!$result) {
289 return "";
291 $row = $result->fetch(PDO::FETCH_NUM);
293 return $row[0];
297 * Determine the user's account type in the database using a session ID
299 * @param string $sid User's session ID
301 * @return string Account type of user ("User", "Trusted User", or "Developer")
303 function account_from_sid($sid="") {
304 if (!$sid) {
305 return "";
307 $dbh = DB::connect();
308 $q = "SELECT AccountType ";
309 $q.= "FROM Users, AccountTypes, Sessions ";
310 $q.= "WHERE Users.ID = Sessions.UsersID ";
311 $q.= "AND AccountTypes.ID = Users.AccountTypeID ";
312 $q.= "AND Sessions.SessionID = " . $dbh->quote($sid);
313 $result = $dbh->query($q);
314 if (!$result) {
315 return "";
317 $row = $result->fetch(PDO::FETCH_NUM);
319 return $row[0];
323 * Determine the user's ID in the database using a session ID
325 * @param string $sid User's session ID
327 * @return string|int The user's name, 0 on query failure
329 function uid_from_sid($sid="") {
330 if (!$sid) {
331 return "";
333 $dbh = DB::connect();
334 $q = "SELECT Users.ID ";
335 $q.= "FROM Users, Sessions ";
336 $q.= "WHERE Users.ID = Sessions.UsersID ";
337 $q.= "AND Sessions.SessionID = " . $dbh->quote($sid);
338 $result = $dbh->query($q);
339 if (!$result) {
340 return 0;
342 $row = $result->fetch(PDO::FETCH_NUM);
344 return $row[0];
348 * Common AUR header displayed on all pages
350 * @global string $LANG Language selected by the visitor
351 * @global array $SUPPORTED_LANGS Languages that are supported by the AUR
352 * @param string $title Name of the AUR page to be displayed on browser
354 * @return void
356 function html_header($title="", $details=array()) {
357 global $LANG;
358 global $SUPPORTED_LANGS;
360 include('header.php');
361 return;
365 * Common AUR footer displayed on all pages
367 * @param string $ver The AUR version
369 * @return void
371 function html_footer($ver="") {
372 include('footer.php');
373 return;
377 * Determine if a user has permission to submit a package
379 * @param string $name Name of the package to be submitted
380 * @param string $sid User's session ID
382 * @return int 0 if the user can't submit, 1 if the user can submit
384 function can_submit_pkgbase($name="", $sid="") {
385 if (!$name || !$sid) {return 0;}
386 $dbh = DB::connect();
387 $q = "SELECT MaintainerUID ";
388 $q.= "FROM PackageBases WHERE Name = " . $dbh->quote($name);
389 $result = $dbh->query($q);
390 $row = $result->fetch(PDO::FETCH_NUM);
392 if (!$row[0]) {
393 return 1;
395 $my_uid = uid_from_sid($sid);
397 if ($row[0] === NULL || $row[0] == $my_uid) {
398 return 1;
401 return 0;
405 * Determine if a package can be overwritten by some package base
407 * @param string $name Name of the package to be submitted
408 * @param int $base_id The ID of the package base
410 * @return bool True if the package can be overwritten, false if not
412 function can_submit_pkg($name, $base_id) {
413 $dbh = DB::connect();
414 $q = "SELECT COUNT(*) FROM Packages WHERE ";
415 $q.= "Name = " . $dbh->quote($name) . " AND ";
416 $q.= "PackageBaseID <> " . intval($base_id);
417 $result = $dbh->query($q);
419 if (!$result) return false;
420 return ($result->fetchColumn() == 0);
424 * Recursively delete a directory
426 * @param string $dirname Name of the directory to be removed
428 * @return void
430 function rm_tree($dirname) {
431 if (empty($dirname) || !is_dir($dirname)) return;
433 foreach (scandir($dirname) as $item) {
434 if ($item != '.' && $item != '..') {
435 $path = $dirname . '/' . $item;
436 if (is_file($path) || is_link($path)) {
437 unlink($path);
439 else {
440 rm_tree($path);
445 rmdir($dirname);
447 return;
451 * Determine the user's ID in the database using a username
453 * @param string $username The username of an account
455 * @return string Return user ID if exists for username, otherwise null
457 function uid_from_username($username) {
458 $dbh = DB::connect();
459 $q = "SELECT ID FROM Users WHERE Username = " . $dbh->quote($username);
460 $result = $dbh->query($q);
461 if (!$result) {
462 return null;
465 $row = $result->fetch(PDO::FETCH_NUM);
466 return $row[0];
470 * Determine the user's ID in the database using an e-mail address
472 * @param string $email An e-mail address in foo@example.com format
474 * @return string The user's ID
476 function uid_from_email($email) {
477 $dbh = DB::connect();
478 $q = "SELECT ID FROM Users WHERE Email = " . $dbh->quote($email);
479 $result = $dbh->query($q);
480 if (!$result) {
481 return null;
484 $row = $result->fetch(PDO::FETCH_NUM);
485 return $row[0];
489 * Generate clean url with edited/added user values
491 * Makes a clean string of variables for use in URLs based on current $_GET and
492 * list of values to edit/add to that. Any empty variables are discarded.
494 * @example print "http://example.com/test.php?" . mkurl("foo=bar&bar=baz")
496 * @param string $append string of variables and values formatted as in URLs
498 * @return string clean string of variables to append to URL, urlencoded
500 function mkurl($append) {
501 $get = $_GET;
502 $append = explode('&', $append);
503 $uservars = array();
504 $out = '';
506 foreach ($append as $i) {
507 $ex = explode('=', $i);
508 $uservars[$ex[0]] = $ex[1];
511 foreach ($uservars as $k => $v) { $get[$k] = $v; }
513 foreach ($get as $k => $v) {
514 if ($v !== '') {
515 $out .= '&amp;' . urlencode($k) . '=' . urlencode($v);
519 return substr($out, 5);
523 * Determine a user's salt from the database
525 * @param string $user_id The user ID of the user trying to log in
527 * @return string|void Return the salt for the requested user, otherwise void
529 function get_salt($user_id) {
530 $dbh = DB::connect();
531 $q = "SELECT Salt FROM Users WHERE ID = " . $user_id;
532 $result = $dbh->query($q);
533 if ($result) {
534 $row = $result->fetch(PDO::FETCH_NUM);
535 return $row[0];
537 return;
541 * Save a user's salted password in the database
543 * @param string $user_id The user ID of the user who is salting their password
544 * @param string $passwd The password of the user logging in
546 function save_salt($user_id, $passwd) {
547 $dbh = DB::connect();
548 $salt = generate_salt();
549 $hash = salted_hash($passwd, $salt);
550 $q = "UPDATE Users SET Salt = " . $dbh->quote($salt) . ", ";
551 $q.= "Passwd = " . $dbh->quote($hash) . " WHERE ID = " . $user_id;
552 return $dbh->exec($q);
556 * Generate a string to be used for salting passwords
558 * @return string MD5 hash of concatenated random number and current time
560 function generate_salt() {
561 return md5(uniqid(mt_rand(), true));
565 * Combine salt and password to form a hash
567 * @param string $passwd User plaintext password
568 * @param string $salt MD5 hash to be used as user salt
570 * @return string The MD5 hash of the concatenated salt and user password
572 function salted_hash($passwd, $salt) {
573 if (strlen($salt) != 32) {
574 trigger_error('Salt does not look like an md5 hash', E_USER_WARNING);
576 return md5($salt . $passwd);
580 * Get a package comment
582 * @param int $comment_id The ID of the comment
584 * @return array The user ID and comment OR null, null in case of an error
586 function comment_by_id($comment_id) {
587 $dbh = DB::connect();
588 $q = "SELECT UsersID, Comments FROM PackageComments ";
589 $q.= "WHERE ID = " . intval($comment_id);
590 $result = $dbh->query($q);
591 if (!$result) {
592 return array(null, null);
595 return $result->fetch(PDO::FETCH_NUM);
599 * Process submitted comments so any links can be followed
601 * @param string $comment Raw user submitted package comment
603 * @return string User comment with links printed in HTML
605 function parse_comment($comment) {
606 $url_pattern = '/(\b(?:https?|ftp):\/\/[\w\/\#~:.?+=&%@!\-;,]+?' .
607 '(?=[.:?\-;,]*(?:[^\w\/\#~:.?+=&%@!\-;,]|$)))/iS';
609 $matches = preg_split($url_pattern, $comment, -1,
610 PREG_SPLIT_DELIM_CAPTURE);
612 $html = '';
613 for ($i = 0; $i < count($matches); $i++) {
614 if ($i % 2) {
615 # convert links
616 $html .= '<a href="' . htmlspecialchars($matches[$i]) .
617 '" rel="nofollow">' . htmlspecialchars($matches[$i]) . '</a>';
619 else {
620 # convert everything else
621 $html .= nl2br(htmlspecialchars($matches[$i]));
625 return $html;
629 * Wrapper for beginning a database transaction
631 function begin_atomic_commit() {
632 $dbh = DB::connect();
633 $dbh->beginTransaction();
637 * Wrapper for committing a database transaction
639 function end_atomic_commit() {
640 $dbh = DB::connect();
641 $dbh->commit();
645 * Merge pkgbase and package options
647 * Merges entries of the first and the second array. If any key appears in both
648 * arrays and the corresponding value in the second array is either a non-array
649 * type or a non-empty array, the value from the second array replaces the
650 * value from the first array. If the value from the second array is an array
651 * containing a single empty string, the value in the resulting array becomes
652 * an empty array instead. If the value in the second array is empty, the
653 * resulting array contains the value from the first array.
655 * @param array $pkgbase_info Options from the pkgbase section
656 * @param array $section_info Options from the package section
658 * @return array Merged information from both sections
660 function array_pkgbuild_merge($pkgbase_info, $section_info) {
661 $pi = $pkgbase_info;
662 foreach ($section_info as $opt_key => $opt_val) {
663 if (is_array($opt_val)) {
664 if ($opt_val == array('')) {
665 $pi[$opt_key] = array();
666 } elseif (count($opt_val) > 0) {
667 $pi[$opt_key] = $opt_val;
669 } else {
670 $pi[$opt_key] = $opt_val;
673 return $pi;
677 * Bound an integer value between two values
679 * @param int $n Integer value to bound
680 * @param int $min Lower bound
681 * @param int $max Upper bound
683 * @return int Bounded integer value
685 function bound($n, $min, $max) {
686 return min(max($n, $min), $max);
690 * Return the URL of the AUR root
692 * @return string The URL of the AUR root
694 function aur_location() {
695 $location = config_get('options', 'aur_location');
696 if (substr($location, -1) != '/') {
697 $location .= '/';
699 return $location;