user.php 38 KB

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