4
0

user.php 40 KB

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