user.php 43 KB

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