user.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. <?php
  2. /**
  3. * A framework for simple user authentication.
  4. *
  5. * Users are recorded using {username, password, token} triplets.
  6. * Whenever a user logs in successfully, his or her database
  7. * entry is assigned a new random token, which is used in
  8. * salting subsequent password checks.
  9. */
  10. $databaseConfig = parse_ini_file('databaseLocation.ini.php', true);
  11. define('USER_HOME', $databaseConfig['databaseLocation'] . '/users/');
  12. define('DATABASE_LOCATION', $databaseConfig['databaseLocation'] . '/');
  13. if(!empty($databaseConfig['timezone'])) : define('TIMEZONE', $databaseConfig['timezone']); else : define('TIMEZONE', 'America/Los_Angeles'); endif;
  14. if(!empty($databaseConfig['titleLogo'])) : define('TITLELOGO', $databaseConfig['titleLogo']); else : define('TITLELOGO', ''); endif;
  15. if(!empty($databaseConfig['loadingIcon'])) : define('LOADINGICON', $databaseConfig['loadingIcon']); else : define('LOADINGICON', ''); endif;
  16. if(!empty($databaseConfig['multipleLogin'])) : define('MULTIPLELOGIN', $databaseConfig['multipleLogin']); else : define('MULTIPLELOGIN', 'false'); endif;
  17. if(!empty($databaseConfig['enableMail'])) : define('ENABLEMAIL', $databaseConfig['enableMail']); else : define('ENABLEMAIL', 'false'); endif;
  18. if(!empty($databaseConfig['loadingScreen'])) : define('LOADINGSCREEN', $databaseConfig['loadingScreen']); else : define('LOADINGSCREEN', 'true'); endif;
  19. if(!empty($databaseConfig['slimBar'])) : define('SLIMBAR', $databaseConfig['slimBar']); else : define('SLIMBAR', 'true'); endif;
  20. if(!empty($databaseConfig['cookiePassword'])) : define('COOKIEPASSWORD', $databaseConfig['cookiePassword']); else : define('COOKIEPASSWORD', ''); endif;
  21. if(!empty($databaseConfig['registerPassword'])) : define('REGISTERPASSWORD', $databaseConfig['registerPassword']); else : define('REGISTERPASSWORD', ''); endif;
  22. if(!empty($databaseConfig['notifyEffect'])) : define('NOTIFYEFFECT', $databaseConfig['notifyEffect']); else : define('NOTIFYEFFECT', 'bar-slidetop'); endif;
  23. $notifyExplode = explode("-", NOTIFYEFFECT);
  24. define('FAIL_LOG', 'loginLog.json');
  25. date_default_timezone_set(TIMEZONE);
  26. class User
  27. {
  28. // =======================================================================
  29. // IMPORTANT VALUES THAT YOU *NEED* TO CHANGE FOR THIS TO BE SECURE
  30. // =======================================================================
  31. // Keeping this location on ./... means that it will be publically visible to all,
  32. // and you need to use htaccess rules or some such to ensure no one
  33. // grabs your user's data.
  34. //const USER_HOME = "../users/";
  35. // In order for users to be notified by email of certain things, set this to true.
  36. // Note that the server you run this on should have sendmail in order for
  37. // notification emails to work. Also note that password resetting doesn't work
  38. // unless mail notification is turned on.
  39. const use_mail = ENABLEMAIL;
  40. // This value should point to a directory that is not available to web users.
  41. // If your documents are in ./public_html, for instance., then put database
  42. // in something like ./database - that way, you don't have to rely on
  43. // htaccess rules or the likes, because it's simply impossible to get to the
  44. // database from a public, or private, URL.
  45. //
  46. // By default it's set to the stupidly dangerous and publically accessible same
  47. // base dir as your web page. So change it, because people are going to try
  48. // to download your database file. And succeed.
  49. //const DATABASE_LOCATION = "../";
  50. // if this is set to "true", registration failure due to known usernames is reported,
  51. // and login failures are explained as either the wrong username or the wrong password.
  52. // You really want to set this to 'false', but it's on true by default because goddamnit
  53. // I'm going to confront you with security issues right off the bat =)
  54. const unsafe_reporting = false;
  55. /**
  56. Think about security for a moment. On the one hand, you want your website
  57. to not reveal whether usernames are already taken, so when people log in
  58. you will want to say "username or password incorrect". However, you also want
  59. to be able to tell people that they can't register because the username they
  60. picked is already taken.
  61. Because these are mutually exclusive, you can't do both using this framework.
  62. You can either use unsafe reporting, where the system will will tell you that
  63. a username exists, both during registration and login, or you can use safe
  64. reporting, and then the system will reject registrations based on username
  65. similarity, not exact match. But then it also won't say which of the username
  66. or password in a login attempt was incorrect.
  67. **/
  68. // =======================================================================
  69. // You can modify the following values, but they're not security related
  70. // =======================================================================
  71. // rename this to whatever you like
  72. const DATABASE_NAME = "users";
  73. // this is the session timeout. If someone hasn't performed any page requests
  74. // in [timeout] seconds, they're considered logged out.
  75. const time_out = 604800;
  76. // You'll probably want to change this to something sensible. If your site is
  77. // www.sockmonkey.com, then you want this to be "sockmonkey.com"
  78. const DOMAIN_NAME = "Organizr";
  79. // This is going to be the "from" address
  80. const MAILER_NAME = "noreply@organizr";
  81. // if you want people to be able to reply to a real address, override
  82. // this variable to "yourmail@somedomain.ext" here.
  83. const MAILER_REPLYTO = "noreply@organizr";
  84. // =======================================================================
  85. // Don't modify any variables beyond this point =)
  86. // =======================================================================
  87. // this is the global error message. If anything goes wrong, this tells you why.
  88. var $error = "";
  89. // progress log
  90. var $info_log = array();
  91. // Information logging
  92. function info($string) { $this->info_log[] = $string; }
  93. // error log
  94. var $error_log = array();
  95. // Error logging
  96. function error($string) { $this->error_log[] = $string; }
  97. // all possible values for a hexadecimal number
  98. var $hex = "0123456789abcdef";
  99. // all possible values for an ascii password, skewed a bit so the number to letter ratio is closer to 1:1
  100. var $ascii = "0a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6A7B8C9D0E1F2G3H4I5J6K7L8M9N0O1P2Q3R4S5T6U7V8W9X0Y1Z23456789";
  101. // the regular expression for email matching (see http://www.regular-expressions.info/email.html)
  102. const emailregexp = "/[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/";
  103. // the regular expression for SHA1 hash matching
  104. const sha1regexp = "/[0123456789abcdef]{40,40}/";
  105. // this will tell us whether the client that requested the page is authenticated or not.
  106. var $authenticated = false;
  107. // the guest user name
  108. const GUEST_USER = "guest user";
  109. // this will contain the user name for the user doing the page request
  110. var $username = User::GUEST_USER;
  111. // if this is a properly logged in user, this will contain the data directory location for this user
  112. var $userdir = false;
  113. // the user's email address, if logged in.
  114. var $email = "";
  115. // the user's role in the system
  116. var $role = "";
  117. // global database handle
  118. var $database = false;
  119. // class object constructor
  120. function __construct($registration_callback=false)
  121. {
  122. // session management comes first. Warnings are repressed with @ because it will warn if something else already called session_start()
  123. @session_start();
  124. if(!isset($_COOKIE['Organizr'])) {
  125. if (empty($_SESSION["username"]) || empty($_SESSION["token"])) $this->resetSession();
  126. }else{
  127. $_SESSION["username"] = $_COOKIE['OrganizrU'];
  128. }
  129. // file location for the user database
  130. $dbfile = DATABASE_LOCATION . User::DATABASE_NAME . ".db";
  131. // do we need to build a new database?
  132. $rebuild = false;
  133. if(!file_exists($dbfile)) { $rebuild = true;}
  134. // bind the database handler
  135. $this->database = new PDO("sqlite:" . $dbfile);
  136. // If we need to rebuild, the file will have been automatically made by the PDO call,
  137. // but we'll still need to define the user table before we can use the database.
  138. if($rebuild) { $this->rebuild_database($dbfile); }
  139. // finally, process the page request.
  140. $this->process($registration_callback);
  141. }
  142. // this function rebuilds the database if there is no database to work with yet
  143. function rebuild_database($dbfile)
  144. {
  145. $this->info("creating/rebuilding database as ".$dbfile);
  146. $this->database->beginTransaction();
  147. $create = "CREATE TABLE users (username TEXT UNIQUE, password TEXT, email TEXT UNIQUE, token TEXT, role TEXT, active TEXT, last TEXT);";
  148. $this->database->exec($create);
  149. $this->database->commit();
  150. }
  151. // process a page request
  152. function process(&$registration_callback=false)
  153. {
  154. $this->database->beginTransaction();
  155. if(isset($_POST["op"]))
  156. {
  157. $operation = $_POST["op"];
  158. // logging in or out, and dropping your registration, may change authentication status
  159. if($operation == "login") { $this->authenticated = $this->login(); }
  160. // logout and unregister will unset authentication if successful
  161. elseif($operation == "logout") { $this->authenticated = !$this->logout(); }
  162. elseif($operation == "unregister") { $this->authenticated = !$this->unregister(); }
  163. // anything else won't change authentication status.
  164. elseif($operation == "register") { $this->register($registration_callback); }
  165. elseif($operation == "update") { $this->update(); }
  166. // we only allow password resetting if we can send notification mails
  167. elseif($operation == "reset" && User::use_mail) { $this->reset_password(); }
  168. }
  169. // if the previous operations didn't authorise the current user,
  170. // see if they're already marked as authorised in the database.
  171. if(!$this->authenticated) {
  172. $username = $_SESSION["username"];
  173. if($username != User::GUEST_USER) {
  174. $this->authenticated = $this->authenticate_user($username,"");
  175. if($this->authenticated) { $this->mark_user_active($username); }}}
  176. // at this point we can make some globals available.
  177. $this->username = $_SESSION["username"];
  178. $this->userdir = ($this->username !=User::GUEST_USER? USER_HOME . $this->username : false);
  179. $this->email = $this->get_user_email($this->username);
  180. $this->role = $this->get_user_role($this->username);
  181. // clear database
  182. $this->database->commit();
  183. $this->database = null;
  184. }
  185. // ---------------------
  186. // validation passthroughs
  187. // ---------------------
  188. /**
  189. * Called when the requested POST operation is "login"
  190. */
  191. function login()
  192. {
  193. // get relevant values
  194. $username = $_POST["username"];
  195. $sha1 = $_POST["sha1"];
  196. $rememberMe = $_POST["rememberMe"];
  197. // step 1: someone could have bypassed the javascript validation, so validate again.
  198. if(!$this->validate_user_name($username)) {
  199. $this->info("<strong>log in error:</strong> user name did not pass validation");
  200. return false; }
  201. if(preg_match(User::sha1regexp, $sha1)==0) {
  202. $this->info("<strong>log in error:</strong> password did not pass validation");
  203. return false; }
  204. // step 2: if validation passed, log the user in
  205. if($rememberMe == "true") {
  206. return $this->login_user($username, $sha1, true);
  207. }else{
  208. return $this->login_user($username, $sha1, false);
  209. }
  210. }
  211. /**
  212. * Called when the requested POST operation is "logout"
  213. */
  214. function logout()
  215. {
  216. // get relevant value
  217. $username = $_POST["username"];
  218. // step 1: validate the user name.
  219. if(!$this->validate_user_name($username)) {
  220. $this->info("<strong>log in error:</strong> user name did not pass validation");
  221. return false; }
  222. // step 2: if validation passed, log the user out
  223. return $this->logout_user($username);
  224. }
  225. /**
  226. * Users should always have the option to unregister
  227. */
  228. function unregister()
  229. {
  230. // get relevant value
  231. $username = $_POST["username"];
  232. // step 1: validate the user name.
  233. if(!$this->validate_user_name($username)) {
  234. $this->info("<strong>unregistration error:</strong> user name did not pass validation");
  235. return false; }
  236. // step 2: if validation passed, drop the user from the system
  237. return $this->unregister_user($username);
  238. }
  239. /**
  240. * Called when the requested POST operation is "register"
  241. */
  242. function register(&$registration_callback=false)
  243. {
  244. // get relevant values
  245. $username = $_POST["username"];
  246. $email = $_POST["email"];
  247. $sha1 = $_POST["sha1"];
  248. $settings = $_POST["settings"];
  249. // step 1: someone could have bypassed the javascript validation, so validate again.
  250. if(!$this->validate_user_name($username)) {
  251. $this->info("<strong>registration error:</strong> user name did not pass validation");
  252. return false; }
  253. if(preg_match(User::emailregexp, $email)==0) {
  254. $this->info("<strong>registration error:</strong> email address did not pass validation");
  255. return false; }
  256. if(preg_match(User::sha1regexp, $sha1)==0) {
  257. $this->info("<strong>registration error:</strong> password did not pass validation");
  258. return false; }
  259. // step 2: if validation passed, register user
  260. $registered = $this->register_user($username, $email, $sha1, $registration_callback, $settings);
  261. if($registered && User::use_mail)
  262. {
  263. // send email notification
  264. $from = User::MAILER_NAME;
  265. $replyto = User::MAILER_REPLYTO;
  266. $domain_name = User::DOMAIN_NAME;
  267. $subject = User::DOMAIN_NAME . " registration";
  268. $body = <<<EOT
  269. Hi,
  270. this is an automated message to let you know that someone signed up at $domain_name with the user name "$username", using this email address as mailing address.
  271. Because of the way our user registration works, we have no idea which password was used to register this account (it gets one-way hashed by the browser before it is sent to our user registration system, so that we don't know your password either), so if you registered this account, hopefully you wrote your password down somewhere.
  272. However, if you ever forget your password, you can click the "I forgot my password" link in the log-in section for $domain_name and you will be sent an email containing a new, ridiculously long and complicated password that you can use to log in. You can change your password after logging in, but that's up to you. No one's going to guess it, or brute force it, but if other people can read your emails, it's generally a good idea to change passwords.
  273. If you were not the one to register this account, you can either contact us the normal way or —much easier— you can ask the system to reset the password for the account, after which you can simply log in with the temporary password and delete the account. That'll teach whoever pretended to be you not to mess with you!
  274. Of course, if you did register it yourself, welcome to $domain_name!
  275. - the $domain_name team
  276. EOT;
  277. $headers = "From: $from\r\n";
  278. $headers .= "Reply-To: $replyto\r\n";
  279. $headers .= "X-Mailer: PHP/" . phpversion();
  280. mail($email, $subject, $body, $headers);
  281. }
  282. return $registered;
  283. }
  284. /**
  285. * Called when the requested POST operation is "update"
  286. */
  287. function update()
  288. {
  289. // get relevant values
  290. @$username = trim($_POST["username"]);
  291. @$email = trim($_POST["email"]);
  292. @$sha1 = trim($_POST["sha1"]);
  293. @$role = trim($_POST["role"]);
  294. // step 1: someone could have bypassed the javascript validation, so validate again.
  295. if($email !="" && preg_match(User::emailregexp, $email)==0) {
  296. $this->info("<strong>registration error:</strong> email address did not pass validation");
  297. return false; }
  298. if($sha1 !="" && preg_match(User::sha1regexp, $sha1)==0) {
  299. $this->info("<strong>registration error:</strong> password did not pass validation");
  300. return false; }
  301. // step 2: if validation passed, update the user's information
  302. return $this->update_user($username, $email, $sha1, $role);
  303. }
  304. /**
  305. * Reset a user's password
  306. */
  307. function reset_password()
  308. {
  309. // get the email for which we should reset
  310. $email = $_POST["email"];
  311. // step 1: someone could have bypassed the javascript validation, so validate again.
  312. if(preg_match(User::emailregexp, $email)==0) {
  313. $this->info("email address did not pass validation");
  314. return false; }
  315. // step 2: if validation passed, see if there is a matching user, and reset the password if there is
  316. $newpassword = $this->random_ascii_string(64);
  317. $sha1 = sha1($newpassword);
  318. $query = "SELECT username, token FROM users WHERE email = '$email'";
  319. $username = "";
  320. $token = "";
  321. foreach($this->database->query($query) as $data) { $username = $data["username"]; $token = $data["token"]; break; }
  322. // step 2a: if there was no user to reset a password for, stop.
  323. if($username == "" || $token == "") return false;
  324. // step 2b: if there was a user to reset a password for, reset it.
  325. $dbpassword = $this->token_hash_password($username, $sha1, $token);
  326. $update = "UPDATE users SET password = '$dbpassword' WHERE email= '$email'";
  327. $this->database->exec($update);
  328. $this->info("Email has been sent with new password");
  329. // step 3: notify the user of the new password
  330. $from = User::MAILER_NAME;
  331. $replyto = User::MAILER_REPLYTO;
  332. $domain_name = User::DOMAIN_NAME;
  333. $subject = User::DOMAIN_NAME . " password reset request";
  334. $body = <<<EOT
  335. Hi,
  336. this is an automated message to let you know that someone requested a password reset for the $domain_name user account with user name "$username", which is linked to this email address.
  337. We've reset the password to the following 64 character string, so make sure to copy/paste it without any leading or trailing spaces:
  338. $newpassword
  339. If you didn't even know this account existed, now is the time to log in and delete it. How dare people use your email address to register accounts! Of course, if you did register it yourself, but you didn't request the reset, some jerk is apparently reset-spamming. We hope he gets run over by a steam shovel driven by rabid ocelots or something.
  340. Then again, it's far more likely that you did register this account, and you simply forgot the password so you asked for the reset yourself, in which case: here's your new password, and thank you for your patronage at $domain_name!
  341. - the $domain_name team
  342. EOT;
  343. $headers = "From: $from\r\n";
  344. $headers .= "Reply-To: $replyto\r\n";
  345. $headers .= "X-Mailer: PHP/" . phpversion();
  346. mail($email, $subject, $body, $headers);
  347. }
  348. // ------------------
  349. // specific functions
  350. // ------------------
  351. // session management: set session values
  352. function setSession($username, $token)
  353. {
  354. $_SESSION["username"]=$username;
  355. $_SESSION["token"]=$token;
  356. }
  357. // session management: reset session values
  358. function resetSession()
  359. {
  360. $_SESSION["username"] = User::GUEST_USER;
  361. $_SESSION["token"] = -1;
  362. unset($_COOKIE['Organizr']);
  363. setcookie('Organizr', '', time() - 3600, '/');
  364. unset($_COOKIE['OrganizrU']);
  365. setcookie('OrganizrU', '', time() - 3600, '/');
  366. unset($_COOKIE['cookiePassword']);
  367. setcookie("cookiePassword", '', time() - 3600, '/');
  368. }
  369. /**
  370. * Validate a username. Empty usernames or names
  371. * that are modified by making them SQL safe are
  372. * considered not validated.
  373. */
  374. function validate_user_name($username)
  375. {
  376. $cleaned = $this->clean_SQLite_string($username);
  377. $validated = ($cleaned != "" && $cleaned==$username);
  378. if(!$validated) { $this->error = "user name did not pass validation."; $this->error("user name did not pass validation."); }
  379. return $validated;
  380. }
  381. /**
  382. * Clean strings for SQL insertion as string in SQLite (single quote enclosed).
  383. * Note that if the cleaning changes the string, this system won't insert.
  384. * The validate_user_name() function will flag this as a validation failure and
  385. * the database operation is never carried out.
  386. */
  387. function clean_SQLite_string($string)
  388. {
  389. $search = array("'", "\\", ";");
  390. $replace = array('', '', '');
  391. return trim(str_replace($search, $replace, $string));
  392. }
  393. /**
  394. * Verify that the given username is allowed
  395. * to perform the given operation.
  396. */
  397. function authenticate_user($username, $operation)
  398. {
  399. // actually logged in?
  400. if($this->is_user_active($username)===false) { return false; }
  401. // logged in, but do the tokens match?
  402. $token = $this->get_user_token($username);
  403. if(MULTIPLELOGIN == "false"){
  404. if(isset($_COOKIE["Organizr"])){
  405. if($_COOKIE["Organizr"] == $token){
  406. return true;
  407. }else{
  408. $this->error("cookie token mismatch for $username");
  409. unset($_COOKIE['Organizr']);
  410. setcookie('Organizr', '', time() - 3600, '/');
  411. unset($_COOKIE['OrganizrU']);
  412. setcookie('OrganizrU', '', time() - 3600, '/');
  413. unset($_COOKIE['cookiePassword']);
  414. setcookie("cookiePassword", '', time() - 3600, '/');
  415. return false;
  416. }
  417. }else{
  418. if($token != $_SESSION["token"]) {
  419. $this->error("token mismatch for $username");
  420. return false;
  421. }
  422. // active, using the correct token -> authenticated
  423. return true;
  424. }
  425. }else{
  426. return true;
  427. }
  428. }
  429. /**
  430. * Unicode friendly(ish) version of strtolower
  431. * see: http://ca3.php.net/manual/en/function.strtolower.php#91805
  432. */
  433. function strtolower_utf8($string)
  434. {
  435. $convert_to = array( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
  436. "v", "w", "x", "y", "z", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï",
  437. "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "ø", "ù", "ú", "û", "ü", "ý", "а", "б", "в", "г", "д", "е", "ё", "ж",
  438. "з", "и", "й", "к", "л", "м", "н", "о", "п", "р", "с", "т", "у", "ф", "х", "ц", "ч", "ш", "щ", "ъ", "ы",
  439. "ь", "э", "ю", "я" );
  440. $convert_from = array( "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
  441. "V", "W", "X", "Y", "Z", "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï",
  442. "Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "А", "Б", "В", "Г", "Д", "Е", "Ё", "Ж",
  443. "З", "И", "Й", "К", "Л", "М", "Н", "О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ъ",
  444. "Ь", "Э", "Ю", "Я" );
  445. return str_replace($convert_from, $convert_to, $string);
  446. }
  447. /**
  448. * This functions flattens user name strings for similarity comparison purposes
  449. */
  450. function homogenise_username($string)
  451. {
  452. // cut off trailing numbers
  453. $string = preg_replace("/\d+$/", '', $string);
  454. // and then replace non-terminal numbers with
  455. // their usual letter counterparts.
  456. $s = array("1","3","4","5","7","8","0");
  457. $r = array("i","e","a","s","t","ate","o");
  458. $string = str_replace($s, $r, $string);
  459. // finally, collapse case
  460. return $this->strtolower_utf8($string);
  461. }
  462. /**
  463. * We don't require assloads of personal information.
  464. * A username and a password are all we want. The rest
  465. * is profile information that can be set, but in no way
  466. * needs to be, in the user's profile section
  467. */
  468. function register_user($username, $email, $sha1, &$registration_callback = false, $settings)
  469. {
  470. $dbpassword = $this->token_hash_password($username, $sha1, "");
  471. if($dbpassword==$sha1) die("password hashing is not implemented.");
  472. $newRole = "admin";
  473. $queryAdmin = "SELECT username FROM users";
  474. foreach($this->database->query($queryAdmin) as $data) {
  475. $newRole = "user";
  476. }
  477. // Does user already exist? (see notes on safe reporting)
  478. if(User::unsafe_reporting) {
  479. $query = "SELECT username FROM users WHERE username LIKE '$username'";
  480. foreach($this->database->query($query) as $data) {
  481. $this->info("user account for $username not created.");
  482. $this->error = "this user name is already being used by someone else.";
  483. $this->error("this user name is already being used by someone else.");
  484. return false; }}
  485. else{ $query = "SELECT username FROM users";
  486. $usernames = array();
  487. foreach($this->database->query($query) as $data) { $usernames[] = $this->homogenise_username($data["username"]); }
  488. if(in_array($this->homogenise_username($username), $usernames)) {
  489. //$this->info("user account for $username not created.");
  490. $this->error = "<strong>$username</strong> is not allowed, because it is too similar to other user names.";
  491. $this->error("<strong>$username</strong> is not allowed, because it is too similar to other user names.");
  492. return false; }}
  493. // Is email address already in use? (see notes on safe reporting)
  494. $query = "SELECT * FROM users WHERE email = '$email'";
  495. foreach($this->database->query($query) as $data) {
  496. $this->info("user account for $username not created.");
  497. $this->error = "this email address is already in use by someone else.";
  498. $this->error("this email address is already in use by someone else.");
  499. return false; }
  500. // This user can be registered
  501. $insert = "INSERT INTO users (username, email, password, token, role, active, last) ";
  502. $insert .= "VALUES ('$username', '$email', '$dbpassword', '', '$newRole', 'false', '') ";
  503. $this->database->exec($insert);
  504. $query = "SELECT * FROM users WHERE username = '$username'";
  505. foreach($this->database->query($query) as $data) {
  506. $this->info("created user account for $username");
  507. $this->update_user_token($username, $sha1, false);
  508. // make the user's data directory
  509. $dir = USER_HOME . $username;
  510. if(!mkdir($dir, 0760, true)) { $this->error("could not make user directory $dir"); return false; }
  511. //$this->info("created user directory $dir");
  512. // if there is a callback, call it
  513. if($registration_callback !== false) { $registration_callback($username, $email, $dir); }
  514. if($settings !== "true") { $this->login_user($username, $sha1, true); }
  515. return true; }
  516. $this->error = "unknown database error occured.";
  517. $this->error("unknown database error occured.");
  518. return false;
  519. }
  520. /**
  521. * Log a user in
  522. */
  523. function login_user($username, $sha1, $remember)
  524. {
  525. function buildLog($username, $authType){
  526. if(file_exists(FAIL_LOG)) {
  527. $getFailLog = str_replace("\r\ndate", "date", file_get_contents(FAIL_LOG));
  528. $gotFailLog = json_decode($getFailLog, true);
  529. }
  530. $failLogEntryFirst = array('logType' => 'login_log', 'auth' => array(array('date' => date("Y-m-d H:i:s"), 'username' => $username, 'ip' => $_SERVER['REMOTE_ADDR'], 'auth_type' => $authType)));
  531. $failLogEntry = array('date' => date("Y-m-d H:i:s"), 'username' => $username, 'ip' => $_SERVER['REMOTE_ADDR'], 'auth_type' => $authType);
  532. if(isset($gotFailLog)) {
  533. array_push($gotFailLog["auth"], $failLogEntry);
  534. $writeFailLog = str_replace("date", "\r\ndate", json_encode($gotFailLog));
  535. }else{
  536. $writeFailLog = str_replace("date", "\r\ndate", json_encode($failLogEntryFirst));
  537. }
  538. return $writeFailLog;
  539. }
  540. // transform sha1 into real password
  541. $dbpassword = $this->token_hash_password($username, $sha1, $this->get_user_token($username));
  542. if($dbpassword==$sha1) {
  543. $this->info("password hashing is not implemented.");
  544. return false; }
  545. // perform the authentication step
  546. $query = "SELECT password FROM users WHERE username = '$username'";
  547. foreach($this->database->query($query) as $data) {
  548. if($dbpassword==$data["password"]) {
  549. // authentication passed - 1) mark active and update token
  550. $this->mark_user_active($username);
  551. $this->setSession($username, $this->update_user_token($username, $sha1, false));
  552. // authentication passed - 2) signal authenticated
  553. if($remember == "true") {
  554. setcookie("Organizr", $this->get_user_token($username), time() + (86400 * 7), "/");
  555. setcookie("OrganizrU", $username, time() + (86400 * 7), "/");
  556. }
  557. $this->info("Welcome $username");
  558. file_put_contents(FAIL_LOG, buildLog($username, "good_auth"));
  559. chmod(FAIL_LOG, 0660);
  560. setcookie("cookiePassword", COOKIEPASSWORD, time() + (86400 * 7), "/");
  561. return true;
  562. }
  563. // authentication failed
  564. //$this->info("password mismatch for $username");
  565. file_put_contents(FAIL_LOG, buildLog($username, "bad_auth"));
  566. chmod(FAIL_LOG, 0660);
  567. if(User::unsafe_reporting) { $this->error = "incorrect password for $username."; $this->error("incorrect password for $username."); }
  568. else { $this->error = "the specified username/password combination is incorrect."; $this->error("the specified username/password combination is incorrect."); }
  569. return false; }
  570. // authentication could not take place
  571. //$this->info("there was no user $username in the database");
  572. file_put_contents(FAIL_LOG, buildLog($username, "bad_auth"));
  573. chmod(FAIL_LOG, 0660);
  574. if(User::unsafe_reporting) { $this->error = "user $username is unknown."; $this->error("user $username is unknown."); }
  575. else { $this->error = "you either did not correctly input your username, or password (... or both)."; $this->error("you either did not correctly input your username, or password (... or both)."); }
  576. return false;
  577. }
  578. /**
  579. * Update a user's information
  580. */
  581. function update_user($username, $email, $sha1, $role)
  582. {
  583. if($email !="") {
  584. $update = "UPDATE users SET email = '$email' WHERE username = '$username'";
  585. $this->database->exec($update); }
  586. if($role !="") {
  587. $update = "UPDATE users SET role = '$role' WHERE username = '$username'";
  588. $this->database->exec($update); }
  589. if($sha1 !="") {
  590. $dbpassword = $this->token_hash_password($username, $sha1, $this->get_user_token($username));
  591. $update = "UPDATE users SET password = '$dbpassword' WHERE username = '$username'";
  592. $this->database->exec($update); }
  593. $this->info("updated the information for <strong>$username</strong>");
  594. }
  595. /**
  596. * Log a user out.
  597. */
  598. function logout_user($username)
  599. {
  600. $update = "UPDATE users SET active = 'false' WHERE username = '$username'";
  601. $this->database->exec($update);
  602. $this->resetSession();
  603. $this->info("Buh-Bye <strong>$username</strong>!");
  604. unset($_COOKIE['Organizr']);
  605. setcookie('Organizr', '', time() - 3600, '/');
  606. unset($_COOKIE['OrganizrU']);
  607. setcookie('OrganizrU', '', time() - 3600, '/');
  608. unset($_COOKIE['cookiePassword']);
  609. setcookie("cookiePassword", '', time() - 3600, '/');
  610. return true;
  611. }
  612. /**
  613. * Drop a user from the system
  614. */
  615. function unregister_user($username)
  616. {
  617. $delete = "DELETE FROM users WHERE username = '$username'";
  618. $this->database->exec($delete);
  619. $this->info("<strong>$username</strong> has been kicked out of Organizr");
  620. //$this->resetSession();
  621. $dir = USER_HOME . $username;
  622. if(!rmdir($dir)) { $this->error("could not delete user directory $dir"); }
  623. $this->info("and we deleted user directory $dir");
  624. return true;
  625. }
  626. /**
  627. * The incoming password will already be a sha1 print (40 bytes) long,
  628. * but for the database we want it to be hased as sha256 (using 64 bytes).
  629. */
  630. function token_hash_password($username, $sha1, $token)
  631. {
  632. return hash("sha256", $username . $sha1 . $token);
  633. }
  634. /**
  635. * Get a user's email address
  636. */
  637. function get_user_email($username)
  638. {
  639. if($username && $username !="" && $username !=User::GUEST_USER) {
  640. $query = "SELECT email FROM users WHERE username = '$username'";
  641. foreach($this->database->query($query) as $data) { return $data["email"]; }}
  642. return "";
  643. }
  644. /**
  645. * Get a user's role
  646. */
  647. function get_user_role($username)
  648. {
  649. if($username && $username !="" && $username !=User::GUEST_USER) {
  650. $query = "SELECT role FROM users WHERE username = '$username'";
  651. foreach($this->database->query($query) as $data) { return $data["role"]; }}
  652. return User::GUEST_USER;
  653. }
  654. /**
  655. * Get the user token
  656. */
  657. function get_user_token($username)
  658. {
  659. $query = "SELECT token FROM users WHERE username = '$username'";
  660. foreach($this->database->query($query) as $data) { return $data["token"]; }
  661. return false;
  662. }
  663. /**
  664. * Update the user's token and password upon successful login
  665. */
  666. function update_user_token($username, $sha1, $noMsg)
  667. {
  668. // update the user's token
  669. $token = $this->random_hex_string(32);
  670. $update = "UPDATE users SET token = '$token' WHERE username = '$username'";
  671. $this->database->exec($update);
  672. // update the user's password
  673. $newpassword = $this->token_hash_password($username, $sha1, $token);
  674. $update = "UPDATE users SET password = '$newpassword' WHERE username = '$username'";
  675. $this->database->exec($update);
  676. if($noMsg == "false"){
  677. $this->info("token and password updated for <strong>$username</strong>");
  678. }
  679. return $token;
  680. }
  681. /**
  682. * Mark a user as active.
  683. */
  684. function mark_user_active($username)
  685. {
  686. $update = "UPDATE users SET active = 'true', last = '" . time() . "' WHERE username = '$username'";
  687. $this->database->exec($update);
  688. //$this->info("$username has been marked currently active.");
  689. return true;
  690. }
  691. /**
  692. * Check if user can be considered active
  693. */
  694. function is_user_active($username)
  695. {
  696. $last = 0;
  697. $active = "false";
  698. $query = "SELECT last, active FROM users WHERE username = '$username'";
  699. foreach($this->database->query($query) as $data) {
  700. $last = intval($data["last"]);
  701. $active = $data["active"];
  702. break; }
  703. if($active=="true") {
  704. $diff = time() - $last;
  705. if($diff >= User::time_out) {
  706. $this->logout_user($username);
  707. $this->error("$username was active but timed out (timeout set at " . User::time_out . " seconds, difference was $diff seconds)");
  708. return false; }
  709. //$this->info("$username is active");
  710. return true; }
  711. $this->error("<strong>$username</strong> is not active");
  712. $this->resetSession();
  713. return false;
  714. }
  715. /**
  716. * Random hex string generator
  717. */
  718. function random_hex_string($len)
  719. {
  720. $string = "";
  721. $max = strlen($this->hex)-1;
  722. while($len-->0) { $string .= $this->hex[mt_rand(0, $max)]; }
  723. return $string;
  724. }
  725. /**
  726. * Random password string generator
  727. */
  728. function random_ascii_string($len)
  729. {
  730. $string = "";
  731. $max = strlen($this->ascii)-1;
  732. while($len-->0) { $string .= $this->ascii[mt_rand(0, $max)]; }
  733. return $string;
  734. }
  735. }
  736. ?>