user.php 47 KB

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