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

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