Geek400

PHP logSys Fixed Code

Jun 26th, 2015
389
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 29.18 KB | None | 0 0
  1. <?php
  2. namespace Fr;
  3.  
  4. /**
  5. .---------------------------------------------------------------------------.
  6. | The Francium Project |
  7. | ------------------------------------------------------------------------- |
  8. | This software logSys is a part of the Francium (Fr) project. |
  9. | http://subinsb.com/the-francium-project |
  10. | ------------------------------------------------------------------------- |
  11. | Author: Subin Siby |
  12. | Copyright (c) 2014 - 2015, Subin Siby. All Rights Reserved. |
  13. | ------------------------------------------------------------------------- |
  14. | License: Distributed under the General Public License (GPL) |
  15. | http://www.gnu.org/licenses/gpl-3.0.html |
  16. | This program is distributed in the hope that it will be useful - WITHOUT |
  17. | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
  18. | FITNESS FOR A PARTICULAR PURPOSE. |
  19. '---------------------------------------------------------------------------'
  20. */
  21.  
  22. /**
  23. .---------------------------------------------------------------------------.
  24. | Software: PHP Login System - PHP logSys |
  25. | Version: 0.4 (2015 May 07) |
  26. | Contact: http://github.com/subins2000/logsys |
  27. | Documentation: https://subinsb.com/php-logsys |
  28. | Support: http://subinsb.com/ask/php-logsys |
  29. '---------------------------------------------------------------------------'
  30. */
  31.  
  32. ini_set("display_errors", "on");
  33.  
  34. class LS {
  35.  
  36. /**
  37. * ------------
  38. * BEGIN CONFIG
  39. * ------------
  40. * Edit the configuraion
  41. */
  42.  
  43. public static $default_config = array(
  44. /**
  45. * Information about who uses logSys
  46. */
  47. "info" => array(
  48. "company" => "The Tax Elephants",
  49. "email" => "[email protected]"
  50. ),
  51.  
  52. /**
  53. * Database Configuration
  54. */
  55. "db" => array(
  56. "host" => "",
  57. "port" => "3306",
  58. "username" => "",
  59. "password" => "",
  60. "name" => "",
  61. "table" => "users"
  62. ),
  63.  
  64. /**
  65. * Keys used for encryption
  66. * DONT MAKE THIS PUBLIC
  67. */
  68. "keys" => array(
  69. /**
  70. * Changing cookie key will expire all current active login sessions
  71. */
  72. "cookie" => "ckxc436jd*^30f840v*9!@#$",
  73. /**
  74. * `salt` should not be changed after users are created
  75. */
  76. "salt" => "^#$4%9f+1^p9)M@4M)V$"
  77. ),
  78.  
  79. /**
  80. * Enable/Disable certain features
  81. */
  82. "features" => array(
  83. /**
  84. * Should I Call session_start();
  85. */
  86. "start_session" => true,
  87. /**
  88. * Enable/Disable Login using Username & E-Mail
  89. */
  90. "email_login" => true,
  91. /**
  92. * Enable/Disable `Remember Me` feature
  93. */
  94. "remember_me" => true,
  95. /**
  96. * Should \Fr\LS::init() be called automatically
  97. */
  98. "auto_init" => false,
  99.  
  100. /**
  101. * Prevent Brute Forcing.
  102. * By enabling this, logSys will deny login for the time mentioned
  103. * in the "brute_force"->"time_limit" seconds after "brute_force"->"tries"
  104. * number of incorrect login tries.
  105. */
  106. "block_brute_force" => true
  107. ),
  108.  
  109. /**
  110. * `Blocking Brute Force Attacks` options
  111. */
  112. "brute_force" => array(
  113. /**
  114. * No of tries alloted to each user
  115. */
  116. "tries" => 5,
  117. /**
  118. * The time IN SECONDS for which block from login action should be done after
  119. * incorrect login attempts. Use http://www.easysurf.cc/utime.htm#m60s
  120. * for converting minutes to seconds. Default : 5 minutes
  121. */
  122. "time_limit" => 300,
  123. ),
  124.  
  125. /**
  126. * Information about pages
  127. */
  128.  
  129. "pages" => array(
  130. "no_login" => array(
  131. "/",
  132. "/reset.php",
  133. "/register.php"
  134. ),
  135. /**
  136. * The login page. ex : /login.php or /accounts/login.php
  137. */
  138. "login_page" => "/login.php",
  139. /**
  140. * The home page. The main page for logged in users.
  141. * logSys redirects to here after user logs in
  142. */
  143. "home_page" => "/profile.php",
  144. ),
  145.  
  146. /**
  147. * Settings about cookie creation
  148. */
  149. "cookies" => array(
  150. /**
  151. * Default : cookies expire in 30 days. The value is
  152. * for setting in strtotime() function
  153. * http://php.net/manual/en/function.strtotime.php
  154. */
  155. "expire" => "+30 days",
  156. "path" => "/",
  157. "domain" => "",
  158. ),
  159. );
  160.  
  161. /* ------------
  162. * END Config.
  163. * ------------
  164. * No more editing after this line.
  165. */
  166.  
  167. public static $config = array();
  168. private static $constructed = false;
  169.  
  170. /**
  171. * Merge user config and default config
  172. */
  173. public static function config(){
  174. self::$config = array_replace_recursive(self::$default_config, self::$config);
  175. }
  176.  
  177. /**
  178. * Log something in the Francium.log file.
  179. * To enable logging, make a file called "Francium.log" in the directory
  180. * where "class.logsys.php" file is situated
  181. */
  182. public static function log($msg = ""){
  183. $log_file = __DIR__ . "/Francium.log";
  184. if(file_exists($log_file)){
  185. if($msg != ""){
  186. $message = "[" . date("Y-m-d H:i:s") . "] $msg";
  187. $fh = fopen($log_file, 'a');
  188. fwrite($fh, $message . "\n");
  189. fclose($fh);
  190. }
  191. }
  192. }
  193.  
  194. public static $loggedIn = false;
  195. public static $db = true;
  196. public static $user = false;
  197. private static $init_called = false;
  198. private static $cookie, $session, $remember_cookie, $dbh;
  199.  
  200. public static function construct($called_from = ""){
  201. if(self::$constructed === false){
  202. self::config();
  203. self::$constructed = true;
  204.  
  205. if(self::$config['features']['start_session'] === true){
  206. session_start();
  207. }
  208. /**
  209. * Try connecting to Database Server
  210. */
  211. try{
  212. /**
  213. * Add the login page to the array of pages that doesn't need logging in
  214. */
  215. array_push(self::$config['pages']['no_login'], self::$config['pages']['login_page']);
  216.  
  217. self::$dbh = new \PDO("mysql:dbname=". self::$config['db']['name'] .";host=". self::$config['db']['host'] .";port=". self::$config['db']['port'], self::$config['db']['username'], self::$config['db']['password']);
  218. self::$db = true;
  219.  
  220. self::$cookie = isset($_COOKIE['logSyslogin']) ? $_COOKIE['logSyslogin'] : false;
  221. self::$session = isset($_SESSION['logSyscuruser']) ? $_SESSION['logSyscuruser'] : false;
  222. self::$remember_cookie = isset($_COOKIE['logSysrememberMe']) ? $_COOKIE['logSysrememberMe'] : false;
  223.  
  224. $encUserID = hash("sha256", self::$config['keys']['cookie'] . self::$session . self::$config['keys']['cookie']);
  225.  
  226. if(self::$cookie == $encUserID){
  227. self::$loggedIn = true;
  228. }else{
  229. self::$loggedIn = false;
  230. }
  231.  
  232. /**
  233. * If there is a Remember Me Cookie and the user is not logged in,
  234. * then log in the user with the ID in the remember cookie, if it
  235. * matches with the decrypted value in `logSyslogin` cookie
  236. */
  237. if(self::$config['features']['remember_me'] === true && self::$remember_cookie !== false && self::$loggedIn === false){
  238. $encUserID = hash("sha256", self::$config['keys']['cookie']. self::$remember_cookie . self::$config['keys']['cookie']);
  239. if(self::$cookie == $encUserID){
  240. self::$loggedIn = true;
  241. }else{
  242. self::$loggedIn = false;
  243. }
  244.  
  245. if(self::$loggedIn === true){
  246. $_SESSION['logSyscuruser'] = self::$remember_cookie;
  247. self::$session = self::$remember_cookie;
  248. }
  249. }
  250.  
  251. self::$user = self::$session;
  252. if(self::$config['features']['auto_init'] === true && $called_from != "logout" && $called_from != "login"){
  253. self::init();
  254. }
  255. return true;
  256. }catch(\PDOException $e) {
  257. /**
  258. * Couldn't connect to Database
  259. */
  260. self::log('Couldn\'t connect to database. Check \Fr\LS::$config["db"] credentials');
  261. return false;
  262. }
  263. }
  264. }
  265.  
  266. /**
  267. * A function that will automatically redirect user according to his/her login status
  268. */
  269. public static function init() {
  270. self::construct();
  271. if(self::$loggedIn === true && array_search(self::curPage(), self::$config['pages']['no_login']) !== false){
  272. self::redirect(self::$config['pages']['home_page']);
  273. }elseif(self::$loggedIn === false && array_search(self::curPage(), self::$config['pages']['no_login']) === false){
  274. self::redirect(self::$config['pages']['login_page']);
  275. }
  276. self::$init_called = true;
  277. }
  278.  
  279. /**
  280. * A function to login the user with the username and password.
  281. * As of version 0.4, it is required to include the remember_me parameter
  282. * when calling this function to avail the "Remember Me" feature.
  283. */
  284. public static function login($username, $password, $remember_me = false, $cookies = true){
  285. self::construct("login");
  286. if(self::$db === true){
  287. /**
  288. * We Add LIMIT to 1 in SQL query because to
  289. * get an array with key as the column name.
  290. */
  291. if(self::$config['features']['email_login'] === true){
  292. $query = "SELECT `id`, `password`, `password_salt`, `attempt` FROM `". self::$config['db']['table'] ."` WHERE `username`=:login OR `email`=:login ORDER BY `id` LIMIT 1";
  293. }else{
  294. $query = "SELECT `id`, `password`, `password_salt`, `attempt` FROM `". self::$config['db']['table'] ."` WHERE `username`=:login ORDER BY `id` LIMIT 1";
  295. }
  296.  
  297. $sql = self::$dbh->prepare($query);
  298. $sql->bindValue(":login", $username);
  299. $sql->execute();
  300.  
  301. if($sql->rowCount() == 0){
  302. // No such user like that
  303. return false;
  304. }else{
  305. /**
  306. * Get the user details
  307. */
  308. $rows = $sql->fetch(\PDO::FETCH_ASSOC);
  309. $us_id = $rows['id'];
  310. $us_pass = $rows['password'];
  311. $us_salt = $rows['password_salt'];
  312. $status = $rows['attempt'];
  313. $saltedPass = hash('sha256', $password . self::$config['keys']['salt'] . $us_salt);
  314.  
  315. if(substr($status, 0, 2) == "b-"){
  316. $blockedTime = substr($status, 2);
  317. if(time() < $blockedTime){
  318. $block = true;
  319. return array(
  320. "status" => "blocked",
  321. "minutes" => round(abs($blockedTime - time()) / 60, 0),
  322. "seconds" => round(abs($blockedTime - time()) / 60*60, 2)
  323. );
  324. }else{
  325. // remove the block, because the time limit is over
  326. self::updateUser(array(
  327. "attempt" => "" // No tries at all
  328. ), $us_id);
  329. }
  330. }
  331. /**
  332. * Why login if password is empty ?
  333. * --------------------------------
  334. * If using OAuth, you have to login someone without knowing their password,
  335. * this usage is helpful. But, it makes a serious security problem too.
  336. * Hence, before calling \Fr\LS::login() in the login page, it is
  337. * required to check whether the password fieldis left blank
  338. */
  339. if(!isset($block) && ($saltedPass == $us_pass || $password == "")){
  340. if($cookies === true){
  341.  
  342. $_SESSION['logSyscuruser'] = $us_id;
  343. setcookie("logSyslogin", hash("sha256", self::$config['keys']['cookie'] . $us_id . self::$config['keys']['cookie']), strtotime(self::$config['cookies']['expire']), self::$config['cookies']['path'], self::$config['cookies']['domain']);
  344.  
  345. if( $remember_me === true && self::$config['features']['remember_me'] === true ){
  346. setcookie("logSysrememberMe", $us_id, strtotime(self::$config['cookies']['expire']), self::$config['cookies']['path'], self::$config['cookies']['domain']);
  347. }
  348. self::$loggedIn = true;
  349.  
  350. // Update the attempt status
  351. self::updateUser(array(
  352. "attempt" => "" // No tries
  353. ), $us_id);
  354.  
  355. // Redirect
  356. if( self::$init_called ){
  357. self::redirect(self::$config['pages']['home_page']);
  358. }
  359. }
  360. return true;
  361. }else{
  362. // Incorrect password
  363. if(self::$config['features']['block_brute_force'] === true){
  364. // Checking for brute force is enabled
  365. if($status == ""){
  366. // User was not logged in before
  367. self::updateUser(array(
  368. "attempt" => "1" // Tried 1 time
  369. ), $us_id);
  370. }else if($status == 5){
  371. self::updateUser(array(
  372. /**
  373. * Account Blocked. User only able to
  374. * re-login at the time in UNIX timestamp
  375. */
  376. "attempt" => "b-" . strtotime("+". self::$config['brute_force']['time_limit'] ." seconds", time())
  377. ), $us_id);
  378. }else if(substr($status, 0, 2) == "b-"){
  379. // Account blocked
  380. }else if($status < 5){
  381. // If the attempts are less than 5 and not 5
  382. self::updateUser(array(
  383. "attempt" => $status + 1 // Increase the no of tries by +1.
  384. ), $us_id);
  385. }
  386. }
  387. return false;
  388. }
  389. }
  390. }
  391. }
  392.  
  393. /**
  394. * A function to register a user with passing the username, password
  395. * and optionally any other additional fields.
  396. */
  397. public static function register( $id, $password, $other = array() ){
  398. self::construct();
  399. if( self::userExists($id) || (isset($other['email']) && self::userExists($other['email'])) ){
  400. return "exists";
  401. }else{
  402. $randomSalt = self::rand_string(20);
  403. $saltedPass = hash('sha256', $password. self::$config['keys']['salt'] . $randomSalt);
  404.  
  405. if( count($other) == 0 ){
  406. /* If there is no other fields mentioned, make the default query */
  407. $sql = self::$dbh->prepare("INSERT INTO `". self::$config['db']['table'] ."` (`username`, `password`, `password_salt`) VALUES(:username, :password, :passwordSalt)");
  408. }else{
  409. /* if there are other fields to add value to, make the query and bind values according to it */
  410. $keys = array_keys($other);
  411. $columns = implode(",", $keys);
  412. $colVals = implode(",:", $keys);
  413. $sql = self::$dbh->prepare("INSERT INTO `". self::$config['db']['table'] ."` (`username`, `password`, `password_salt`, $columns) VALUES(:username, :password, :passwordSalt, :$colVals)");
  414. foreach($other as $key => $value){
  415. $value = htmlspecialchars($value);
  416. $sql->bindValue(":$key", $value);
  417. }
  418. }
  419. /* Bind the default values */
  420. $sql->bindValue(":username", $id);
  421. $sql->bindValue(":password", $saltedPass);
  422. $sql->bindValue(":passwordSalt", $randomSalt);
  423. $sql->execute();
  424. return true;
  425. }
  426. }
  427.  
  428. /**
  429. * Logout the current logged in user by deleting the cookies and destroying session
  430. */
  431. public static function logout(){
  432. self::construct("logout");
  433. session_destroy();
  434. setcookie("logSyslogin", "", time()-3600, self::$config['cookies']['path'], self::$config['cookies']['domain']);
  435. setcookie("logSysrememberMe", "", time()-3600, self::$config['cookies']['path'], self::$config['cookies']['domain']);
  436. self::redirect(self::$config['pages']['login_page']);
  437. return true;
  438. }
  439.  
  440. /**
  441. * A function to handle the Forgot Password process
  442. */
  443. public static function forgotPassword(){
  444. self::construct();
  445. $curStatus = "initial"; // The Current Status of Forgot Password process
  446. $identName = self::$config['features']['email_login'] === false ? "Username" : "Username / E-Mail";
  447.  
  448. if( !isset($_POST['logSysForgotPass']) && !isset($_GET['resetPassToken']) && !isset($_POST['logSysForgotPassChange']) ){
  449. $html = '<form action="'. self::curPageURL() .'" method="POST">';
  450. $html .= "<label>";
  451. $html .= "<p>{$identName}</p>";
  452. $html .= "<input type='text' id='logSysIdentification' placeholder='Enter your {$identName}' size='25' name='identification' />";
  453. $html .= "</label>";
  454. $html .= "<p><button name='logSysForgotPass' type='submit'>Reset Password</button></p>";
  455. $html .= "</form>";
  456. echo $html;
  457. /**
  458. * The user had moved to the reset password form ie she/he is currently seeing the forgot password form
  459. */
  460. $curStatus = "resetPasswordForm";
  461. }elseif( isset($_GET['resetPassToken']) && !isset($_POST['logSysForgotPassChange']) ){
  462. /**
  463. * The user gave the password reset token. Check if the token is valid.
  464. */
  465. $reset_pass_token = urldecode($_GET['resetPassToken']);
  466. $sql = self::$dbh->prepare("SELECT `uid` FROM `resetTokens` WHERE `token` = ?");
  467. $sql->execute(array($reset_pass_token));
  468.  
  469. if($sql->rowCount() == 0 || $reset_pass_token == ""){
  470. echo "<h3>Error : Wrong/Invalid Token</h3>";
  471. $curStatus = "invalidToken"; // The token user gave was not valid
  472. }else{
  473. /**
  474. * The token is valid, display the new password form
  475. */
  476. $html = "<p>The Token key was Authorized. Now, you can change the password</p>";
  477. $html .= "<form action='{$_SERVER['PHP_SELF']}' method='POST'>";
  478. $html .= "<input type='hidden' name='token' value='{$reset_pass_token}' />";
  479. $html .= "<label>";
  480. $html .= "<p>New Password</p>";
  481. $html .= "<input type='password' name='logSysForgotPassNewPassword' />";
  482. $html .= "</label><br/>";
  483. $html .= "<label>";
  484. $html .= "<p>Retype Password</p>";
  485. $html .= "<input type='password' name='logSysForgotPassRetypedPassword'/>";
  486. $html .= "</label><br/>";
  487. $html .= "<p><button name='logSysForgotPassChange'>Reset Password</button></p>";
  488. $html .= "</form>";
  489. echo $html;
  490. /**
  491. * The token was correct, displayed the change/new password form
  492. */
  493. $curStatus = "changePasswordForm";
  494. }
  495. }elseif(isset($_POST['logSysForgotPassChange']) && isset($_POST['logSysForgotPassNewPassword']) && isset($_POST['logSysForgotPassRetypedPassword'])){
  496. $reset_pass_token = urldecode($_POST['token']);
  497. $sql = self::$dbh->prepare("SELECT `uid` FROM `resetTokens` WHERE `token` = ?");
  498. $sql->execute(array($reset_pass_token));
  499.  
  500. if( $sql->rowCount() == 0 || $reset_pass_token == "" ){
  501. echo "<h3>Error : Wrong/Invalid Token</h3>";
  502. $curStatus = "invalidToken"; // The token user gave was not valid
  503. }else{
  504. if($_POST['logSysForgotPassNewPassword'] == "" || $_POST['logSysForgotPassRetypedPassword'] == ""){
  505. echo "<h3>Error : Passwords Fields Left Blank</h3>";
  506. $curStatus = "fieldsLeftBlank";
  507. }elseif( $_POST['logSysForgotPassNewPassword'] != $_POST['logSysForgotPassRetypedPassword'] ){
  508. echo "<h3>Error : Passwords Don't Match</h3>";
  509. $curStatus = "passwordDontMatch"; // The new password and retype password submitted didn't match
  510. }else{
  511. /**
  512. * We must create a fake assumption that the user is logged in to
  513. * change the password as \Fr\LS::changePassword()
  514. * requires the user to be logged in.
  515. */
  516. self::$user = $sql->fetchColumn();
  517. self::$loggedIn = true;
  518.  
  519. if(self::changePassword("", $_POST['logSysForgotPassNewPassword'])){
  520. self::$user = false;
  521. self::$loggedIn = false;
  522.  
  523. /**
  524. * The token shall not be used again, so remove it.
  525. */
  526. $sql = self::$dbh->prepare("DELETE FROM `resetTokens` WHERE `token` = ?");
  527. $sql->execute(array($reset_pass_token));
  528.  
  529. echo "<h3>Success : Password Reset Successful</h3><p>You may now login with your new password.</p>";
  530. $curStatus = "passwordChanged"; // The password was successfully changed
  531. }
  532. }
  533. }
  534. }elseif(isset($_POST['identification'])){
  535. /**
  536. * Check if username/email is provided and if it's valid and exists
  537. */
  538. $identification = $_POST['identification'];
  539. if($identification == ""){
  540. echo "<h3>Error : {$identName} not provided</h3>";
  541. $curStatus = "identityNotProvided"; // The identity was not given
  542. }else{
  543. $sql = self::$dbh->prepare("SELECT `email`, `id` FROM `". self::$config['db']['table'] ."` WHERE `username`=:login OR `email`=:login");
  544. $sql->bindValue(":login", $identification);
  545. $sql->execute();
  546. if($sql->rowCount() == 0){
  547. echo "<h3>Error : User Not Found</h3>";
  548. $curStatus = "userNotFound"; // The user with the identity given was not found in the users database
  549. }else{
  550. $rows = $sql->fetch(\PDO::FETCH_ASSOC);
  551. $email = $rows['email'];
  552. $uid = $rows['id'];
  553.  
  554. /**
  555. * Make token and insert into the table
  556. */
  557. $token = self::rand_string(40);
  558. $sql = self::$dbh->prepare("INSERT INTO `resetTokens` (`token`, `uid`, `requested`) VALUES (?, ?, NOW())");
  559. $sql->execute(array($token, $uid));
  560. $encodedToken = urlencode($token);
  561.  
  562. /**
  563. * Prepare the email to be sent
  564. */
  565. $subject = "Reset Password";
  566. $body = "You requested for resetting your password on ". self::$config['info']['company'] .". For this, please click the following link :
  567. <blockquote>
  568. <a href='". self::curPageURL() ."?resetPassToken={$encodedToken}'>Reset Password : {$token}</a>
  569. </blockquote>";
  570. self::sendMail($email, $subject, $body);
  571.  
  572. echo "<p>An email has been sent to your email inbox with instructions. Check Your Mail Inbox and SPAM Folders.</p><p>You can close this window.</p>";
  573. $curStatus = "emailSent"; // E-Mail has been sent
  574. }
  575. }
  576. }
  577. return $curStatus;
  578. }
  579.  
  580. /**
  581. * A function that handles the logged in user to change her/his password
  582. */
  583. public static function changePassword($curpass, $newpass, $parent = ""){
  584. self::construct();
  585. if(self::$loggedIn){
  586. $randomSalt = self::rand_string(20);
  587. $saltedPass = hash('sha256', $newpass . self::$config['keys']['salt'] . $randomSalt);
  588. $sql = self::$dbh->prepare("UPDATE `". self::$config['db']['table'] ."` SET `password` = ?, `password_salt` = ? WHERE `id` = ?");
  589. $sql->execute(array($saltedPass, $randomSalt, self::$user));
  590. return true;
  591. }else{
  592. echo "<h3>Error : Not Logged In</h3>";
  593. return "notLoggedIn";
  594. }
  595. }
  596.  
  597. /**
  598. * Check if user exists with ther username/email given
  599. * $identification - Either email/username
  600. */
  601. public static function userExists($identification){
  602. self::construct();
  603. if(self::$config['features']['email_login'] === true){
  604. $query = "SELECT `id` FROM `". self::$config['db']['table'] ."` WHERE `username`=:login OR `email`=:login";
  605. }else{
  606. $query = "SELECT `id` FROM `". self::$config['db']['table'] ."` WHERE `username`=:login";
  607. }
  608. $sql = self::$dbh->prepare($query);
  609. $sql->execute(array(
  610. ":login" => $identification
  611. ));
  612. return $sql->rowCount() == 0 ? false : true;
  613. }
  614.  
  615. /**
  616. * Fetches data of user in database. Returns a single value or an
  617. * array of value according to parameteres given to the function
  618. */
  619. public static function getUser($what = "*", $user = null){
  620. self::construct();
  621. if($user == null){
  622. $user = self::$user;
  623. }
  624. if( is_array($what) ){
  625. $columns = implode("`,`", $what);
  626. $columns = "`{$columns}`";
  627. }else{
  628. $columns = $what != "*" ? "`$what`" : "*";
  629. }
  630.  
  631. $sql = self::$dbh->prepare("SELECT {$columns} FROM `". self::$config['db']['table'] ."` WHERE `id` = ? ORDER BY `id` LIMIT 1");
  632. $sql->execute(array($user));
  633.  
  634. $data = $sql->fetch(\PDO::FETCH_ASSOC);
  635. if( !is_array($what) ){
  636. $data = $what == "*" ? $data : $data[$what];
  637. }
  638. return $data;
  639. }
  640.  
  641. /**
  642. * Updates the info of user in DB
  643. */
  644. public static function updateUser($toUpdate = array(), $user = null){
  645. self::construct();
  646. if( is_array($toUpdate) && !isset($toUpdate['id']) ){
  647. if($user == null){
  648. $user = self::$user;
  649. }
  650. $columns = "";
  651. foreach($toUpdate as $k => $v){
  652. $columns .= "`$k` = :$k, ";
  653. }
  654. $columns = substr($columns, 0, -2); // Remove last ","
  655.  
  656. $sql = self::$dbh->prepare("UPDATE `". self::$config['db']['table'] ."` SET {$columns} WHERE `id`=:id");
  657. $sql->bindValue(":id", $user);
  658. foreach($toUpdate as $key => $value){
  659. $value = htmlspecialchars($value);
  660. $sql->bindValue(":$key", $value);
  661. }
  662. $sql->execute();
  663.  
  664. }else{
  665. return false;
  666. }
  667. }
  668.  
  669. /**
  670. * Returns a string which shows the time since the user has joined
  671. */
  672. public static function joinedSince($user = null){
  673. self::construct();
  674. if($user == null){
  675. $user = self::$user;
  676. }
  677. $created = self::getUser("created");
  678. $timeFirst = strtotime($created);
  679. $timeSecond = strtotime("now");
  680. $memsince = $timeSecond - strtotime($created);
  681. $regged = date("n/j/Y", strtotime($created));
  682.  
  683. if($memsince < 60) {
  684. $memfor = $memsince . " Seconds";
  685. }else if($memsince < 120){
  686. $memfor = floor ($memsince / 60) . " Minute";
  687. }else if($memsince < 3600 && $memsince > 120){
  688. $memfor = floor($memsince / 60) . " Minutes";
  689. }else if($memsince < 7200 && $memsince > 3600){
  690. $memfor = floor($memsince / 3600) . " Hour";
  691. }else if($memsince < 86400 && $memsince > 3600){
  692. $memfor = floor($memsince / 3600) . " Hours";
  693. }else if($memsince < 172800){
  694. $memfor = floor($memsince / 86400) . " Day";
  695. }else if($memsince < 604800 && $memsince > 172800){
  696. $memfor = floor($memsince / 86400) . " Days";
  697. }else if($memsince < 1209600 && $memsince > 604800){
  698. $memfor = floor($memsince / 604800) . " Week";
  699. }else if($memsince < 2419200 && $memsince > 1209600){
  700. $memfor = floor($memsince / 604800) . " Weeks";
  701. }else if($memsince < 4838400){
  702. $memfor = floor($memsince / 2419200) . " Month";
  703. }else if($memsince < 31536000 && $memsince > 4838400){
  704. $memfor = floor($memsince / 2419200) . " Months";
  705. }else if($memsince < 63072000){
  706. $memfor = floor($memsince / 31536000) . " Year";
  707. }else if($memsince > 63072000){
  708. $memfor = floor($memsince / 31536000) . " Years";
  709. }
  710. return (string) $memfor;
  711. }
  712.  
  713. /**
  714. * ---------------------
  715. * Extra Tools/Functions
  716. * ---------------------
  717. */
  718.  
  719. /**
  720. * Check if E-Mail is valid
  721. */
  722. public static function validEmail($email = ""){
  723. return filter_var($email, FILTER_VALIDATE_EMAIL);
  724. }
  725.  
  726. /**
  727. * Get the current page URL
  728. */
  729. public static function curPageURL() {
  730. $pageURL = 'http';
  731. if(isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on"){$pageURL .= "s";}
  732. $pageURL .= "://";
  733. if($_SERVER["SERVER_PORT"] != "80") {
  734. $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
  735. }else{
  736. $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
  737. }
  738. return $pageURL;
  739. }
  740.  
  741. /**
  742. * Generate a Random String
  743.  
  744. */
  745. public static function rand_string($length) {
  746. $random_str = "";
  747. $chars = "subinsblogabcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  748. $size = strlen($chars) - 1;
  749. for($i = 0;$i < $length;$i++) {
  750. $random_str .= $chars[rand(0, $size)];
  751. }
  752. return $random_str;
  753. }
  754.  
  755. /**
  756. * Get the current page path.
  757. * Eg: /mypage, /folder/mypage.php
  758. */
  759. public static function curPage(){
  760. $parts = parse_url(self::curPageURL());
  761. return $parts["path"];
  762. }
  763.  
  764. /**
  765. * Do a redirect
  766. */
  767. public static function redirect($url, $status = 302){
  768. header("Location: $url", true, $status);
  769. exit;
  770. }
  771.  
  772. /**
  773. * Any mails need to be sent by logSys goes to here
  774. */
  775. public static function sendMail($email, $subject, $body){
  776. /**
  777. * Change this to something else if you don't like PHP's mail()
  778. */
  779. $headers = array();
  780. $headers[] = "MIME-Version: 1.0";
  781. $headers[] = "Content-type: text/html; charset=iso-8859-1";
  782. $headers[] = "From: ". self::$config['info']['email'];
  783. $headers[] = "Reply-To: ". self::$config['info']['email'];
  784. mail($email, $subject, $body, implode("\r\n", $headers));
  785. }
  786.  
  787. /**
  788. * -------------------------
  789. * End Extra Tools/Functions
  790. * -------------------------
  791. */
  792. }
Advertisement
Add Comment
Please, Sign In to add comment