user.php 40 KB

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