3 * Authentication library
5 * Including this file will automatically try to login
6 * a user by calling auth_login()
8 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
9 * @author Andreas Gohr <andi@splitbrain.org>
12 if(!defined('DOKU_INC')) die('meh.');
14 // some ACL level defines
15 define('AUTH_NONE', 0);
16 define('AUTH_READ', 1);
17 define('AUTH_EDIT', 2);
18 define('AUTH_CREATE', 4);
19 define('AUTH_UPLOAD', 8);
20 define('AUTH_DELETE', 16);
21 define('AUTH_ADMIN', 255);
24 * Initialize the auth system.
26 * This function is automatically called at the end of init.php
28 * This used to be the main() of the auth.php
30 * @todo backend loading maybe should be handled by the class autoloader
31 * @todo maybe split into multiple functions at the XXX marked positions
32 * @triggers AUTH_LOGIN_CHECK
35 function auth_setup() {
37 /* @var auth_basic $auth */
39 /* @var Input $INPUT */
45 if(!$conf['useacl']) return false;
47 // load the the backend auth functions and instantiate the auth object XXX
48 if(@file_exists(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php')) {
49 require_once(DOKU_INC.'inc/auth/basic.class.php');
50 require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php');
52 $auth_class = "auth_".$conf['authtype'];
53 if(class_exists($auth_class)) {
54 $auth = new $auth_class();
55 if($auth->success == false) {
56 // degrade to unauthenticated user
59 msg($lang['authtempfail'], -1);
62 nice_die($lang['authmodfailed']);
65 nice_die($lang['authmodfailed']);
68 if(!isset($auth) || !$auth) return false;
70 // do the login either by cookie or provided credentials XXX
71 $INPUT->set('http_credentials', false);
72 if(!$conf['rememberme']) $INPUT->set('r', false);
74 // handle renamed HTTP_AUTHORIZATION variable (can happen when a fix like
75 // the one presented at
76 // http://www.besthostratings.com/articles/http-auth-php-cgi.html is used
77 // for enabling HTTP authentication with CGI/SuExec)
78 if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
79 $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
80 // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
81 if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
82 list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
83 explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
86 // if no credentials were given try to use HTTP auth (for SSO)
87 if(!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])) {
88 $INPUT->set('u', $_SERVER['PHP_AUTH_USER']);
89 $INPUT->set('p', $_SERVER['PHP_AUTH_PW']);
90 $INPUT->set('http_credentials', true);
94 $INPUT->set('u', $auth->cleanUser($INPUT->str('u')));
96 if($INPUT->str('authtok')) {
97 // when an authentication token is given, trust the session
98 auth_validateToken($INPUT->str('authtok'));
99 } elseif(!is_null($auth) && $auth->canDo('external')) {
100 // external trust mechanism in place
101 $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
104 'user' => $INPUT->str('u'),
105 'password' => $INPUT->str('p'),
106 'sticky' => $INPUT->bool('r'),
107 'silent' => $INPUT->bool('http_credentials')
109 trigger_event('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
112 //load ACL into a global array XXX
113 $AUTH_ACL = auth_loadACL();
119 * Loads the ACL setup and handle user wildcards
121 * @author Andreas Gohr <andi@splitbrain.org>
124 function auth_loadACL() {
125 global $config_cascade;
128 if(!is_readable($config_cascade['acl']['default'])) return array();
130 $acl = file($config_cascade['acl']['default']);
132 //support user wildcard
134 foreach($acl as $line) {
136 if($line{0} == '#') continue;
137 list($id,$rest) = preg_split('/\s+/',$line,2);
139 if(strstr($line, '%GROUP%')){
140 foreach((array) $USERINFO['grps'] as $grp){
141 $nid = str_replace('%GROUP%',cleanID($grp),$id);
142 $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest);
143 $out[] = "$nid\t$nrest";
146 $id = str_replace('%USER%',cleanID($_SERVER['REMOTE_USER']),$id);
147 $rest = str_replace('%USER%',auth_nameencode($_SERVER['REMOTE_USER']),$rest);
148 $out[] = "$id\t$rest";
156 * Event hook callback for AUTH_LOGIN_CHECK
161 function auth_login_wrapper($evdata) {
171 * This tries to login the user based on the sent auth credentials
173 * The authentication works like this: if a username was given
174 * a new login is assumed and user/password are checked. If they
175 * are correct the password is encrypted with blowfish and stored
176 * together with the username in a cookie - the same info is stored
177 * in the session, too. Additonally a browserID is stored in the
180 * If no username was given the cookie is checked: if the username,
181 * crypted password and browserID match between session and cookie
182 * no further testing is done and the user is accepted
184 * If a cookie was found but no session info was availabe the
185 * blowfish encrypted password from the cookie is decrypted and
186 * together with username rechecked by calling this function again.
188 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
191 * @author Andreas Gohr <andi@splitbrain.org>
193 * @param string $user Username
194 * @param string $pass Cleartext Password
195 * @param bool $sticky Cookie should not expire
196 * @param bool $silent Don't show error on bad auth
197 * @return bool true on successful auth
199 function auth_login($user, $pass, $sticky = false, $silent = false) {
203 /* @var auth_basic $auth */
206 $sticky ? $sticky = true : $sticky = false; //sanity check
208 if(!$auth) return false;
212 if($auth->checkPass($user, $pass)) {
213 // make logininfo globally available
214 $_SERVER['REMOTE_USER'] = $user;
215 $secret = auth_cookiesalt(!$sticky); //bind non-sticky to session
216 auth_setCookie($user, PMA_blowfish_encrypt($pass, $secret), $sticky);
219 //invalid credentials - log off
220 if(!$silent) msg($lang['badlogin'], -1);
225 // read cookie information
226 list($user, $sticky, $pass) = auth_getCookie();
228 // we got a cookie - see if we can trust it
231 $session = $_SESSION[DOKU_COOKIE]['auth'];
232 if(isset($session) &&
233 $auth->useSessionCache($user) &&
234 ($session['time'] >= time() - $conf['auth_security_timeout']) &&
235 ($session['user'] == $user) &&
236 ($session['pass'] == sha1($pass)) && //still crypted
237 ($session['buid'] == auth_browseruid())
240 // he has session, cookie and browser right - let him in
241 $_SERVER['REMOTE_USER'] = $user;
242 $USERINFO = $session['info']; //FIXME move all references to session
245 // no we don't trust it yet - recheck pass but silent
246 $secret = auth_cookiesalt(!$sticky); //bind non-sticky to session
247 $pass = PMA_blowfish_decrypt($pass, $secret);
248 return auth_login($user, $pass, $sticky, true);
257 * Checks if a given authentication token was stored in the session
259 * Will setup authentication data using data from the session if the
260 * token is correct. Will exit with a 401 Status if not.
262 * @author Andreas Gohr <andi@splitbrain.org>
263 * @param string $token The authentication token
264 * @return boolean true (or will exit on failure)
266 function auth_validateToken($token) {
267 if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']) {
269 header("HTTP/1.0 401 Unauthorized");
270 print 'Invalid auth token - maybe the session timed out';
271 unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
274 // still here? trust the session data
276 $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
277 $USERINFO = $_SESSION[DOKU_COOKIE]['auth']['info'];
282 * Create an auth token and store it in the session
284 * NOTE: this is completely unrelated to the getSecurityToken() function
286 * @author Andreas Gohr <andi@splitbrain.org>
287 * @return string The auth token
289 function auth_createToken() {
290 $token = md5(mt_rand());
291 @session_start(); // reopen the session if needed
292 $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
293 session_write_close();
298 * Builds a pseudo UID from browser and IP data
300 * This is neither unique nor unfakable - still it adds some
301 * security. Using the first part of the IP makes sure
302 * proxy farms like AOLs are stil okay.
304 * @author Andreas Gohr <andi@splitbrain.org>
306 * @return string a MD5 sum of various browser headers
308 function auth_browseruid() {
309 $ip = clientIP(true);
311 $uid .= $_SERVER['HTTP_USER_AGENT'];
312 $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
313 $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
314 $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
315 $uid .= substr($ip, 0, strpos($ip, '.'));
320 * Creates a random key to encrypt the password in cookies
322 * This function tries to read the password for encrypting
323 * cookies from $conf['metadir'].'/_htcookiesalt'
324 * if no such file is found a random key is created and
325 * and stored in this file.
327 * @author Andreas Gohr <andi@splitbrain.org>
328 * @param bool $addsession if true, the sessionid is added to the salt
331 function auth_cookiesalt($addsession = false) {
333 $file = $conf['metadir'].'/_htcookiesalt';
334 $salt = io_readFile($file);
336 $salt = uniqid(rand(), true);
337 io_saveFile($file, $salt);
340 $salt .= session_id();
346 * Log out the current user
348 * This clears all authentication data and thus log the user
349 * off. It also clears session data.
351 * @author Andreas Gohr <andi@splitbrain.org>
352 * @param bool $keepbc - when true, the breadcrumb data is not cleared
354 function auth_logoff($keepbc = false) {
357 /* @var auth_basic $auth */
360 // make sure the session is writable (it usually is)
363 if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
364 unset($_SESSION[DOKU_COOKIE]['auth']['user']);
365 if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
366 unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
367 if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
368 unset($_SESSION[DOKU_COOKIE]['auth']['info']);
369 if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
370 unset($_SESSION[DOKU_COOKIE]['bc']);
371 if(isset($_SERVER['REMOTE_USER']))
372 unset($_SERVER['REMOTE_USER']);
373 $USERINFO = null; //FIXME
375 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
376 if(version_compare(PHP_VERSION, '5.2.0', '>')) {
377 setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
379 setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
382 if($auth) $auth->logOff();
386 * Check if a user is a manager
388 * Should usually be called without any parameters to check the current
391 * The info is available through $INFO['ismanager'], too
393 * @author Andreas Gohr <andi@splitbrain.org>
395 * @param string $user Username
396 * @param array $groups List of groups the user is in
397 * @param bool $adminonly when true checks if user is admin
400 function auth_ismanager($user = null, $groups = null, $adminonly = false) {
403 /* @var auth_basic $auth */
406 if(!$auth) return false;
408 if(!isset($_SERVER['REMOTE_USER'])) {
411 $user = $_SERVER['REMOTE_USER'];
414 if(is_null($groups)) {
415 $groups = (array) $USERINFO['grps'];
418 // check superuser match
419 if(auth_isMember($conf['superuser'], $user, $groups)) return true;
420 if($adminonly) return false;
422 if(auth_isMember($conf['manager'], $user, $groups)) return true;
428 * Check if a user is admin
430 * Alias to auth_ismanager with adminonly=true
432 * The info is available through $INFO['isadmin'], too
434 * @author Andreas Gohr <andi@splitbrain.org>
435 * @see auth_ismanager()
436 * @param string $user Username
437 * @param array $groups List of groups the user is in
440 function auth_isadmin($user = null, $groups = null) {
441 return auth_ismanager($user, $groups, true);
445 * Match a user and his groups against a comma separated list of
446 * users and groups to determine membership status
448 * Note: all input should NOT be nameencoded.
450 * @param $memberlist string commaseparated list of allowed users and groups
451 * @param $user string user to match against
452 * @param $groups array groups the user is member of
453 * @return bool true for membership acknowledged
455 function auth_isMember($memberlist, $user, array $groups) {
456 /* @var auth_basic $auth */
458 if(!$auth) return false;
460 // clean user and groups
461 if(!$auth->isCaseSensitive()) {
462 $user = utf8_strtolower($user);
463 $groups = array_map('utf8_strtolower', $groups);
465 $user = $auth->cleanUser($user);
466 $groups = array_map(array($auth, 'cleanGroup'), $groups);
468 // extract the memberlist
469 $members = explode(',', $memberlist);
470 $members = array_map('trim', $members);
471 $members = array_unique($members);
472 $members = array_filter($members);
474 // compare cleaned values
475 foreach($members as $member) {
476 if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member);
477 if($member[0] == '@') {
478 $member = $auth->cleanGroup(substr($member, 1));
479 if(in_array($member, $groups)) return true;
481 $member = $auth->cleanUser($member);
482 if($member == $user) return true;
486 // still here? not a member!
491 * Convinience function for auth_aclcheck()
493 * This checks the permissions for the current user
495 * @author Andreas Gohr <andi@splitbrain.org>
497 * @param string $id page ID (needs to be resolved and cleaned)
498 * @return int permission level
500 function auth_quickaclcheck($id) {
503 # if no ACL is used always return upload rights
504 if(!$conf['useacl']) return AUTH_UPLOAD;
505 return auth_aclcheck($id, $_SERVER['REMOTE_USER'], $USERINFO['grps']);
509 * Returns the maximum rights a user has for
510 * the given ID or its namespace
512 * @author Andreas Gohr <andi@splitbrain.org>
514 * @param string $id page ID (needs to be resolved and cleaned)
515 * @param string $user Username
516 * @param array|null $groups Array of groups the user is in
517 * @return int permission level
519 function auth_aclcheck($id, $user, $groups) {
522 /* @var auth_basic $auth */
525 // if no ACL is used always return upload rights
526 if(!$conf['useacl']) return AUTH_UPLOAD;
527 if(!$auth) return AUTH_NONE;
529 //make sure groups is an array
530 if(!is_array($groups)) $groups = array();
532 //if user is superuser or in superusergroup return 255 (acl_admin)
533 if(auth_isadmin($user, $groups)) {
538 if(!$auth->isCaseSensitive()) $ci = 'ui';
540 $user = $auth->cleanUser($user);
541 $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
542 $user = auth_nameencode($user);
544 //prepend groups with @ and nameencode
545 $cnt = count($groups);
546 for($i = 0; $i < $cnt; $i++) {
547 $groups[$i] = '@'.auth_nameencode($groups[$i]);
553 if($user || count($groups)) {
557 if($user) $groups[] = $user;
562 //check exact match first
563 $matches = preg_grep('/^'.preg_quote($id, '/').'\s+(\S+)\s+/'.$ci, $AUTH_ACL);
564 if(count($matches)) {
565 foreach($matches as $match) {
566 $match = preg_replace('/#.*$/', '', $match); //ignore comments
567 $acl = preg_split('/\s+/', $match);
568 if(!in_array($acl[1], $groups)) {
571 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
572 if($acl[2] > $perm) {
577 //we had a match - return it
582 //still here? do the namespace checks
586 $path = '*'; //root document
590 $matches = preg_grep('/^'.preg_quote($path, '/').'\s+(\S+)\s+/'.$ci, $AUTH_ACL);
591 if(count($matches)) {
592 foreach($matches as $match) {
593 $match = preg_replace('/#.*$/', '', $match); //ignore comments
594 $acl = preg_split('/\s+/', $match);
595 if(!in_array($acl[1], $groups)) {
598 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
599 if($acl[2] > $perm) {
603 //we had a match - return it
608 //get next higher namespace
613 if($path == ':*') $path = '*';
615 //we did this already
616 //looks like there is something wrong with the ACL
618 msg('No ACL setup yet! Denying access to everyone.');
621 } while(1); //this should never loop endless
626 * Encode ASCII special chars
628 * Some auth backends allow special chars in their user and groupnames
629 * The special chars are encoded with this function. Only ASCII chars
630 * are encoded UTF-8 multibyte are left as is (different from usual
633 * Decoding can be done with rawurldecode
635 * @author Andreas Gohr <gohr@cosmocode.de>
636 * @see rawurldecode()
638 function auth_nameencode($name, $skip_group = false) {
639 global $cache_authname;
640 $cache =& $cache_authname;
641 $name = (string) $name;
643 // never encode wildcard FS#1955
644 if($name == '%USER%') return $name;
645 if($name == '%GROUP%') return $name;
647 if(!isset($cache[$name][$skip_group])) {
648 if($skip_group && $name{0} == '@') {
649 $cache[$name][$skip_group] = '@'.preg_replace(
650 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
651 "'%'.dechex(ord(substr('\\1',-1)))", substr($name, 1)
654 $cache[$name][$skip_group] = preg_replace(
655 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
656 "'%'.dechex(ord(substr('\\1',-1)))", $name
661 return $cache[$name][$skip_group];
665 * Create a pronouncable password
667 * @author Andreas Gohr <andi@splitbrain.org>
668 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451
670 * @return string pronouncable password
672 function auth_pwgen() {
674 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
675 $v = 'aeiou'; //vowels
678 //use two syllables...
679 for($i = 0; $i < 2; $i++) {
680 $pw .= $c[rand(0, strlen($c) - 1)];
681 $pw .= $v[rand(0, strlen($v) - 1)];
682 $pw .= $a[rand(0, strlen($a) - 1)];
684 //... and add a nice number
691 * Sends a password to the given user
693 * @author Andreas Gohr <andi@splitbrain.org>
694 * @param string $user Login name of the user
695 * @param string $password The new password in clear text
696 * @return bool true on success
698 function auth_sendPassword($user, $password) {
700 /* @var auth_basic $auth */
702 if(!$auth) return false;
704 $user = $auth->cleanUser($user);
705 $userinfo = $auth->getUserData($user);
707 if(!$userinfo['mail']) return false;
709 $text = rawLocale('password');
711 'FULLNAME' => $userinfo['name'],
713 'PASSWORD' => $password
716 $mail = new Mailer();
717 $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
718 $mail->subject($lang['regpwmail']);
719 $mail->setBody($text, $trep);
720 return $mail->send();
724 * Register a new user
726 * This registers a new user - Data is read directly from $_POST
728 * @author Andreas Gohr <andi@splitbrain.org>
729 * @return bool true on success, false on any error
731 function register() {
734 /* @var auth_basic $auth */
738 if(!$INPUT->post->bool('save')) return false;
739 if(!actionOK('register')) return false;
742 $login = trim($auth->cleanUser($INPUT->post->str('login')));
743 $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
744 $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
745 $pass = $INPUT->post->str('pass');
746 $passchk = $INPUT->post->str('passchk');
748 if(empty($login) || empty($fullname) || empty($email)) {
749 msg($lang['regmissing'], -1);
753 if($conf['autopasswd']) {
754 $pass = auth_pwgen(); // automatically generate password
755 } elseif(empty($pass) || empty($passchk)) {
756 msg($lang['regmissing'], -1); // complain about missing passwords
758 } elseif($pass != $passchk) {
759 msg($lang['regbadpass'], -1); // complain about misspelled passwords
764 if(!mail_isvalid($email)) {
765 msg($lang['regbadmail'], -1);
769 //okay try to create the user
770 if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) {
771 msg($lang['reguexists'], -1);
775 // create substitutions for use in notification email
776 $substitutions = array(
778 'NEWNAME' => $fullname,
779 'NEWEMAIL' => $email,
782 if(!$conf['autopasswd']) {
783 msg($lang['regsuccess2'], 1);
784 notify('', 'register', '', $login, false, $substitutions);
788 // autogenerated password? then send him the password
789 if(auth_sendPassword($login, $pass)) {
790 msg($lang['regsuccess'], 1);
791 notify('', 'register', '', $login, false, $substitutions);
794 msg($lang['regmailfail'], -1);
800 * Update user profile
802 * @author Christopher Smith <chris@jalakai.co.uk>
804 function updateprofile() {
807 /* @var auth_basic $auth */
809 /* @var Input $INPUT */
812 if(!$INPUT->post->bool('save')) return false;
813 if(!checkSecurityToken()) return false;
815 if(!actionOK('profile')) {
816 msg($lang['profna'], -1);
821 $changes['pass'] = $INPUT->post->str('newpass');
822 $changes['name'] = $INPUT->post->str('fullname');
823 $changes['mail'] = $INPUT->post->str('email');
825 // check misspelled passwords
826 if($changes['pass'] != $INPUT->post->str('passchk')) {
827 msg($lang['regbadpass'], -1);
831 // clean fullname and email
832 $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
833 $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
835 // no empty name and email (except the backend doesn't support them)
836 if((empty($changes['name']) && $auth->canDo('modName')) ||
837 (empty($changes['mail']) && $auth->canDo('modMail'))
839 msg($lang['profnoempty'], -1);
842 if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
843 msg($lang['regbadmail'], -1);
847 $changes = array_filter($changes);
849 // check for unavailable capabilities
850 if(!$auth->canDo('modName')) unset($changes['name']);
851 if(!$auth->canDo('modMail')) unset($changes['mail']);
852 if(!$auth->canDo('modPass')) unset($changes['pass']);
855 if(!count($changes)) {
856 msg($lang['profnochange'], -1);
860 if($conf['profileconfirm']) {
861 if(!$auth->checkPass($_SERVER['REMOTE_USER'], $INPUT->post->str('oldpass'))) {
862 msg($lang['badlogin'], -1);
867 if($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
868 // update cookie and session with the changed data
869 if($changes['pass']) {
870 list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
871 $pass = PMA_blowfish_encrypt($changes['pass'], auth_cookiesalt(!$sticky));
872 auth_setCookie($_SERVER['REMOTE_USER'], $pass, (bool) $sticky);
881 * Send a new password
883 * This function handles both phases of the password reset:
885 * - handling the first request of password reset
886 * - validating the password reset auth token
888 * @author Benoit Chesneau <benoit@bchesneau.info>
889 * @author Chris Smith <chris@jalakai.co.uk>
890 * @author Andreas Gohr <andi@splitbrain.org>
892 * @return bool true on success, false on any error
894 function act_resendpwd() {
897 /* @var auth_basic $auth */
899 /* @var Input $INPUT */
902 if(!actionOK('resendpwd')) {
903 msg($lang['resendna'], -1);
907 $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
910 // we're in token phase - get user info from token
912 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
913 if(!@file_exists($tfile)) {
914 msg($lang['resendpwdbadauth'], -1);
915 $INPUT->remove('pwauth');
918 // token is only valid for 3 days
919 if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
920 msg($lang['resendpwdbadauth'], -1);
921 $INPUT->remove('pwauth');
926 $user = io_readfile($tfile);
927 $userinfo = $auth->getUserData($user);
928 if(!$userinfo['mail']) {
929 msg($lang['resendpwdnouser'], -1);
933 if(!$conf['autopasswd']) { // we let the user choose a password
934 $pass = $INPUT->str('pass');
936 // password given correctly?
937 if(!$pass) return false;
938 if($pass != $INPUT->str('passchk')) {
939 msg($lang['regbadpass'], -1);
944 if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
945 msg('error modifying user data', -1);
949 } else { // autogenerate the password and send by mail
951 $pass = auth_pwgen();
952 if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
953 msg('error modifying user data', -1);
957 if(auth_sendPassword($user, $pass)) {
958 msg($lang['resendpwdsuccess'], 1);
960 msg($lang['regmailfail'], -1);
968 // we're in request phase
970 if(!$INPUT->post->bool('save')) return false;
972 if(!$INPUT->post->str('login')) {
973 msg($lang['resendpwdmissing'], -1);
976 $user = trim($auth->cleanUser($INPUT->post->str('login')));
979 $userinfo = $auth->getUserData($user);
980 if(!$userinfo['mail']) {
981 msg($lang['resendpwdnouser'], -1);
985 // generate auth token
986 $token = md5(auth_cookiesalt().$user); //secret but user based
987 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
988 $url = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
990 io_saveFile($tfile, $user);
992 $text = rawLocale('pwconfirm');
994 'FULLNAME' => $userinfo['name'],
999 $mail = new Mailer();
1000 $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1001 $mail->subject($lang['regpwmail']);
1002 $mail->setBody($text, $trep);
1004 msg($lang['resendpwdconfirm'], 1);
1006 msg($lang['regmailfail'], -1);
1014 * Encrypts a password using the given method and salt
1016 * If the selected method needs a salt and none was given, a random one
1019 * @author Andreas Gohr <andi@splitbrain.org>
1020 * @param string $clear The clear text password
1021 * @param string $method The hashing method
1022 * @param string $salt A salt, null for random
1023 * @return string The crypted password
1025 function auth_cryptPassword($clear, $method = '', $salt = null) {
1027 if(empty($method)) $method = $conf['passcrypt'];
1029 $pass = new PassHash();
1030 $call = 'hash_'.$method;
1032 if(!method_exists($pass, $call)) {
1033 msg("Unsupported crypt method $method", -1);
1037 return $pass->$call($clear, $salt);
1041 * Verifies a cleartext password against a crypted hash
1043 * @author Andreas Gohr <andi@splitbrain.org>
1044 * @param string $clear The clear text password
1045 * @param string $crypt The hash to compare with
1046 * @return bool true if both match
1048 function auth_verifyPassword($clear, $crypt) {
1049 $pass = new PassHash();
1050 return $pass->verify_hash($clear, $crypt);
1054 * Set the authentication cookie and add user identification data to the session
1056 * @param string $user username
1057 * @param string $pass encrypted password
1058 * @param bool $sticky whether or not the cookie will last beyond the session
1061 function auth_setCookie($user, $pass, $sticky) {
1063 /* @var auth_basic $auth */
1067 if(!$auth) return false;
1068 $USERINFO = $auth->getUserData($user);
1071 $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
1072 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1073 $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1074 if(version_compare(PHP_VERSION, '5.2.0', '>')) {
1075 setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
1077 setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
1080 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1081 $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1082 $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1083 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1084 $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1090 * Returns the user, (encrypted) password and sticky bit from cookie
1094 function auth_getCookie() {
1095 if(!isset($_COOKIE[DOKU_COOKIE])) {
1096 return array(null, null, null);
1098 list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
1099 $sticky = (bool) $sticky;
1100 $pass = base64_decode($pass);
1101 $user = base64_decode($user);
1102 return array($user, $sticky, $pass);
1105 //Setup VIM: ex: et ts=2 :