xref: /dokuwiki/inc/auth.php (revision 3a48618a538412994ec244d5a9fde5c4a6161d10)
1ed7b5f09Sandi<?php
215fae107Sandi/**
315fae107Sandi * Authentication library
415fae107Sandi *
515fae107Sandi * Including this file will automatically try to login
615fae107Sandi * a user by calling auth_login()
715fae107Sandi *
815fae107Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
915fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
1015fae107Sandi */
1115fae107Sandi
12fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.');
131c73890cSAndreas Gohr
14ebf97c8fSAndreas Gohr// some ACL level defines
15ebf97c8fSAndreas Gohrdefine('AUTH_NONE',0);
16ebf97c8fSAndreas Gohrdefine('AUTH_READ',1);
17ebf97c8fSAndreas Gohrdefine('AUTH_EDIT',2);
18ebf97c8fSAndreas Gohrdefine('AUTH_CREATE',4);
19ebf97c8fSAndreas Gohrdefine('AUTH_UPLOAD',8);
20ebf97c8fSAndreas Gohrdefine('AUTH_DELETE',16);
21ebf97c8fSAndreas Gohrdefine('AUTH_ADMIN',255);
22ebf97c8fSAndreas Gohr
2316905344SAndreas Gohr/**
2416905344SAndreas Gohr * Initialize the auth system.
2516905344SAndreas Gohr *
2616905344SAndreas Gohr * This function is automatically called at the end of init.php
2716905344SAndreas Gohr *
2816905344SAndreas Gohr * This used to be the main() of the auth.php
2916905344SAndreas Gohr *
3016905344SAndreas Gohr * @todo backend loading maybe should be handled by the class autoloader
3116905344SAndreas Gohr * @todo maybe split into multiple functions at the XXX marked positions
3216905344SAndreas Gohr */
3316905344SAndreas Gohrfunction auth_setup(){
34742c66f8Schris    global $conf;
3503c4aec3Schris    global $auth;
369a9714acSDominik Eckelmann    global $AUTH_ACL;
379a9714acSDominik Eckelmann    global $lang;
38c8f80b4eSAndreas Gohr    global $config_cascade;
399a9714acSDominik Eckelmann    $AUTH_ACL = array();
4003c4aec3Schris
4116905344SAndreas Gohr    if(!$conf['useacl']) return false;
4216905344SAndreas Gohr
4316905344SAndreas Gohr    // load the the backend auth functions and instantiate the auth object XXX
448b06d178Schris    if (@file_exists(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php')) {
458b06d178Schris        require_once(DOKU_INC.'inc/auth/basic.class.php');
468b06d178Schris        require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php');
478b06d178Schris
488b06d178Schris        $auth_class = "auth_".$conf['authtype'];
49cd52f92dSchris        if (class_exists($auth_class)) {
508b06d178Schris            $auth = new $auth_class();
51d2dde4ebSMatthias Grimm            if ($auth->success == false) {
520f4f4adfSAndreas Gohr                // degrade to unauthenticated user
53d2dde4ebSMatthias Grimm                unset($auth);
540f4f4adfSAndreas Gohr                auth_logoff();
55cd52f92dSchris                msg($lang['authtempfail'], -1);
56d2dde4ebSMatthias Grimm            }
578b06d178Schris        } else {
583816dcbcSAndreas Gohr            nice_die($lang['authmodfailed']);
59cd52f92dSchris        }
60cd52f92dSchris    } else {
613816dcbcSAndreas Gohr        nice_die($lang['authmodfailed']);
628b06d178Schris    }
63f3f0262cSandi
6416905344SAndreas Gohr    if(!$auth) return;
6516905344SAndreas Gohr
6616905344SAndreas Gohr    // do the login either by cookie or provided credentials XXX
67bbbd6568SAndreas Gohr    if (!isset($_REQUEST['u'])) $_REQUEST['u'] = '';
68bbbd6568SAndreas Gohr    if (!isset($_REQUEST['p'])) $_REQUEST['p'] = '';
69bbbd6568SAndreas Gohr    if (!isset($_REQUEST['r'])) $_REQUEST['r'] = '';
70b2c0d874SGina Haeussge    $_REQUEST['http_credentials'] = false;
7117f89d7eSMichael Klier    if (!$conf['rememberme']) $_REQUEST['r'] = false;
72bbbd6568SAndreas Gohr
73b2665af7SMichael Hamann    // handle renamed HTTP_AUTHORIZATION variable (can happen when a fix like
74b2665af7SMichael Hamann    // the one presented at
75b2665af7SMichael Hamann    // http://www.besthostratings.com/articles/http-auth-php-cgi.html is used
76b2665af7SMichael Hamann    // for enabling HTTP authentication with CGI/SuExec)
77b2665af7SMichael Hamann    if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
78b2665af7SMichael Hamann        $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
79528ddc7cSAndreas Gohr    // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
8006156f3cSAndreas Gohr    if(isset($_SERVER['HTTP_AUTHORIZATION'])){
81528ddc7cSAndreas Gohr        list($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']) =
82528ddc7cSAndreas Gohr            explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
83528ddc7cSAndreas Gohr    }
84528ddc7cSAndreas Gohr
851e8c9c90SAndreas Gohr    // if no credentials were given try to use HTTP auth (for SSO)
864a26ad85Schris    if(empty($_REQUEST['u']) && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])){
871e8c9c90SAndreas Gohr        $_REQUEST['u'] = $_SERVER['PHP_AUTH_USER'];
881e8c9c90SAndreas Gohr        $_REQUEST['p'] = $_SERVER['PHP_AUTH_PW'];
89b2c0d874SGina Haeussge        $_REQUEST['http_credentials'] = true;
901e8c9c90SAndreas Gohr    }
911e8c9c90SAndreas Gohr
92191bb90aSAndreas Gohr    // apply cleaning
93191bb90aSAndreas Gohr    $_REQUEST['u'] = $auth->cleanUser($_REQUEST['u']);
94191bb90aSAndreas Gohr
95c66972f2SAdrian Lang    if(isset($_REQUEST['authtok'])){
96f13fa892SAndreas Gohr        // when an authentication token is given, trust the session
97f13fa892SAndreas Gohr        auth_validateToken($_REQUEST['authtok']);
98f13fa892SAndreas Gohr    }elseif(!is_null($auth) && $auth->canDo('external')){
99f13fa892SAndreas Gohr        // external trust mechanism in place
100f5cb575dSAndreas Gohr        $auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
101f5cb575dSAndreas Gohr    }else{
1026080c584SRobin Gareus        $evdata = array(
1036080c584SRobin Gareus                'user'     => $_REQUEST['u'],
1046080c584SRobin Gareus                'password' => $_REQUEST['p'],
1056080c584SRobin Gareus                'sticky'   => $_REQUEST['r'],
1066080c584SRobin Gareus                'silent'   => $_REQUEST['http_credentials'],
1076080c584SRobin Gareus                );
108b5ee21aaSAdrian Lang        trigger_event('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
109f5cb575dSAndreas Gohr    }
110f5cb575dSAndreas Gohr
11116905344SAndreas Gohr    //load ACL into a global array XXX
11275c93b77SAndreas Gohr    $AUTH_ACL = auth_loadACL();
11375c93b77SAndreas Gohr}
11475c93b77SAndreas Gohr
11575c93b77SAndreas Gohr/**
11675c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards
11775c93b77SAndreas Gohr *
11875c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
11975c93b77SAndreas Gohr * @returns array
12075c93b77SAndreas Gohr */
12175c93b77SAndreas Gohrfunction auth_loadACL(){
12275c93b77SAndreas Gohr    global $config_cascade;
12375c93b77SAndreas Gohr
12475c93b77SAndreas Gohr    if(!is_readable($config_cascade['acl']['default'])) return array();
12575c93b77SAndreas Gohr
12675c93b77SAndreas Gohr    $acl = file($config_cascade['acl']['default']);
12775c93b77SAndreas Gohr
128191bb90aSAndreas Gohr    //support user wildcard
129f8cc3354SGuy Brand    if(isset($_SERVER['REMOTE_USER'])){
13075c93b77SAndreas Gohr        $len = count($acl);
13175c93b77SAndreas Gohr        for($i=0; $i<$len; $i++){
13275c93b77SAndreas Gohr            if($acl[$i]{0} == '#') continue;
13375c93b77SAndreas Gohr            list($id,$rest) = preg_split('/\s+/',$acl[$i],2);
13475c93b77SAndreas Gohr            $id   = str_replace('%USER%',cleanID($_SERVER['REMOTE_USER']),$id);
13575c93b77SAndreas Gohr            $rest = str_replace('%USER%',auth_nameencode($_SERVER['REMOTE_USER']),$rest);
13675c93b77SAndreas Gohr            $acl[$i] = "$id\t$rest";
137a8fe108bSGuy Brand        }
13811799630Sandi    }
13975c93b77SAndreas Gohr    return $acl;
140f3f0262cSandi}
141f3f0262cSandi
142b5ee21aaSAdrian Langfunction auth_login_wrapper($evdata) {
143b5ee21aaSAdrian Lang    return auth_login($evdata['user'],
144b5ee21aaSAdrian Lang                      $evdata['password'],
145b5ee21aaSAdrian Lang                      $evdata['sticky'],
146b5ee21aaSAdrian Lang                      $evdata['silent']);
147b5ee21aaSAdrian Lang}
148b5ee21aaSAdrian Lang
149f3f0262cSandi/**
150f3f0262cSandi * This tries to login the user based on the sent auth credentials
151f3f0262cSandi *
152f3f0262cSandi * The authentication works like this: if a username was given
15315fae107Sandi * a new login is assumed and user/password are checked. If they
15415fae107Sandi * are correct the password is encrypted with blowfish and stored
15515fae107Sandi * together with the username in a cookie - the same info is stored
15615fae107Sandi * in the session, too. Additonally a browserID is stored in the
15715fae107Sandi * session.
15815fae107Sandi *
15915fae107Sandi * If no username was given the cookie is checked: if the username,
16015fae107Sandi * crypted password and browserID match between session and cookie
16115fae107Sandi * no further testing is done and the user is accepted
16215fae107Sandi *
16315fae107Sandi * If a cookie was found but no session info was availabe the
164136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
16515fae107Sandi * together with username rechecked by calling this function again.
166f3f0262cSandi *
167f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
168f3f0262cSandi * are set.
16915fae107Sandi *
17015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
17115fae107Sandi *
17215fae107Sandi * @param   string  $user    Username
17315fae107Sandi * @param   string  $pass    Cleartext Password
17415fae107Sandi * @param   bool    $sticky  Cookie should not expire
175f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
17615fae107Sandi * @return  bool             true on successful auth
177f3f0262cSandi */
178f112c2faSAndreas Gohrfunction auth_login($user,$pass,$sticky=false,$silent=false){
179f3f0262cSandi    global $USERINFO;
180f3f0262cSandi    global $conf;
181f3f0262cSandi    global $lang;
182cd52f92dSchris    global $auth;
183132bdbfeSandi    $sticky ? $sticky = true : $sticky = false; //sanity check
184f3f0262cSandi
185beca106aSAdrian Lang    if (!$auth) return false;
186beca106aSAdrian Lang
187bbbd6568SAndreas Gohr    if(!empty($user)){
188132bdbfeSandi        //usual login
189cd52f92dSchris        if ($auth->checkPass($user,$pass)){
190132bdbfeSandi            // make logininfo globally available
191f3f0262cSandi            $_SERVER['REMOTE_USER'] = $user;
192a0b5b007SChris Smith            auth_setCookie($user,PMA_blowfish_encrypt($pass,auth_cookiesalt()),$sticky);
193132bdbfeSandi            return true;
194f3f0262cSandi        }else{
195f3f0262cSandi            //invalid credentials - log off
196f112c2faSAndreas Gohr            if(!$silent) msg($lang['badlogin'],-1);
197f3f0262cSandi            auth_logoff();
198132bdbfeSandi            return false;
199f3f0262cSandi        }
200f3f0262cSandi    }else{
201132bdbfeSandi        // read cookie information
202645c0a36SAndreas Gohr        list($user,$sticky,$pass) = auth_getCookie();
203132bdbfeSandi        if($user && $pass){
204132bdbfeSandi            // we got a cookie - see if we can trust it
205fa7c70ffSAdrian Lang
206fa7c70ffSAdrian Lang            // get session info
207fa7c70ffSAdrian Lang            $session = $_SESSION[DOKU_COOKIE]['auth'];
208132bdbfeSandi            if(isset($session) &&
2097172dbc0SAndreas Gohr                    $auth->useSessionCache($user) &&
2104c989037SChris Smith                    ($session['time'] >= time()-$conf['auth_security_timeout']) &&
211132bdbfeSandi                    ($session['user'] == $user) &&
212132bdbfeSandi                    ($session['pass'] == $pass) &&  //still crypted
213132bdbfeSandi                    ($session['buid'] == auth_browseruid()) ){
214132bdbfeSandi                // he has session, cookie and browser right - let him in
215132bdbfeSandi                $_SERVER['REMOTE_USER'] = $user;
216132bdbfeSandi                $USERINFO = $session['info']; //FIXME move all references to session
217132bdbfeSandi                return true;
218132bdbfeSandi            }
219f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
220132bdbfeSandi            $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
221f112c2faSAndreas Gohr            return auth_login($user,$pass,$sticky,true);
222132bdbfeSandi        }
223132bdbfeSandi    }
224f3f0262cSandi    //just to be sure
225883179a4SAndreas Gohr    auth_logoff(true);
226132bdbfeSandi    return false;
227f3f0262cSandi}
228132bdbfeSandi
229132bdbfeSandi/**
230f13fa892SAndreas Gohr * Checks if a given authentication token was stored in the session
231f13fa892SAndreas Gohr *
232f13fa892SAndreas Gohr * Will setup authentication data using data from the session if the
233f13fa892SAndreas Gohr * token is correct. Will exit with a 401 Status if not.
234f13fa892SAndreas Gohr *
235f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
236f13fa892SAndreas Gohr * @param  string $token The authentication token
237f13fa892SAndreas Gohr * @return boolean true (or will exit on failure)
238f13fa892SAndreas Gohr */
239f13fa892SAndreas Gohrfunction auth_validateToken($token){
240f13fa892SAndreas Gohr    if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']){
241f13fa892SAndreas Gohr        // bad token
242f13fa892SAndreas Gohr        header("HTTP/1.0 401 Unauthorized");
243f13fa892SAndreas Gohr        print 'Invalid auth token - maybe the session timed out';
244f13fa892SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
245f13fa892SAndreas Gohr        exit;
246f13fa892SAndreas Gohr    }
247f13fa892SAndreas Gohr    // still here? trust the session data
248f13fa892SAndreas Gohr    global $USERINFO;
249f13fa892SAndreas Gohr    $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
250f13fa892SAndreas Gohr    $USERINFO = $_SESSION[DOKU_COOKIE]['auth']['info'];
251f13fa892SAndreas Gohr    return true;
252f13fa892SAndreas Gohr}
253f13fa892SAndreas Gohr
254f13fa892SAndreas Gohr/**
255f13fa892SAndreas Gohr * Create an auth token and store it in the session
256f13fa892SAndreas Gohr *
257f13fa892SAndreas Gohr * NOTE: this is completely unrelated to the getSecurityToken() function
258f13fa892SAndreas Gohr *
259f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
260f13fa892SAndreas Gohr * @return string The auth token
261f13fa892SAndreas Gohr */
262f13fa892SAndreas Gohrfunction auth_createToken(){
263f13fa892SAndreas Gohr    $token = md5(mt_rand());
26409c2d803SAndreas Gohr    @session_start(); // reopen the session if needed
265f13fa892SAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
26609c2d803SAndreas Gohr    session_write_close();
267f13fa892SAndreas Gohr    return $token;
268f13fa892SAndreas Gohr}
269f13fa892SAndreas Gohr
270f13fa892SAndreas Gohr/**
271136ce040Sandi * Builds a pseudo UID from browser and IP data
272132bdbfeSandi *
273132bdbfeSandi * This is neither unique nor unfakable - still it adds some
274136ce040Sandi * security. Using the first part of the IP makes sure
275136ce040Sandi * proxy farms like AOLs are stil okay.
27615fae107Sandi *
27715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
27815fae107Sandi *
27915fae107Sandi * @return  string  a MD5 sum of various browser headers
280132bdbfeSandi */
281132bdbfeSandifunction auth_browseruid(){
2822f9daf16SAndreas Gohr    $ip   = clientIP(true);
283132bdbfeSandi    $uid  = '';
284132bdbfeSandi    $uid .= $_SERVER['HTTP_USER_AGENT'];
285132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
286132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
287132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
2882f9daf16SAndreas Gohr    $uid .= substr($ip,0,strpos($ip,'.'));
289132bdbfeSandi    return md5($uid);
290132bdbfeSandi}
291132bdbfeSandi
292132bdbfeSandi/**
293132bdbfeSandi * Creates a random key to encrypt the password in cookies
29415fae107Sandi *
29515fae107Sandi * This function tries to read the password for encrypting
29698407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
29715fae107Sandi * if no such file is found a random key is created and
29815fae107Sandi * and stored in this file.
29915fae107Sandi *
30015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
30115fae107Sandi *
30215fae107Sandi * @return  string
303132bdbfeSandi */
304132bdbfeSandifunction auth_cookiesalt(){
305132bdbfeSandi    global $conf;
30698407a7aSandi    $file = $conf['metadir'].'/_htcookiesalt';
307132bdbfeSandi    $salt = io_readFile($file);
308132bdbfeSandi    if(empty($salt)){
309132bdbfeSandi        $salt = uniqid(rand(),true);
310132bdbfeSandi        io_saveFile($file,$salt);
311132bdbfeSandi    }
312132bdbfeSandi    return $salt;
313f3f0262cSandi}
314f3f0262cSandi
315f3f0262cSandi/**
316883179a4SAndreas Gohr * Log out the current user
317883179a4SAndreas Gohr *
318f3f0262cSandi * This clears all authentication data and thus log the user
319883179a4SAndreas Gohr * off. It also clears session data.
32015fae107Sandi *
32115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
322883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
323f3f0262cSandi */
324883179a4SAndreas Gohrfunction auth_logoff($keepbc=false){
325f3f0262cSandi    global $conf;
326f3f0262cSandi    global $USERINFO;
3278b06d178Schris    global $INFO, $ID;
3285298a619SAndreas Gohr    global $auth;
32937065e65Sandi
330d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
331e9621d07SAndreas Gohr    @session_start();
332e9621d07SAndreas Gohr
333e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
334e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
335e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
336e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
337e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
338e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
339883179a4SAndreas Gohr    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
340e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
34137065e65Sandi    if(isset($_SERVER['REMOTE_USER']))
342f3f0262cSandi        unset($_SERVER['REMOTE_USER']);
343132bdbfeSandi    $USERINFO=null; //FIXME
344f5c6743cSAndreas Gohr
345f5c6743cSAndreas Gohr    if (version_compare(PHP_VERSION, '5.2.0', '>')) {
34685c6f7d0SAndreas Gohr        setcookie(DOKU_COOKIE,'',time()-600000,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true);
347f5c6743cSAndreas Gohr    }else{
34885c6f7d0SAndreas Gohr        setcookie(DOKU_COOKIE,'',time()-600000,DOKU_REL,'',($conf['securecookie'] && is_ssl()));
349f5c6743cSAndreas Gohr    }
3505298a619SAndreas Gohr
351880f62faSAndreas Gohr    if($auth) $auth->logOff();
352f3f0262cSandi}
353f3f0262cSandi
354f3f0262cSandi/**
355f8cc712eSAndreas Gohr * Check if a user is a manager
356f8cc712eSAndreas Gohr *
357f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
358f8cc712eSAndreas Gohr * user.
359f8cc712eSAndreas Gohr *
360f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
361f8cc712eSAndreas Gohr *
362f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
363f8cc712eSAndreas Gohr * @see    auth_isadmin
364f8cc712eSAndreas Gohr * @param  string user      - Username
365f8cc712eSAndreas Gohr * @param  array  groups    - List of groups the user is in
366f8cc712eSAndreas Gohr * @param  bool   adminonly - when true checks if user is admin
367f8cc712eSAndreas Gohr */
368f8cc712eSAndreas Gohrfunction auth_ismanager($user=null,$groups=null,$adminonly=false){
369f8cc712eSAndreas Gohr    global $conf;
370f8cc712eSAndreas Gohr    global $USERINFO;
371d752aedeSAndreas Gohr    global $auth;
372f8cc712eSAndreas Gohr
373beca106aSAdrian Lang    if (!$auth) return false;
374c66972f2SAdrian Lang    if(is_null($user)) {
375c66972f2SAdrian Lang        if (!isset($_SERVER['REMOTE_USER'])) {
376c66972f2SAdrian Lang            return false;
377c66972f2SAdrian Lang        } else {
378c66972f2SAdrian Lang            $user = $_SERVER['REMOTE_USER'];
379c66972f2SAdrian Lang        }
380c66972f2SAdrian Lang    }
381d6dc956fSAndreas Gohr    if(is_null($groups)){
382d6dc956fSAndreas Gohr        $groups = (array) $USERINFO['grps'];
383e259aa79SAndreas Gohr    }
384e259aa79SAndreas Gohr
385d6dc956fSAndreas Gohr    // check superuser match
386d6dc956fSAndreas Gohr    if(auth_isMember($conf['superuser'],$user, $groups)) return true;
387d6dc956fSAndreas Gohr    if($adminonly) return false;
388e259aa79SAndreas Gohr    // check managers
389d6dc956fSAndreas Gohr    if(auth_isMember($conf['manager'],$user, $groups)) return true;
39000ce12daSChris Smith
391f8cc712eSAndreas Gohr    return false;
392f8cc712eSAndreas Gohr}
393f8cc712eSAndreas Gohr
394f8cc712eSAndreas Gohr/**
395f8cc712eSAndreas Gohr * Check if a user is admin
396f8cc712eSAndreas Gohr *
397f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
398f8cc712eSAndreas Gohr *
399f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
400f8cc712eSAndreas Gohr *
401f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
402f8cc712eSAndreas Gohr * @see auth_ismanager
403f8cc712eSAndreas Gohr */
404f8cc712eSAndreas Gohrfunction auth_isadmin($user=null,$groups=null){
405f8cc712eSAndreas Gohr    return auth_ismanager($user,$groups,true);
406f8cc712eSAndreas Gohr}
407f8cc712eSAndreas Gohr
408d6dc956fSAndreas Gohr
409d6dc956fSAndreas Gohr/**
410d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
411d6dc956fSAndreas Gohr * users and groups to determine membership status
412d6dc956fSAndreas Gohr *
413d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
414d6dc956fSAndreas Gohr *
415d6dc956fSAndreas Gohr * @param $memberlist string commaseparated list of allowed users and groups
416d6dc956fSAndreas Gohr * @param $user       string user to match against
417d6dc956fSAndreas Gohr * @param $groups     array  groups the user is member of
418d6dc956fSAndreas Gohr * @returns bool      true for membership acknowledged
419d6dc956fSAndreas Gohr */
420d6dc956fSAndreas Gohrfunction auth_isMember($memberlist,$user,array $groups){
421d6dc956fSAndreas Gohr    global $auth;
422d6dc956fSAndreas Gohr    if (!$auth) return false;
423d6dc956fSAndreas Gohr
424d6dc956fSAndreas Gohr    // clean user and groups
4254f56ecbfSAdrian Lang    if(!$auth->isCaseSensitive()){
426d6dc956fSAndreas Gohr        $user = utf8_strtolower($user);
427d6dc956fSAndreas Gohr        $groups = array_map('utf8_strtolower',$groups);
428d6dc956fSAndreas Gohr    }
429d6dc956fSAndreas Gohr    $user = $auth->cleanUser($user);
430d6dc956fSAndreas Gohr    $groups = array_map(array($auth,'cleanGroup'),$groups);
431d6dc956fSAndreas Gohr
432d6dc956fSAndreas Gohr    // extract the memberlist
433d6dc956fSAndreas Gohr    $members = explode(',',$memberlist);
434d6dc956fSAndreas Gohr    $members = array_map('trim',$members);
435d6dc956fSAndreas Gohr    $members = array_unique($members);
436d6dc956fSAndreas Gohr    $members = array_filter($members);
437d6dc956fSAndreas Gohr
438d6dc956fSAndreas Gohr    // compare cleaned values
439d6dc956fSAndreas Gohr    foreach($members as $member){
4404f56ecbfSAdrian Lang        if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member);
441d6dc956fSAndreas Gohr        if($member[0] == '@'){
442d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member,1));
443d6dc956fSAndreas Gohr            if(in_array($member, $groups)) return true;
444d6dc956fSAndreas Gohr        }else{
445d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
446d6dc956fSAndreas Gohr            if($member == $user) return true;
447d6dc956fSAndreas Gohr        }
448d6dc956fSAndreas Gohr    }
449d6dc956fSAndreas Gohr
450d6dc956fSAndreas Gohr    // still here? not a member!
451d6dc956fSAndreas Gohr    return false;
452d6dc956fSAndreas Gohr}
453d6dc956fSAndreas Gohr
454f8cc712eSAndreas Gohr/**
45515fae107Sandi * Convinience function for auth_aclcheck()
45615fae107Sandi *
45715fae107Sandi * This checks the permissions for the current user
45815fae107Sandi *
45915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
46015fae107Sandi *
4611698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
46215fae107Sandi * @return int          permission level
463f3f0262cSandi */
464f3f0262cSandifunction auth_quickaclcheck($id){
465f3f0262cSandi    global $conf;
466f3f0262cSandi    global $USERINFO;
467f3f0262cSandi    # if no ACL is used always return upload rights
468f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
469f3f0262cSandi    return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
470f3f0262cSandi}
471f3f0262cSandi
472f3f0262cSandi/**
473f3f0262cSandi * Returns the maximum rights a user has for
474f3f0262cSandi * the given ID or its namespace
47515fae107Sandi *
47615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
47715fae107Sandi *
4781698b983Smichael * @param  string  $id     page ID (needs to be resolved and cleaned)
47915fae107Sandi * @param  string  $user   Username
48015fae107Sandi * @param  array   $groups Array of groups the user is in
48115fae107Sandi * @return int             permission level
482f3f0262cSandi */
483f3f0262cSandifunction auth_aclcheck($id,$user,$groups){
484f3f0262cSandi    global $conf;
485f3f0262cSandi    global $AUTH_ACL;
486d752aedeSAndreas Gohr    global $auth;
487f3f0262cSandi
48885d03f68SAndreas Gohr    // if no ACL is used always return upload rights
489f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
490beca106aSAdrian Lang    if (!$auth) return AUTH_NONE;
491f3f0262cSandi
492074cf26bSandi    //make sure groups is an array
493074cf26bSandi    if(!is_array($groups)) $groups = array();
494074cf26bSandi
49585d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
49685d03f68SAndreas Gohr    if(auth_isadmin($user,$groups)) { return AUTH_ADMIN; }
49785d03f68SAndreas Gohr
498e259aa79SAndreas Gohr    $ci = '';
499e259aa79SAndreas Gohr    if(!$auth->isCaseSensitive()) $ci = 'ui';
500d752aedeSAndreas Gohr
501d752aedeSAndreas Gohr    $user = $auth->cleanUser($user);
502d752aedeSAndreas Gohr    $groups = array_map(array($auth,'cleanGroup'),(array)$groups);
50385d03f68SAndreas Gohr    $user = auth_nameencode($user);
50485d03f68SAndreas Gohr
5056c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
5062cd2db38Sandi    $cnt = count($groups);
5072cd2db38Sandi    for($i=0; $i<$cnt; $i++){
5086c2bb100SAndreas Gohr        $groups[$i] = '@'.auth_nameencode($groups[$i]);
50910a76f6fSfrank    }
51010a76f6fSfrank
511f3f0262cSandi    $ns    = getNS($id);
512f3f0262cSandi    $perm  = -1;
513f3f0262cSandi
51434aeb4afSAndreas Gohr    if($user || count($groups)){
515f3f0262cSandi        //add ALL group
516f3f0262cSandi        $groups[] = '@ALL';
517f3f0262cSandi        //add User
51834aeb4afSAndreas Gohr        if($user) $groups[] = $user;
519f3f0262cSandi        //build regexp
520f3f0262cSandi        $regexp   = join('|',$groups);
521f3f0262cSandi    }else{
522f3f0262cSandi        $regexp = '@ALL';
523f3f0262cSandi    }
524f3f0262cSandi
525f3f0262cSandi    //check exact match first
526e259aa79SAndreas Gohr    $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/'.$ci,$AUTH_ACL);
527f3f0262cSandi    if(count($matches)){
528f3f0262cSandi        foreach($matches as $match){
529f3f0262cSandi            $match = preg_replace('/#.*$/','',$match); //ignore comments
530f3f0262cSandi            $acl   = preg_split('/\s+/',$match);
5318ef6b7caSandi            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
532f3f0262cSandi            if($acl[2] > $perm){
533f3f0262cSandi                $perm = $acl[2];
534f3f0262cSandi            }
535f3f0262cSandi        }
536f3f0262cSandi        if($perm > -1){
537f3f0262cSandi            //we had a match - return it
538f3f0262cSandi            return $perm;
539f3f0262cSandi        }
540f3f0262cSandi    }
541f3f0262cSandi
542f3f0262cSandi    //still here? do the namespace checks
543f3f0262cSandi    if($ns){
5443e304b55SMichael Hamann        $path = $ns.':*';
545f3f0262cSandi    }else{
5463e304b55SMichael Hamann        $path = '*'; //root document
547f3f0262cSandi    }
548f3f0262cSandi
549f3f0262cSandi    do{
5503e304b55SMichael Hamann        $matches = preg_grep('/^'.preg_quote($path,'/').'\s+('.$regexp.')\s+/'.$ci,$AUTH_ACL);
551f3f0262cSandi        if(count($matches)){
552f3f0262cSandi            foreach($matches as $match){
553f3f0262cSandi                $match = preg_replace('/#.*$/','',$match); //ignore comments
554f3f0262cSandi                $acl   = preg_split('/\s+/',$match);
5558ef6b7caSandi                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
556f3f0262cSandi                if($acl[2] > $perm){
557f3f0262cSandi                    $perm = $acl[2];
558f3f0262cSandi                }
559f3f0262cSandi            }
560f3f0262cSandi            //we had a match - return it
561f3f0262cSandi            return $perm;
562f3f0262cSandi        }
563f3f0262cSandi
564f3f0262cSandi        //get next higher namespace
565f3f0262cSandi        $ns   = getNS($ns);
566f3f0262cSandi
5673e304b55SMichael Hamann        if($path != '*'){
5683e304b55SMichael Hamann            $path = $ns.':*';
5693e304b55SMichael Hamann            if($path == ':*') $path = '*';
570f3f0262cSandi        }else{
571f3f0262cSandi            //we did this already
572f3f0262cSandi            //looks like there is something wrong with the ACL
573f3f0262cSandi            //break here
574d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
575d5ce66f6SAndreas Gohr            return AUTH_NONE;
576f3f0262cSandi        }
577f3f0262cSandi    }while(1); //this should never loop endless
57852a5af8dSandi
57952a5af8dSandi    //still here? return no permissions
58052a5af8dSandi    return AUTH_NONE;
581f3f0262cSandi}
582f3f0262cSandi
583f3f0262cSandi/**
5846c2bb100SAndreas Gohr * Encode ASCII special chars
5856c2bb100SAndreas Gohr *
5866c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
5876c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
5886c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
5896c2bb100SAndreas Gohr * urlencoding!).
5906c2bb100SAndreas Gohr *
5916c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
5926c2bb100SAndreas Gohr *
5936c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
5946c2bb100SAndreas Gohr * @see rawurldecode()
5956c2bb100SAndreas Gohr */
596e838fc2eSAndreas Gohrfunction auth_nameencode($name,$skip_group=false){
597a424cd8eSchris    global $cache_authname;
598a424cd8eSchris    $cache =& $cache_authname;
59931784267SAndreas Gohr    $name  = (string) $name;
600a424cd8eSchris
60180601d26SAndreas Gohr    // never encode wildcard FS#1955
60280601d26SAndreas Gohr    if($name == '%USER%') return $name;
60380601d26SAndreas Gohr
604a424cd8eSchris    if (!isset($cache[$name][$skip_group])) {
605e838fc2eSAndreas Gohr        if($skip_group && $name{0} =='@'){
606a424cd8eSchris            $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
6071a9ae8e5SAndreas Gohr                    "'%'.dechex(ord(substr('\\1',-1)))",substr($name,1));
608e838fc2eSAndreas Gohr        }else{
609a424cd8eSchris            $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
6101a9ae8e5SAndreas Gohr                    "'%'.dechex(ord(substr('\\1',-1)))",$name);
611e838fc2eSAndreas Gohr        }
6126c2bb100SAndreas Gohr    }
6136c2bb100SAndreas Gohr
614a424cd8eSchris    return $cache[$name][$skip_group];
615a424cd8eSchris}
616a424cd8eSchris
6176c2bb100SAndreas Gohr/**
618f3f0262cSandi * Create a pronouncable password
619f3f0262cSandi *
62015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
62115fae107Sandi * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
62215fae107Sandi *
62315fae107Sandi * @return string  pronouncable password
624f3f0262cSandi */
625f3f0262cSandifunction auth_pwgen(){
626f3f0262cSandi    $pw = '';
627f3f0262cSandi    $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
628f3f0262cSandi    $v  = 'aeiou';              //vowels
629f3f0262cSandi    $a  = $c.$v;                //both
630f3f0262cSandi
631f3f0262cSandi    //use two syllables...
632f3f0262cSandi    for($i=0;$i < 2; $i++){
633f3f0262cSandi        $pw .= $c[rand(0, strlen($c)-1)];
634f3f0262cSandi        $pw .= $v[rand(0, strlen($v)-1)];
635f3f0262cSandi        $pw .= $a[rand(0, strlen($a)-1)];
636f3f0262cSandi    }
637f3f0262cSandi    //... and add a nice number
638f3f0262cSandi    $pw .= rand(10,99);
639f3f0262cSandi
640f3f0262cSandi    return $pw;
641f3f0262cSandi}
642f3f0262cSandi
643f3f0262cSandi/**
644f3f0262cSandi * Sends a password to the given user
645f3f0262cSandi *
64615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
64715fae107Sandi *
64815fae107Sandi * @return bool  true on success
649f3f0262cSandi */
650f3f0262cSandifunction auth_sendPassword($user,$password){
651f3f0262cSandi    global $conf;
652f3f0262cSandi    global $lang;
653cd52f92dSchris    global $auth;
654beca106aSAdrian Lang    if (!$auth) return false;
655cd52f92dSchris
656f3f0262cSandi    $hdrs  = '';
657d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
658cd52f92dSchris    $userinfo = $auth->getUserData($user);
659f3f0262cSandi
66087ddda95Sandi    if(!$userinfo['mail']) return false;
661f3f0262cSandi
662f3f0262cSandi    $text = rawLocale('password');
663ed7b5f09Sandi    $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
66487ddda95Sandi    $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
665f3f0262cSandi    $text = str_replace('@LOGIN@',$user,$text);
666f3f0262cSandi    $text = str_replace('@PASSWORD@',$password,$text);
667f3f0262cSandi    $text = str_replace('@TITLE@',$conf['title'],$text);
668f3f0262cSandi
66944f669e9Sandi    return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
67044f669e9Sandi            $lang['regpwmail'],
67144f669e9Sandi            $text,
67244f669e9Sandi            $conf['mailfrom']);
673f3f0262cSandi}
674f3f0262cSandi
675f3f0262cSandi/**
67615fae107Sandi * Register a new user
677f3f0262cSandi *
67815fae107Sandi * This registers a new user - Data is read directly from $_POST
67915fae107Sandi *
68015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
68115fae107Sandi *
68215fae107Sandi * @return bool  true on success, false on any error
683f3f0262cSandi */
684f3f0262cSandifunction register(){
685f3f0262cSandi    global $lang;
686eb5d07e4Sjan    global $conf;
687cd52f92dSchris    global $auth;
688f3f0262cSandi
689f3f0262cSandi    if(!$_POST['save']) return false;
690*3a48618aSAnika Henke    if(!actionOK('register')) return false;
691640145a5Sandi
692f3f0262cSandi    //clean username
693d752aedeSAndreas Gohr    $_POST['login'] = trim($auth->cleanUser($_POST['login']));
694d752aedeSAndreas Gohr
695f3f0262cSandi    //clean fullname and email
69654f0e6eaSAndreas Gohr    $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
69754f0e6eaSAndreas Gohr    $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
698f3f0262cSandi
699f3f0262cSandi    if( empty($_POST['login']) ||
700f3f0262cSandi        empty($_POST['fullname']) ||
701f3f0262cSandi        empty($_POST['email']) ){
702f3f0262cSandi        msg($lang['regmissing'],-1);
703f3f0262cSandi        return false;
704f3f0262cSandi    }
705f3f0262cSandi
706cab2716aSmatthias.grimm    if ($conf['autopasswd']) {
707cab2716aSmatthias.grimm        $pass = auth_pwgen();                // automatically generate password
708cab2716aSmatthias.grimm    } elseif (empty($_POST['pass']) ||
709cab2716aSmatthias.grimm            empty($_POST['passchk'])) {
710bf12ec81Sjan        msg($lang['regmissing'], -1);        // complain about missing passwords
711cab2716aSmatthias.grimm        return false;
712cab2716aSmatthias.grimm    } elseif ($_POST['pass'] != $_POST['passchk']) {
713bf12ec81Sjan        msg($lang['regbadpass'], -1);      // complain about misspelled passwords
714cab2716aSmatthias.grimm        return false;
715cab2716aSmatthias.grimm    } else {
716cab2716aSmatthias.grimm        $pass = $_POST['pass'];              // accept checked and valid password
717cab2716aSmatthias.grimm    }
718cab2716aSmatthias.grimm
719f3f0262cSandi    //check mail
72044f669e9Sandi    if(!mail_isvalid($_POST['email'])){
721f3f0262cSandi        msg($lang['regbadmail'],-1);
722f3f0262cSandi        return false;
723f3f0262cSandi    }
724f3f0262cSandi
725f3f0262cSandi    //okay try to create the user
7267d3c8d42SGabriel Birke    if(!$auth->triggerUserMod('create', array($_POST['login'],$pass,$_POST['fullname'],$_POST['email']))){
727f3f0262cSandi        msg($lang['reguexists'],-1);
728f3f0262cSandi        return false;
729f3f0262cSandi    }
730f3f0262cSandi
73102a498e7Schris    // create substitutions for use in notification email
73202a498e7Schris    $substitutions = array(
73302a498e7Schris            'NEWUSER' => $_POST['login'],
73402a498e7Schris            'NEWNAME' => $_POST['fullname'],
73502a498e7Schris            'NEWEMAIL' => $_POST['email'],
73602a498e7Schris            );
73702a498e7Schris
738cab2716aSmatthias.grimm    if (!$conf['autopasswd']) {
739cab2716aSmatthias.grimm        msg($lang['regsuccess2'],1);
74002a498e7Schris        notify('', 'register', '', $_POST['login'], false, $substitutions);
741cab2716aSmatthias.grimm        return true;
742cab2716aSmatthias.grimm    }
743cab2716aSmatthias.grimm
744cab2716aSmatthias.grimm    // autogenerated password? then send him the password
745f3f0262cSandi    if (auth_sendPassword($_POST['login'],$pass)){
746f3f0262cSandi        msg($lang['regsuccess'],1);
74702a498e7Schris        notify('', 'register', '', $_POST['login'], false, $substitutions);
748f3f0262cSandi        return true;
749f3f0262cSandi    }else{
750f3f0262cSandi        msg($lang['regmailfail'],-1);
751f3f0262cSandi        return false;
752f3f0262cSandi    }
753f3f0262cSandi}
754f3f0262cSandi
75510a76f6fSfrank/**
7568b06d178Schris * Update user profile
7578b06d178Schris *
7588b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
7598b06d178Schris */
7608b06d178Schrisfunction updateprofile() {
7618b06d178Schris    global $conf;
7628b06d178Schris    global $INFO;
7638b06d178Schris    global $lang;
764cd52f92dSchris    global $auth;
7658b06d178Schris
766bb4866bdSchris    if(empty($_POST['save'])) return false;
7671b2a85e8SAndreas Gohr    if(!checkSecurityToken()) return false;
7688b06d178Schris
769*3a48618aSAnika Henke    if(!actionOK('profile')) {
7708b06d178Schris        msg($lang['profna'],-1);
7718b06d178Schris        return false;
7728b06d178Schris    }
7738b06d178Schris
7748b06d178Schris    if ($_POST['newpass'] != $_POST['passchk']) {
7758b06d178Schris        msg($lang['regbadpass'], -1);      // complain about misspelled passwords
7768b06d178Schris        return false;
7778b06d178Schris    }
7788b06d178Schris
7798b06d178Schris    //clean fullname and email
78054f0e6eaSAndreas Gohr    $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
78154f0e6eaSAndreas Gohr    $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
7828b06d178Schris
7834369edafSAndy Webber    if ((empty($_POST['fullname']) && $auth->canDo('modName')) ||
7844369edafSAndy Webber        (empty($_POST['email']) && $auth->canDo('modMail'))) {
7858b06d178Schris        msg($lang['profnoempty'],-1);
7868b06d178Schris        return false;
7878b06d178Schris    }
7888b06d178Schris
7894369edafSAndy Webber    if (!mail_isvalid($_POST['email']) && $auth->canDo('modMail')){
7908b06d178Schris        msg($lang['regbadmail'],-1);
7918b06d178Schris        return false;
7928b06d178Schris    }
7938b06d178Schris
7944c21b7eeSAndreas Gohr    if ($_POST['fullname'] != $INFO['userinfo']['name'] && $auth->canDo('modName')) $changes['name'] = $_POST['fullname'];
7954c21b7eeSAndreas Gohr    if ($_POST['email'] != $INFO['userinfo']['mail'] && $auth->canDo('modMail')) $changes['mail'] = $_POST['email'];
796cf626a62SAndreas Gohr    if (!empty($_POST['newpass']) && $auth->canDo('modPass')) $changes['pass'] = $_POST['newpass'];
7974c21b7eeSAndreas Gohr
7988b06d178Schris    if (!count($changes)) {
7998b06d178Schris        msg($lang['profnochange'], -1);
8008b06d178Schris        return false;
8018b06d178Schris    }
8028b06d178Schris
8038b06d178Schris    if ($conf['profileconfirm']) {
804df466c7aSAndreas Gohr        if (!$auth->checkPass($_SERVER['REMOTE_USER'], $_POST['oldpass'])) {
8058b06d178Schris            msg($lang['badlogin'],-1);
8068b06d178Schris            return false;
8078b06d178Schris        }
8088b06d178Schris    }
8098b06d178Schris
810a0b5b007SChris Smith    if ($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
811a0b5b007SChris Smith        // update cookie and session with the changed data
812a0b5b007SChris Smith        $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
8134b7f9e70STom N Harris        list($user,$sticky,$pass) = explode('|',$cookie,3);
814a0b5b007SChris Smith        if ($changes['pass']) $pass = PMA_blowfish_encrypt($changes['pass'],auth_cookiesalt());
815a0b5b007SChris Smith
816a0b5b007SChris Smith        auth_setCookie($_SERVER['REMOTE_USER'],$pass,(bool)$sticky);
81725b2a98cSMichael Klier        return true;
818a0b5b007SChris Smith    }
8198b06d178Schris}
8208b06d178Schris
8218b06d178Schris/**
8228b06d178Schris * Send a  new password
8238b06d178Schris *
8241d5856cfSAndreas Gohr * This function handles both phases of the password reset:
8251d5856cfSAndreas Gohr *
8261d5856cfSAndreas Gohr *   - handling the first request of password reset
8271d5856cfSAndreas Gohr *   - validating the password reset auth token
8281d5856cfSAndreas Gohr *
8298b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
8308b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
8311d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
8328b06d178Schris *
8338b06d178Schris * @return bool true on success, false on any error
8348b06d178Schris */
8358b06d178Schrisfunction act_resendpwd(){
8368b06d178Schris    global $lang;
8378b06d178Schris    global $conf;
838cd52f92dSchris    global $auth;
8398b06d178Schris
840*3a48618aSAnika Henke    if(!actionOK('resendpwd')) {
8418b06d178Schris        msg($lang['resendna'],-1);
8428b06d178Schris        return false;
8438b06d178Schris    }
8448b06d178Schris
8451d5856cfSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
8468b06d178Schris
8471d5856cfSAndreas Gohr    if($token){
8481d5856cfSAndreas Gohr        // we're in token phase
8491d5856cfSAndreas Gohr
8501d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
8511d5856cfSAndreas Gohr        if(!@file_exists($tfile)){
8521d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'],-1);
8531d5856cfSAndreas Gohr            return false;
8541d5856cfSAndreas Gohr        }
8551d5856cfSAndreas Gohr        $user = io_readfile($tfile);
8561d5856cfSAndreas Gohr        @unlink($tfile);
857cd52f92dSchris        $userinfo = $auth->getUserData($user);
8588b06d178Schris        if(!$userinfo['mail']) {
8598b06d178Schris            msg($lang['resendpwdnouser'], -1);
8608b06d178Schris            return false;
8618b06d178Schris        }
8628b06d178Schris
8638b06d178Schris        $pass = auth_pwgen();
8647d3c8d42SGabriel Birke        if (!$auth->triggerUserMod('modify', array($user,array('pass' => $pass)))) {
8658b06d178Schris            msg('error modifying user data',-1);
8668b06d178Schris            return false;
8678b06d178Schris        }
8688b06d178Schris
8698b06d178Schris        if (auth_sendPassword($user,$pass)) {
8708b06d178Schris            msg($lang['resendpwdsuccess'],1);
8718b06d178Schris        } else {
8728b06d178Schris            msg($lang['regmailfail'],-1);
8738b06d178Schris        }
8748b06d178Schris        return true;
8751d5856cfSAndreas Gohr
8761d5856cfSAndreas Gohr    } else {
8771d5856cfSAndreas Gohr        // we're in request phase
8781d5856cfSAndreas Gohr
8791d5856cfSAndreas Gohr        if(!$_POST['save']) return false;
8801d5856cfSAndreas Gohr
8811d5856cfSAndreas Gohr        if (empty($_POST['login'])) {
8821d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
8831d5856cfSAndreas Gohr            return false;
8841d5856cfSAndreas Gohr        } else {
885d752aedeSAndreas Gohr            $user = trim($auth->cleanUser($_POST['login']));
8861d5856cfSAndreas Gohr        }
8871d5856cfSAndreas Gohr
8881d5856cfSAndreas Gohr        $userinfo = $auth->getUserData($user);
8891d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
8901d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
8911d5856cfSAndreas Gohr            return false;
8921d5856cfSAndreas Gohr        }
8931d5856cfSAndreas Gohr
8941d5856cfSAndreas Gohr        // generate auth token
8951d5856cfSAndreas Gohr        $token = md5(auth_cookiesalt().$user); //secret but user based
8961d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
8971d5856cfSAndreas Gohr        $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
8981d5856cfSAndreas Gohr
8991d5856cfSAndreas Gohr        io_saveFile($tfile,$user);
9001d5856cfSAndreas Gohr
9011d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
9021d5856cfSAndreas Gohr        $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
9031d5856cfSAndreas Gohr        $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
9041d5856cfSAndreas Gohr        $text = str_replace('@LOGIN@',$user,$text);
9051d5856cfSAndreas Gohr        $text = str_replace('@TITLE@',$conf['title'],$text);
9061d5856cfSAndreas Gohr        $text = str_replace('@CONFIRM@',$url,$text);
9071d5856cfSAndreas Gohr
9081d5856cfSAndreas Gohr        if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
9091d5856cfSAndreas Gohr                     $lang['regpwmail'],
9101d5856cfSAndreas Gohr                     $text,
9111d5856cfSAndreas Gohr                     $conf['mailfrom'])){
9121d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'],1);
9131d5856cfSAndreas Gohr        }else{
9141d5856cfSAndreas Gohr            msg($lang['regmailfail'],-1);
9151d5856cfSAndreas Gohr        }
9161d5856cfSAndreas Gohr        return true;
9171d5856cfSAndreas Gohr    }
9181d5856cfSAndreas Gohr
9191d5856cfSAndreas Gohr    return false; // never reached
9208b06d178Schris}
9218b06d178Schris
9228b06d178Schris/**
923b0855b11Sandi * Encrypts a password using the given method and salt
924b0855b11Sandi *
925b0855b11Sandi * If the selected method needs a salt and none was given, a random one
926b0855b11Sandi * is chosen.
927b0855b11Sandi *
928b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
929b0855b11Sandi * @return  string  The crypted password
930b0855b11Sandi */
931577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear,$method='',$salt=null){
932b0855b11Sandi    global $conf;
933b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
93410a76f6fSfrank
9353a0a2d05SAndreas Gohr    $pass  = new PassHash();
9363a0a2d05SAndreas Gohr    $call  = 'hash_'.$method;
937b0855b11Sandi
9383a0a2d05SAndreas Gohr    if(!method_exists($pass,$call)){
939b0855b11Sandi        msg("Unsupported crypt method $method",-1);
9403a0a2d05SAndreas Gohr        return false;
941b0855b11Sandi    }
9423a0a2d05SAndreas Gohr
9433a0a2d05SAndreas Gohr    return $pass->$call($clear,$salt);
944b0855b11Sandi}
945b0855b11Sandi
946b0855b11Sandi/**
947b0855b11Sandi * Verifies a cleartext password against a crypted hash
948b0855b11Sandi *
949b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
950b0855b11Sandi * @return  bool
951b0855b11Sandi */
952b0855b11Sandifunction auth_verifyPassword($clear,$crypt){
9533a0a2d05SAndreas Gohr    $pass = new PassHash();
9543a0a2d05SAndreas Gohr    return $pass->verify_hash($clear,$crypt);
955b0855b11Sandi}
956340756e4Sandi
957a0b5b007SChris Smith/**
958a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
959a0b5b007SChris Smith *
960a0b5b007SChris Smith * @param string  $user       username
961a0b5b007SChris Smith * @param string  $pass       encrypted password
962a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
963a0b5b007SChris Smith */
964a0b5b007SChris Smithfunction auth_setCookie($user,$pass,$sticky) {
965a0b5b007SChris Smith    global $conf;
966a0b5b007SChris Smith    global $auth;
96779d00841SOliver Geisen    global $USERINFO;
968a0b5b007SChris Smith
969beca106aSAdrian Lang    if (!$auth) return false;
970a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
971a0b5b007SChris Smith
972a0b5b007SChris Smith    // set cookie
973645c0a36SAndreas Gohr    $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
974c66972f2SAdrian Lang    $time = $sticky ? (time()+60*60*24*365) : 0; //one year
975a0b5b007SChris Smith    if (version_compare(PHP_VERSION, '5.2.0', '>')) {
976a0b5b007SChris Smith        setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true);
977a0b5b007SChris Smith    }else{
978a0b5b007SChris Smith        setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()));
979a0b5b007SChris Smith    }
980a0b5b007SChris Smith    // set session
981a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
982a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['pass'] = $pass;
983a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
984a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
985a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
986a0b5b007SChris Smith}
987a0b5b007SChris Smith
988645c0a36SAndreas Gohr/**
989645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
990645c0a36SAndreas Gohr *
991645c0a36SAndreas Gohr * @returns array
992645c0a36SAndreas Gohr */
993645c0a36SAndreas Gohrfunction auth_getCookie(){
994c66972f2SAdrian Lang    if (!isset($_COOKIE[DOKU_COOKIE])) {
995c66972f2SAdrian Lang        return array(null, null, null);
996c66972f2SAdrian Lang    }
997645c0a36SAndreas Gohr    list($user,$sticky,$pass) = explode('|',$_COOKIE[DOKU_COOKIE],3);
998645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
999645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1000645c0a36SAndreas Gohr    $user   = base64_decode($user);
1001645c0a36SAndreas Gohr    return array($user,$sticky,$pass);
1002645c0a36SAndreas Gohr}
1003645c0a36SAndreas Gohr
1004e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1005