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.');
13 require_once(DOKU_INC
.'inc/common.php');
14 require_once(DOKU_INC
.'inc/io.php');
16 // some ACL level defines
17 define('AUTH_NONE',0);
18 define('AUTH_READ',1);
19 define('AUTH_EDIT',2);
20 define('AUTH_CREATE',4);
21 define('AUTH_UPLOAD',8);
22 define('AUTH_DELETE',16);
23 define('AUTH_ADMIN',255);
28 require_once(DOKU_INC
.'inc/blowfish.php');
29 require_once(DOKU_INC
.'inc/mail.php');
33 // load the the backend auth functions and instantiate the auth object
34 if (@file_exists
(DOKU_INC
.'inc/auth/'.$conf['authtype'].'.class.php')) {
35 require_once(DOKU_INC
.'inc/auth/basic.class.php');
36 require_once(DOKU_INC
.'inc/auth/'.$conf['authtype'].'.class.php');
38 $auth_class = "auth_".$conf['authtype'];
39 if (class_exists($auth_class)) {
40 $auth = new $auth_class();
41 if ($auth->success
== false) {
42 // degrade to unauthenticated user
45 msg($lang['authtempfail'], -1);
48 nice_die($lang['authmodfailed']);
51 nice_die($lang['authmodfailed']);
55 // do the login either by cookie or provided credentials
58 if (!isset($_REQUEST['u'])) $_REQUEST['u'] = '';
59 if (!isset($_REQUEST['p'])) $_REQUEST['p'] = '';
60 if (!isset($_REQUEST['r'])) $_REQUEST['r'] = '';
61 $_REQUEST['http_credentials'] = false;
62 if (!$conf['rememberme']) $_REQUEST['r'] = false;
64 // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
65 if(isset($_SERVER['HTTP_AUTHORIZATION'])){
66 list($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']) =
67 explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
70 // if no credentials were given try to use HTTP auth (for SSO)
71 if(empty($_REQUEST['u']) && empty($_COOKIE[DOKU_COOKIE
]) && !empty($_SERVER['PHP_AUTH_USER'])){
72 $_REQUEST['u'] = $_SERVER['PHP_AUTH_USER'];
73 $_REQUEST['p'] = $_SERVER['PHP_AUTH_PW'];
74 $_REQUEST['http_credentials'] = true;
78 $_REQUEST['u'] = $auth->cleanUser($_REQUEST['u']);
80 if(isset($_REQUEST['authtok'])){
81 // when an authentication token is given, trust the session
82 auth_validateToken($_REQUEST['authtok']);
83 }elseif(!is_null($auth) && $auth->canDo('external')){
84 // external trust mechanism in place
85 $auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
88 'user' => $_REQUEST['u'],
89 'password' => $_REQUEST['p'],
90 'sticky' => $_REQUEST['r'],
91 'silent' => $_REQUEST['http_credentials'],
93 $evt = new Doku_Event('AUTH_LOGIN_CHECK',$evdata);
94 if($evt->advise_before()){
95 auth_login($evdata['user'],
103 //load ACL into a global array
105 if(is_readable(DOKU_CONF
.'acl.auth.php')){
106 $AUTH_ACL = file(DOKU_CONF
.'acl.auth.php');
107 //support user wildcard
108 if(isset($_SERVER['REMOTE_USER'])){
109 $AUTH_ACL = str_replace('%USER%',$_SERVER['REMOTE_USER'],$AUTH_ACL);
110 $AUTH_ACL = str_replace('@USER@',$_SERVER['REMOTE_USER'],$AUTH_ACL); //legacy
118 * This tries to login the user based on the sent auth credentials
120 * The authentication works like this: if a username was given
121 * a new login is assumed and user/password are checked. If they
122 * are correct the password is encrypted with blowfish and stored
123 * together with the username in a cookie - the same info is stored
124 * in the session, too. Additonally a browserID is stored in the
127 * If no username was given the cookie is checked: if the username,
128 * crypted password and browserID match between session and cookie
129 * no further testing is done and the user is accepted
131 * If a cookie was found but no session info was availabe the
132 * blowfish encrypted password from the cookie is decrypted and
133 * together with username rechecked by calling this function again.
135 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
138 * @author Andreas Gohr <andi@splitbrain.org>
140 * @param string $user Username
141 * @param string $pass Cleartext Password
142 * @param bool $sticky Cookie should not expire
143 * @param bool $silent Don't show error on bad auth
144 * @return bool true on successful auth
146 function auth_login($user,$pass,$sticky=false,$silent=false){
151 $sticky ?
$sticky = true : $sticky = false; //sanity check
153 if (!$auth) return false;
157 if ($auth->checkPass($user,$pass)){
158 // make logininfo globally available
159 $_SERVER['REMOTE_USER'] = $user;
160 auth_setCookie($user,PMA_blowfish_encrypt($pass,auth_cookiesalt()),$sticky);
163 //invalid credentials - log off
164 if(!$silent) msg($lang['badlogin'],-1);
169 // read cookie information
170 list($user,$sticky,$pass) = auth_getCookie();
172 $session = $_SESSION[DOKU_COOKIE
]['auth'];
174 // we got a cookie - see if we can trust it
175 if(isset($session) &&
176 $auth->useSessionCache($user) &&
177 ($session['time'] >= time()-$conf['auth_security_timeout']) &&
178 ($session['user'] == $user) &&
179 ($session['pass'] == $pass) && //still crypted
180 ($session['buid'] == auth_browseruid()) ){
181 // he has session, cookie and browser right - let him in
182 $_SERVER['REMOTE_USER'] = $user;
183 $USERINFO = $session['info']; //FIXME move all references to session
186 // no we don't trust it yet - recheck pass but silent
187 $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
188 return auth_login($user,$pass,$sticky,true);
197 * Checks if a given authentication token was stored in the session
199 * Will setup authentication data using data from the session if the
200 * token is correct. Will exit with a 401 Status if not.
202 * @author Andreas Gohr <andi@splitbrain.org>
203 * @param string $token The authentication token
204 * @return boolean true (or will exit on failure)
206 function auth_validateToken($token){
207 if(!$token ||
$token != $_SESSION[DOKU_COOKIE
]['auth']['token']){
209 header("HTTP/1.0 401 Unauthorized");
210 print 'Invalid auth token - maybe the session timed out';
211 unset($_SESSION[DOKU_COOKIE
]['auth']['token']); // no second chance
214 // still here? trust the session data
216 $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE
]['auth']['user'];
217 $USERINFO = $_SESSION[DOKU_COOKIE
]['auth']['info'];
222 * Create an auth token and store it in the session
224 * NOTE: this is completely unrelated to the getSecurityToken() function
226 * @author Andreas Gohr <andi@splitbrain.org>
227 * @return string The auth token
229 function auth_createToken(){
230 $token = md5(mt_rand());
231 @session_start
(); // reopen the session if needed
232 $_SESSION[DOKU_COOKIE
]['auth']['token'] = $token;
233 session_write_close();
238 * Builds a pseudo UID from browser and IP data
240 * This is neither unique nor unfakable - still it adds some
241 * security. Using the first part of the IP makes sure
242 * proxy farms like AOLs are stil okay.
244 * @author Andreas Gohr <andi@splitbrain.org>
246 * @return string a MD5 sum of various browser headers
248 function auth_browseruid(){
249 $ip = clientIP(true);
251 $uid .= $_SERVER['HTTP_USER_AGENT'];
252 $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
253 $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
254 $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
255 $uid .= substr($ip,0,strpos($ip,'.'));
260 * Creates a random key to encrypt the password in cookies
262 * This function tries to read the password for encrypting
263 * cookies from $conf['metadir'].'/_htcookiesalt'
264 * if no such file is found a random key is created and
265 * and stored in this file.
267 * @author Andreas Gohr <andi@splitbrain.org>
271 function auth_cookiesalt(){
273 $file = $conf['metadir'].'/_htcookiesalt';
274 $salt = io_readFile($file);
276 $salt = uniqid(rand(),true);
277 io_saveFile($file,$salt);
283 * Log out the current user
285 * This clears all authentication data and thus log the user
286 * off. It also clears session data.
288 * @author Andreas Gohr <andi@splitbrain.org>
289 * @param bool $keepbc - when true, the breadcrumb data is not cleared
291 function auth_logoff($keepbc=false){
297 // make sure the session is writable (it usually is)
300 if(isset($_SESSION[DOKU_COOKIE
]['auth']['user']))
301 unset($_SESSION[DOKU_COOKIE
]['auth']['user']);
302 if(isset($_SESSION[DOKU_COOKIE
]['auth']['pass']))
303 unset($_SESSION[DOKU_COOKIE
]['auth']['pass']);
304 if(isset($_SESSION[DOKU_COOKIE
]['auth']['info']))
305 unset($_SESSION[DOKU_COOKIE
]['auth']['info']);
306 if(!$keepbc && isset($_SESSION[DOKU_COOKIE
]['bc']))
307 unset($_SESSION[DOKU_COOKIE
]['bc']);
308 if(isset($_SERVER['REMOTE_USER']))
309 unset($_SERVER['REMOTE_USER']);
310 $USERINFO=null; //FIXME
312 if (version_compare(PHP_VERSION
, '5.2.0', '>')) {
313 setcookie(DOKU_COOKIE
,'',time()-600000,DOKU_REL
,'',($conf['securecookie'] && is_ssl()),true);
315 setcookie(DOKU_COOKIE
,'',time()-600000,DOKU_REL
,'',($conf['securecookie'] && is_ssl()));
318 if($auth && $auth->canDo('logoff')){
324 * Check if a user is a manager
326 * Should usually be called without any parameters to check the current
329 * The info is available through $INFO['ismanager'], too
331 * @author Andreas Gohr <andi@splitbrain.org>
333 * @param string user - Username
334 * @param array groups - List of groups the user is in
335 * @param bool adminonly - when true checks if user is admin
337 function auth_ismanager($user=null,$groups=null,$adminonly=false){
342 if (!$auth) return false;
344 if (!isset($_SERVER['REMOTE_USER'])) {
347 $user = $_SERVER['REMOTE_USER'];
350 $user = $auth->cleanUser($user);
351 if(is_null($groups)) $groups = (array) $USERINFO['grps'];
352 $groups = array_map(array($auth,'cleanGroup'),$groups);
353 $user = auth_nameencode($user);
355 // check username against superuser and manager
356 $superusers = explode(',', $conf['superuser']);
357 $superusers = array_unique($superusers);
358 $superusers = array_map('trim', $superusers);
359 // prepare an array containing only true values for array_map call
360 $alltrue = array_fill(0, count($superusers), true);
361 $superusers = array_map('auth_nameencode', $superusers, $alltrue);
364 if(!$auth->isCaseSensitive()){
365 $superusers = array_map('utf8_strtolower',$superusers);
366 $user = utf8_strtolower($user);
370 if(in_array($user, $superusers)) return true;
374 $managers = explode(',', $conf['manager']);
375 $managers = array_unique($managers);
376 $managers = array_map('trim', $managers);
377 // prepare an array containing only true values for array_map call
378 $alltrue = array_fill(0, count($managers), true);
379 $managers = array_map('auth_nameencode', $managers, $alltrue);
380 if(!$auth->isCaseSensitive()) $managers = array_map('utf8_strtolower',$managers);
381 if(in_array($user, $managers)) return true;
384 // check user's groups against superuser and manager
385 if (!empty($groups)) {
387 //prepend groups with @ and nameencode
388 $cnt = count($groups);
389 for($i=0; $i<$cnt; $i++
){
390 $groups[$i] = '@'.auth_nameencode($groups[$i]);
391 if(!$auth->isCaseSensitive()){
392 $groups[$i] = utf8_strtolower($groups[$i]);
396 // check groups against superuser and manager
397 foreach($superusers as $supu)
398 if(in_array($supu, $groups)) return true;
400 foreach($managers as $mana)
401 if(in_array($mana, $groups)) return true;
409 * Check if a user is admin
411 * Alias to auth_ismanager with adminonly=true
413 * The info is available through $INFO['isadmin'], too
415 * @author Andreas Gohr <andi@splitbrain.org>
416 * @see auth_ismanager
418 function auth_isadmin($user=null,$groups=null){
419 return auth_ismanager($user,$groups,true);
423 * Convinience function for auth_aclcheck()
425 * This checks the permissions for the current user
427 * @author Andreas Gohr <andi@splitbrain.org>
429 * @param string $id page ID (needs to be resolved and cleaned)
430 * @return int permission level
432 function auth_quickaclcheck($id){
435 # if no ACL is used always return upload rights
436 if(!$conf['useacl']) return AUTH_UPLOAD
;
437 return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
441 * Returns the maximum rights a user has for
442 * the given ID or its namespace
444 * @author Andreas Gohr <andi@splitbrain.org>
446 * @param string $id page ID (needs to be resolved and cleaned)
447 * @param string $user Username
448 * @param array $groups Array of groups the user is in
449 * @return int permission level
451 function auth_aclcheck($id,$user,$groups){
456 // if no ACL is used always return upload rights
457 if(!$conf['useacl']) return AUTH_UPLOAD
;
458 if (!$auth) return AUTH_NONE
;
460 //make sure groups is an array
461 if(!is_array($groups)) $groups = array();
463 //if user is superuser or in superusergroup return 255 (acl_admin)
464 if(auth_isadmin($user,$groups)) { return AUTH_ADMIN
; }
467 if(!$auth->isCaseSensitive()) $ci = 'ui';
469 $user = $auth->cleanUser($user);
470 $groups = array_map(array($auth,'cleanGroup'),(array)$groups);
471 $user = auth_nameencode($user);
473 //prepend groups with @ and nameencode
474 $cnt = count($groups);
475 for($i=0; $i<$cnt; $i++
){
476 $groups[$i] = '@'.auth_nameencode($groups[$i]);
482 if($user ||
count($groups)){
486 if($user) $groups[] = $user;
488 $regexp = join('|',$groups);
493 //check exact match first
494 $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/'.$ci,$AUTH_ACL);
496 foreach($matches as $match){
497 $match = preg_replace('/#.*$/','',$match); //ignore comments
498 $acl = preg_split('/\s+/',$match);
499 if($acl[2] > AUTH_DELETE
) $acl[2] = AUTH_DELETE
; //no admins in the ACL!
505 //we had a match - return it
510 //still here? do the namespace checks
514 $path = '\*'; //root document
518 $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/'.$ci,$AUTH_ACL);
520 foreach($matches as $match){
521 $match = preg_replace('/#.*$/','',$match); //ignore comments
522 $acl = preg_split('/\s+/',$match);
523 if($acl[2] > AUTH_DELETE
) $acl[2] = AUTH_DELETE
; //no admins in the ACL!
528 //we had a match - return it
532 //get next higher namespace
537 if($path == ':\*') $path = '\*';
539 //we did this already
540 //looks like there is something wrong with the ACL
542 msg('No ACL setup yet! Denying access to everyone.');
545 }while(1); //this should never loop endless
547 //still here? return no permissions
552 * Encode ASCII special chars
554 * Some auth backends allow special chars in their user and groupnames
555 * The special chars are encoded with this function. Only ASCII chars
556 * are encoded UTF-8 multibyte are left as is (different from usual
559 * Decoding can be done with rawurldecode
561 * @author Andreas Gohr <gohr@cosmocode.de>
562 * @see rawurldecode()
564 function auth_nameencode($name,$skip_group=false){
565 global $cache_authname;
566 $cache =& $cache_authname;
567 $name = (string) $name;
569 if (!isset($cache[$name][$skip_group])) {
570 if($skip_group && $name{0} =='@'){
571 $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
572 "'%'.dechex(ord(substr('\\1',-1)))",substr($name,1));
574 $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
575 "'%'.dechex(ord(substr('\\1',-1)))",$name);
579 return $cache[$name][$skip_group];
583 * Create a pronouncable password
585 * @author Andreas Gohr <andi@splitbrain.org>
586 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451
588 * @return string pronouncable password
590 function auth_pwgen(){
592 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
593 $v = 'aeiou'; //vowels
596 //use two syllables...
597 for($i=0;$i < 2; $i++
){
598 $pw .= $c[rand(0, strlen($c)-1)];
599 $pw .= $v[rand(0, strlen($v)-1)];
600 $pw .= $a[rand(0, strlen($a)-1)];
602 //... and add a nice number
609 * Sends a password to the given user
611 * @author Andreas Gohr <andi@splitbrain.org>
613 * @return bool true on success
615 function auth_sendPassword($user,$password){
619 if (!$auth) return false;
622 $user = $auth->cleanUser($user);
623 $userinfo = $auth->getUserData($user);
625 if(!$userinfo['mail']) return false;
627 $text = rawLocale('password');
628 $text = str_replace('@DOKUWIKIURL@',DOKU_URL
,$text);
629 $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
630 $text = str_replace('@LOGIN@',$user,$text);
631 $text = str_replace('@PASSWORD@',$password,$text);
632 $text = str_replace('@TITLE@',$conf['title'],$text);
634 return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
641 * Register a new user
643 * This registers a new user - Data is read directly from $_POST
645 * @author Andreas Gohr <andi@splitbrain.org>
647 * @return bool true on success, false on any error
654 if (!$auth) return false;
655 if(!$_POST['save']) return false;
656 if(!$auth->canDo('addUser')) return false;
659 $_POST['login'] = trim($auth->cleanUser($_POST['login']));
661 //clean fullname and email
662 $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
663 $_POST['email'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
665 if( empty($_POST['login']) ||
666 empty($_POST['fullname']) ||
667 empty($_POST['email']) ){
668 msg($lang['regmissing'],-1);
672 if ($conf['autopasswd']) {
673 $pass = auth_pwgen(); // automatically generate password
674 } elseif (empty($_POST['pass']) ||
675 empty($_POST['passchk'])) {
676 msg($lang['regmissing'], -1); // complain about missing passwords
678 } elseif ($_POST['pass'] != $_POST['passchk']) {
679 msg($lang['regbadpass'], -1); // complain about misspelled passwords
682 $pass = $_POST['pass']; // accept checked and valid password
686 if(!mail_isvalid($_POST['email'])){
687 msg($lang['regbadmail'],-1);
691 //okay try to create the user
692 if(!$auth->triggerUserMod('create', array($_POST['login'],$pass,$_POST['fullname'],$_POST['email']))){
693 msg($lang['reguexists'],-1);
697 // create substitutions for use in notification email
698 $substitutions = array(
699 'NEWUSER' => $_POST['login'],
700 'NEWNAME' => $_POST['fullname'],
701 'NEWEMAIL' => $_POST['email'],
704 if (!$conf['autopasswd']) {
705 msg($lang['regsuccess2'],1);
706 notify('', 'register', '', $_POST['login'], false, $substitutions);
710 // autogenerated password? then send him the password
711 if (auth_sendPassword($_POST['login'],$pass)){
712 msg($lang['regsuccess'],1);
713 notify('', 'register', '', $_POST['login'], false, $substitutions);
716 msg($lang['regmailfail'],-1);
722 * Update user profile
724 * @author Christopher Smith <chris@jalakai.co.uk>
726 function updateprofile() {
732 if (!$auth) return false;
733 if(empty($_POST['save'])) return false;
734 if(!checkSecurityToken()) return false;
736 // should not be able to get here without Profile being possible...
737 if(!$auth->canDo('Profile')) {
738 msg($lang['profna'],-1);
742 if ($_POST['newpass'] != $_POST['passchk']) {
743 msg($lang['regbadpass'], -1); // complain about misspelled passwords
747 //clean fullname and email
748 $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
749 $_POST['email'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
751 if ((empty($_POST['fullname']) && $auth->canDo('modName')) ||
752 (empty($_POST['email']) && $auth->canDo('modMail'))) {
753 msg($lang['profnoempty'],-1);
757 if (!mail_isvalid($_POST['email']) && $auth->canDo('modMail')){
758 msg($lang['regbadmail'],-1);
762 if ($_POST['fullname'] != $INFO['userinfo']['name'] && $auth->canDo('modName')) $changes['name'] = $_POST['fullname'];
763 if ($_POST['email'] != $INFO['userinfo']['mail'] && $auth->canDo('modMail')) $changes['mail'] = $_POST['email'];
764 if (!empty($_POST['newpass']) && $auth->canDo('modPass')) $changes['pass'] = $_POST['newpass'];
766 if (!count($changes)) {
767 msg($lang['profnochange'], -1);
771 if ($conf['profileconfirm']) {
772 if (!$auth->checkPass($_SERVER['REMOTE_USER'], $_POST['oldpass'])) {
773 msg($lang['badlogin'],-1);
778 if ($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
779 // update cookie and session with the changed data
780 $cookie = base64_decode($_COOKIE[DOKU_COOKIE
]);
781 list($user,$sticky,$pass) = explode('|',$cookie,3);
782 if ($changes['pass']) $pass = PMA_blowfish_encrypt($changes['pass'],auth_cookiesalt());
784 auth_setCookie($_SERVER['REMOTE_USER'],$pass,(bool)$sticky);
790 * Send a new password
792 * This function handles both phases of the password reset:
794 * - handling the first request of password reset
795 * - validating the password reset auth token
797 * @author Benoit Chesneau <benoit@bchesneau.info>
798 * @author Chris Smith <chris@jalakai.co.uk>
799 * @author Andreas Gohr <andi@splitbrain.org>
801 * @return bool true on success, false on any error
803 function act_resendpwd(){
808 if(!actionOK('resendpwd')) return false;
809 if (!$auth) return false;
811 // should not be able to get here without modPass being possible...
812 if(!$auth->canDo('modPass')) {
813 msg($lang['resendna'],-1);
817 $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
820 // we're in token phase
822 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
823 if(!@file_exists
($tfile)){
824 msg($lang['resendpwdbadauth'],-1);
827 $user = io_readfile($tfile);
829 $userinfo = $auth->getUserData($user);
830 if(!$userinfo['mail']) {
831 msg($lang['resendpwdnouser'], -1);
835 $pass = auth_pwgen();
836 if (!$auth->triggerUserMod('modify', array($user,array('pass' => $pass)))) {
837 msg('error modifying user data',-1);
841 if (auth_sendPassword($user,$pass)) {
842 msg($lang['resendpwdsuccess'],1);
844 msg($lang['regmailfail'],-1);
849 // we're in request phase
851 if(!$_POST['save']) return false;
853 if (empty($_POST['login'])) {
854 msg($lang['resendpwdmissing'], -1);
857 $user = trim($auth->cleanUser($_POST['login']));
860 $userinfo = $auth->getUserData($user);
861 if(!$userinfo['mail']) {
862 msg($lang['resendpwdnouser'], -1);
866 // generate auth token
867 $token = md5(auth_cookiesalt().$user); //secret but user based
868 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
869 $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
871 io_saveFile($tfile,$user);
873 $text = rawLocale('pwconfirm');
874 $text = str_replace('@DOKUWIKIURL@',DOKU_URL
,$text);
875 $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
876 $text = str_replace('@LOGIN@',$user,$text);
877 $text = str_replace('@TITLE@',$conf['title'],$text);
878 $text = str_replace('@CONFIRM@',$url,$text);
880 if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
884 msg($lang['resendpwdconfirm'],1);
886 msg($lang['regmailfail'],-1);
891 return false; // never reached
895 * Encrypts a password using the given method and salt
897 * If the selected method needs a salt and none was given, a random one
900 * The following methods are understood:
902 * smd5 - Salted MD5 hashing
903 * apr1 - Apache salted MD5 hashing
904 * md5 - Simple MD5 hashing
905 * sha1 - SHA1 hashing
906 * ssha - Salted SHA1 hashing
908 * mysql - MySQL password (old method)
909 * my411 - MySQL 4.1.1 password
910 * kmd5 - Salted MD5 hashing as used by UNB
912 * @author Andreas Gohr <andi@splitbrain.org>
913 * @return string The crypted password
915 function auth_cryptPassword($clear,$method='',$salt=null){
917 if(empty($method)) $method = $conf['passcrypt'];
920 if(is_null($salt)) $salt = md5(uniqid(rand(), true));
922 switch(strtolower($method)){
924 if(defined('CRYPT_MD5') && CRYPT_MD5
) return crypt($clear,'$1$'.substr($salt,0,8).'$');
925 // when crypt can't handle SMD5, falls through to pure PHP implementation
928 //from http://de.php.net/manual/en/function.crypt.php#73619 comment by <mikey_nich at hotmail dot com>
929 if(!$magic) $magic = 'apr1';
930 $salt = substr($salt,0,8);
931 $len = strlen($clear);
932 $text = $clear.'$'.$magic.'$'.$salt;
933 $bin = pack("H32", md5($clear.$salt.$clear));
934 for($i = $len; $i > 0; $i -= 16) {
935 $text .= substr($bin, 0, min(16, $i));
937 for($i = $len; $i > 0; $i >>= 1) {
938 $text .= ($i & 1) ?
chr(0) : $clear{0};
940 $bin = pack("H32", md5($text));
941 for($i = 0; $i < 1000; $i++
) {
942 $new = ($i & 1) ?
$clear : $bin;
943 if ($i %
3) $new .= $salt;
944 if ($i %
7) $new .= $clear;
945 $new .= ($i & 1) ?
$bin : $clear;
946 $bin = pack("H32", md5($new));
949 for ($i = 0; $i < 5; $i++
) {
952 if ($j == 16) $j = 5;
953 $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
955 $tmp = chr(0).chr(0).$bin[11].$tmp;
956 $tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
957 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
958 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
959 return '$'.$magic.'$'.$salt.'$'.$tmp;
965 $salt=substr($salt,0,4);
966 return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
968 return crypt($clear,substr($salt,0,2));
970 //from http://www.php.net/mysql comment by <soren at byu dot edu>
974 $charArr = preg_split("//", $clear);
975 foreach ($charArr as $char) {
976 if (($char == '') ||
($char == ' ') ||
($char == '\t')) continue;
977 $charVal = ord($char);
978 $nr ^
= ((($nr & 63) +
$add) * $charVal) +
($nr << 8);
979 $nr2 +
= ($nr2 << 8) ^
$nr;
982 return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
984 return '*'.sha1(pack("H*", sha1($clear)));
986 $key = substr($salt, 16, 2);
987 $hash1 = strtolower(md5($key . md5($clear)));
988 $hash2 = substr($hash1, 0, 16) . $key . substr($hash1, 16);
991 msg("Unsupported crypt method $method",-1);
996 * Verifies a cleartext password against a crypted hash
998 * The method and salt used for the crypted hash is determined automatically
999 * then the clear text password is crypted using the same method. If both hashs
1000 * match true is is returned else false
1002 * @author Andreas Gohr <andi@splitbrain.org>
1005 function auth_verifyPassword($clear,$crypt){
1009 //determine the used method and salt
1010 $len = strlen($crypt);
1011 if(preg_match('/^\$1\$([^\$]{0,8})\$/',$crypt,$m)){
1014 }elseif(preg_match('/^\$apr1\$([^\$]{0,8})\$/',$crypt,$m)){
1017 }elseif(substr($crypt,0,6) == '{SSHA}'){
1019 $salt = substr(base64_decode(substr($crypt, 6)),20);
1020 }elseif($len == 32){
1022 }elseif($len == 40){
1024 }elseif($len == 16){
1026 }elseif($len == 41 && $crypt[0] == '*'){
1028 }elseif($len == 34){
1033 $salt = substr($crypt,0,2);
1037 if(auth_cryptPassword($clear,$method,$salt) === $crypt){
1044 * Set the authentication cookie and add user identification data to the session
1046 * @param string $user username
1047 * @param string $pass encrypted password
1048 * @param bool $sticky whether or not the cookie will last beyond the session
1050 function auth_setCookie($user,$pass,$sticky) {
1055 if (!$auth) return false;
1056 $USERINFO = $auth->getUserData($user);
1059 $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
1060 $time = $sticky ?
(time()+
60*60*24*365) : 0; //one year
1061 if (version_compare(PHP_VERSION
, '5.2.0', '>')) {
1062 setcookie(DOKU_COOKIE
,$cookie,$time,DOKU_REL
,'',($conf['securecookie'] && is_ssl()),true);
1064 setcookie(DOKU_COOKIE
,$cookie,$time,DOKU_REL
,'',($conf['securecookie'] && is_ssl()));
1067 $_SESSION[DOKU_COOKIE
]['auth']['user'] = $user;
1068 $_SESSION[DOKU_COOKIE
]['auth']['pass'] = $pass;
1069 $_SESSION[DOKU_COOKIE
]['auth']['buid'] = auth_browseruid();
1070 $_SESSION[DOKU_COOKIE
]['auth']['info'] = $USERINFO;
1071 $_SESSION[DOKU_COOKIE
]['auth']['time'] = time();
1075 * Returns the user, (encrypted) password and sticky bit from cookie
1079 function auth_getCookie(){
1080 if (!isset($_COOKIE[DOKU_COOKIE
])) {
1081 return array(null, null, null);
1083 list($user,$sticky,$pass) = explode('|',$_COOKIE[DOKU_COOKIE
],3);
1084 $sticky = (bool) $sticky;
1085 $pass = base64_decode($pass);
1086 $user = base64_decode($user);
1087 return array($user,$sticky,$pass);
1090 //Setup VIM: ex: et ts=2 enc=utf-8 :