Oppaitime's version of Gazelle
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. <?php
  2. /*-- TODO ---------------------------//
  3. Add the JavaScript validation into the display page using the class
  4. //-----------------------------------*/
  5. // Allow users to reset their password while logged in
  6. if (!empty($LoggedUser['ID']) && $_REQUEST['act'] != 'recover') {
  7. header('Location: index.php');
  8. die();
  9. }
  10. if (BLOCK_OPERA_MINI && isset($_SERVER['HTTP_X_OPERAMINI_PHONE'])) {
  11. error('Opera Mini is banned. Please use another browser.');
  12. }
  13. // Check if IP is banned
  14. if (Tools::site_ban_ip($_SERVER['REMOTE_ADDR'])) {
  15. error('Your IP address has been banned.');
  16. }
  17. require(SERVER_ROOT.'/classes/validate.class.php');
  18. $Validate = NEW VALIDATE;
  19. if (array_key_exists('action', $_GET) && $_GET['action'] == 'disabled') {
  20. require('disabled.php');
  21. die();
  22. }
  23. if (isset($_REQUEST['act']) && $_REQUEST['act'] == 'recover') {
  24. // Recover password
  25. if (!empty($_REQUEST['key'])) {
  26. // User has entered a new password, use step 2
  27. $DB->query("
  28. SELECT
  29. m.ID,
  30. m.Email,
  31. m.ipcc,
  32. i.ResetExpires
  33. FROM users_main AS m
  34. INNER JOIN users_info AS i ON i.UserID = m.ID
  35. WHERE i.ResetKey = '".db_string($_REQUEST['key'])."'
  36. AND i.ResetKey != ''");
  37. list($UserID, $Email, $Country, $Expires) = $DB->next_record();
  38. if (!apc_exists('DBKEY')) {
  39. error('Database not fully decrypted. Please wait for staff to fix this and try again later');
  40. }
  41. $Email = DBCrypt::decrypt($Email);
  42. if ($UserID && strtotime($Expires) > time()) {
  43. // If the user has requested a password change, and his key has not expired
  44. $Validate->SetFields('password', '1', 'regex', 'You entered an invalid password. Any password at least 6 characters long is accepted, but a strong password is 8 characters or longer, contains at least 1 lowercase and uppercase letter, contains at least a number or symbol', array('regex' => '/(?=^.{6,}$).*$/'));
  45. $Validate->SetFields('verifypassword', '1', 'compare', 'Your passwords did not match.', array('comparefield' => 'password'));
  46. if (!empty($_REQUEST['password'])) {
  47. // If the user has entered a password.
  48. // If the user has not entered a password, $PassWasReset is not set to 1, and the success message is not shown
  49. $Err = $Validate->ValidateForm($_REQUEST);
  50. if ($Err == '') {
  51. // Form validates without error, set new secret and password.
  52. $DB->query("
  53. UPDATE
  54. users_main AS m,
  55. users_info AS i
  56. SET
  57. m.PassHash = '".db_string(Users::make_sec_hash($_REQUEST['password']))."',
  58. i.ResetKey = '',
  59. m.LastLogin = NOW(),
  60. i.ResetExpires = '0000-00-00 00:00:00'
  61. WHERE m.ID = '$UserID'
  62. AND i.UserID = m.ID");
  63. $DB->query("
  64. INSERT INTO users_history_passwords
  65. (UserID, ChangerIP, ChangeTime)
  66. VALUES
  67. ('$UserID', '".DBCrypt::encrypt($_SERVER['REMOTE_ADDR'])."', '".sqltime()."')");
  68. $PassWasReset = true;
  69. $LoggedUser['ID'] = $UserID; // Set $LoggedUser['ID'] for logout_all_sessions() to work
  70. logout_all_sessions();
  71. }
  72. }
  73. // Either a form asking for them to enter the password
  74. // Or a success message if $PassWasReset is 1
  75. require('recover_step2.php');
  76. } else {
  77. // Either his key has expired, or he hasn't requested a pass change at all
  78. if (strtotime($Expires) < time() && $UserID) {
  79. // If his key has expired, clear all the reset information
  80. $DB->query("
  81. UPDATE users_info
  82. SET ResetKey = '',
  83. ResetExpires = '0000-00-00 00:00:00'
  84. WHERE UserID = '$UserID'");
  85. $_SESSION['reseterr'] = 'The link you were given has expired.'; // Error message to display on form
  86. }
  87. // Show him the first form (enter email address)
  88. header('Location: login.php?act=recover');
  89. }
  90. } // End step 2
  91. // User has not clicked the link in his email, use step 1
  92. else {
  93. $Validate->SetFields('email', '1', 'email', 'You entered an invalid email address.');
  94. if (!empty($_REQUEST['email'])) {
  95. // User has entered email and submitted form
  96. $Err = $Validate->ValidateForm($_REQUEST);
  97. if (!apc_exists('DBKEY')) {
  98. $Err = 'Database not fully decrypted. Please wait for staff to fix this and try again.';
  99. }
  100. if (!$Err) {
  101. // Form validates correctly
  102. $DB->query("
  103. SELECT
  104. Email
  105. FROM users_main");
  106. while(list($EncEmail) = $DB->next_record()) {
  107. if (strtolower($_REQUEST['email']) == strtolower(DBCrypt::decrypt($EncEmail))) {
  108. break; // $EncEmail is now the encrypted form of the given email from the database
  109. }
  110. }
  111. $DB->query("
  112. SELECT
  113. ID,
  114. Username,
  115. Email
  116. FROM users_main
  117. WHERE Email = '$EncEmail'");
  118. list($UserID, $Username, $Email) = $DB->next_record();
  119. $Email = DBCrypt::decrypt($Email);
  120. if ($UserID) {
  121. // Email exists in the database
  122. // Set ResetKey, send out email, and set $Sent to 1 to show success page
  123. Users::reset_password($UserID, $Username, $Email);
  124. $Sent = 1; // If $Sent is 1, recover_step1.php displays a success message
  125. //Log out all of the users current sessions
  126. $Cache->delete_value("user_info_$UserID");
  127. $Cache->delete_value("user_info_heavy_$UserID");
  128. $Cache->delete_value("user_stats_$UserID");
  129. $Cache->delete_value("enabled_$UserID");
  130. $DB->query("
  131. SELECT SessionID
  132. FROM users_sessions
  133. WHERE UserID = '$UserID'");
  134. while (list($SessionID) = $DB->next_record()) {
  135. $Cache->delete_value("session_$UserID"."_$SessionID");
  136. }
  137. $DB->query("
  138. UPDATE users_sessions
  139. SET Active = 0
  140. WHERE UserID = '$UserID'
  141. AND Active = 1");
  142. } else {
  143. $Err = 'There is no user with that email address.';
  144. }
  145. }
  146. } elseif (!empty($_SESSION['reseterr'])) {
  147. // User has not entered email address, and there is an error set in session data
  148. // This is typically because their key has expired.
  149. // Stick the error into $Err so recover_step1.php can take care of it
  150. $Err = $_SESSION['reseterr'];
  151. unset($_SESSION['reseterr']);
  152. }
  153. // Either a form for the user's email address, or a success message
  154. require('recover_step1.php');
  155. }
  156. } // End password recovery
  157. else if (isset($_REQUEST['act']) && $_REQUEST['act'] == 'newlocation') {
  158. if (isset($_REQUEST['key'])) {
  159. if ($ASNCache = $Cache->get_value('new_location_'.$_REQUEST['key'])) {
  160. $Cache->cache_value('new_location_'.$ASNCache['UserID'].'_'.$ASNCache['ASN'], true);
  161. require('newlocation.php');
  162. die();
  163. } else {
  164. error(403);
  165. }
  166. } else {
  167. error(403);
  168. }
  169. } // End new location
  170. // Normal login
  171. else {
  172. $Validate->SetFields('username', true, 'regex', 'You did not enter a valid username.', array('regex' => USERNAME_REGEX));
  173. $Validate->SetFields('password', '1', 'string', 'You entered an invalid password.', array('minlength' => '6', 'maxlength' => '307200'));
  174. list($Attempts, $Banned) = $Cache->get_value('login_attempts_'.db_string($_SERVER['REMOTE_ADDR']));
  175. // Function to log a user's login attempt
  176. function log_attempt() {
  177. global $Cache, $Attempts;
  178. $Attempts = ($Attempts ?? 0) + 1;
  179. $Cache->cache_value('login_attempts_'.db_string($_SERVER['REMOTE_ADDR']), array($Attempts, ($Attempts > 5)), 60*60*$Attempts);
  180. $AllAttempts = $Cache->get_value('login_attempts');
  181. $AllAttempts[$_SERVER['REMOTE_ADDR']] = time()+(60*60*$Attempts);
  182. foreach($AllAttempts as $IP => $Time) {
  183. if ($Time < time()) { unset($AllAttempts[$IP]); }
  184. }
  185. $Cache->cache_value('login_attempts', $AllAttempts, 0);
  186. }
  187. // If user has submitted form
  188. if (isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['password']) && !empty($_POST['password'])) {
  189. if ($Banned) {
  190. header("Location: login.php");
  191. die();
  192. }
  193. $Err = $Validate->ValidateForm($_POST);
  194. if (!$Err) {
  195. // Passes preliminary validation (username and password "look right")
  196. $DB->query("
  197. SELECT
  198. ID,
  199. PermissionID,
  200. CustomPermissions,
  201. PassHash,
  202. Enabled
  203. FROM users_main
  204. WHERE Username = '".db_string($_POST['username'])."'
  205. AND Username != ''");
  206. list($UserID, $PermissionID, $CustomPermissions, $PassHash, $Enabled) = $DB->next_record(MYSQLI_NUM, array(2));
  207. if (!$Banned) {
  208. if ($UserID && Users::check_password($_POST['password'], $PassHash)) {
  209. // Update hash if better algorithm available
  210. if (password_needs_rehash($PassHash, PASSWORD_DEFAULT)) {
  211. $DB->query("
  212. UPDATE users_main
  213. SET PassHash = '".make_sec_hash($_POST['password'])."'
  214. WHERE Username = '".db_string($_POST['username'])."'");
  215. }
  216. if ($Enabled == 1) {
  217. // Check if the current login attempt is from a location previously logged in from
  218. if (apc_exists('DBKEY')) {
  219. $DB->query("
  220. SELECT IP
  221. FROM users_history_ips
  222. WHERE UserID = $UserID");
  223. $IPs = $DB->to_array(false, MYSQLI_NUM);
  224. $QueryParts = array();
  225. foreach ($IPs as $i => $IP) {
  226. $IPs[$i] = DBCrypt::decrypt($IP[0]);
  227. }
  228. $IPs = array_unique($IPs);
  229. if (count($IPs) > 0) { // Always allow first login
  230. foreach ($IPs as $IP) {
  231. $QueryParts[] = "(StartIP<=INET6_ATON('$IP') AND EndIP>=INET6_ATON('$IP'))";
  232. }
  233. $DB->query('SELECT ASN FROM geoip_asn WHERE '.implode(' OR ', $QueryParts));
  234. $PastASNs = array_column($DB->to_array(false, MYSQLI_NUM), 0);
  235. $DB->query("SELECT ASN FROM geoip_asn WHERE StartIP<=INET6_ATON('$_SERVER[REMOTE_ADDR]') AND EndIP>=INET6_ATON('$_SERVER[REMOTE_ADDR]')");
  236. list($CurrentASN) = $DB->next_record();
  237. if (!in_array($CurrentASN, $PastASNs)) {
  238. // Never logged in from this location before
  239. if ($Cache->get_value('new_location_'.$UserID.'_'.$CurrentASN) !== true) {
  240. $DB->query("
  241. SELECT
  242. UserName,
  243. Email
  244. FROM users_main
  245. WHERE ID = $UserID");
  246. list($Username, $Email) = $DB->next_record();
  247. Users::auth_location($UserID, $Username, $CurrentASN, DBCrypt::decrypt($Email));
  248. require('newlocation.php');
  249. die();
  250. }
  251. }
  252. }
  253. }
  254. $SessionID = Users::make_secret(64);
  255. $KeepLogged = ($_POST['keeplogged'] ?? false) ? 1 : 0;
  256. setcookie('session', $SessionID, (time()+60*60*24*365)*$KeepLogged, '/', '', true, true);
  257. setcookie('userid', $UserID, (time()+60*60*24*365)*$KeepLogged, '/', '', true, true);
  258. // Because we <3 our staff
  259. $Permissions = Permissions::get_permissions($PermissionID);
  260. $CustomPermissions = unserialize($CustomPermissions);
  261. if (isset($Permissions['Permissions']['site_disable_ip_history'])
  262. || isset($CustomPermissions['site_disable_ip_history'])
  263. ) {
  264. $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
  265. }
  266. $DB->query("
  267. INSERT INTO users_sessions
  268. (UserID, SessionID, KeepLogged, Browser, OperatingSystem, IP, LastUpdate, FullUA)
  269. VALUES
  270. ('$UserID', '".db_string($SessionID)."', '$KeepLogged', '$Browser', '$OperatingSystem', '".db_string(apc_exists('DBKEY')?DBCrypt::encrypt($_SERVER['REMOTE_ADDR']):'0.0.0.0')."', '".sqltime()."', '".db_string($_SERVER['HTTP_USER_AGENT'])."')");
  271. $Cache->begin_transaction("users_sessions_$UserID");
  272. $Cache->insert_front($SessionID, array(
  273. 'SessionID' => $SessionID,
  274. 'Browser' => $Browser,
  275. 'OperatingSystem' => $OperatingSystem,
  276. 'IP' => (apc_exists('DBKEY')?DBCrypt::encrypt($_SERVER['REMOTE_ADDR']):'0.0.0.0'),
  277. 'LastUpdate' => sqltime()
  278. ));
  279. $Cache->commit_transaction(0);
  280. $Sql = "
  281. UPDATE users_main
  282. SET
  283. LastLogin = '".sqltime()."',
  284. LastAccess = '".sqltime()."'
  285. WHERE ID = '".db_string($UserID)."'";
  286. $DB->query($Sql);
  287. if (!empty($_COOKIE['redirect'])) {
  288. $URL = $_COOKIE['redirect'];
  289. setcookie('redirect', '', time() - 60 * 60 * 24, '/', '', false);
  290. header("Location: $URL");
  291. die();
  292. } else {
  293. header('Location: index.php');
  294. die();
  295. }
  296. } else {
  297. log_attempt();
  298. if ($Enabled == 2) {
  299. // Save the username in a cookie for the disabled page
  300. setcookie('username', db_string($_POST['username']), time() + 60 * 60, '/', '', false);
  301. header('Location: login.php?action=disabled');
  302. } elseif ($Enabled == 0) {
  303. $Err = 'Your account has not been confirmed.<br />Please check your email.';
  304. }
  305. setcookie('keeplogged', '', time() + 60 * 60 * 24 * 365, '/', '', false);
  306. }
  307. } else {
  308. log_attempt();
  309. $Err = 'Your username or password was incorrect.';
  310. setcookie('keeplogged', '', time() + 60 * 60 * 24 * 365, '/', '', false);
  311. }
  312. } else {
  313. log_attempt();
  314. setcookie('keeplogged', '', time() + 60 * 60 * 24 * 365, '/', '', false);
  315. }
  316. } else {
  317. log_attempt();
  318. setcookie('keeplogged', '', time() + 60 * 60 * 24 * 365, '/', '', false);
  319. }
  320. }
  321. require('sections/login/login.php');
  322. }