xref: /dokuwiki/inc/auth.php (revision 9c29eea515b336b23187a86f5b55443571fcba01)
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;
39*9c29eea5SJan Schumann    global $plugin_controller;
409a9714acSDominik Eckelmann    $AUTH_ACL = array();
4103c4aec3Schris
4216905344SAndreas Gohr    if(!$conf['useacl']) return false;
4316905344SAndreas Gohr
44*9c29eea5SJan Schumann    // try to load auth backend from plugins
45*9c29eea5SJan Schumann    $plugins = $plugin_controller->getList('auth');
46*9c29eea5SJan Schumann    foreach ($plugin_controller->getList('auth') as $plugin) {
47*9c29eea5SJan Schumann    	if ($conf['authtype'] === $plugin) {
48*9c29eea5SJan Schumann    		$auth = $plugin_controller->load('auth', $plugin)->getAuth();
49*9c29eea5SJan Schumann    		break;
50*9c29eea5SJan Schumann    	}
51*9c29eea5SJan Schumann    }
52*9c29eea5SJan Schumann
53*9c29eea5SJan Schumann    if (!$auth) {
5416905344SAndreas Gohr	    // load the the backend auth functions and instantiate the auth object XXX
558b06d178Schris	    if (@file_exists(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php')) {
568b06d178Schris	        require_once(DOKU_INC.'inc/auth/basic.class.php');
578b06d178Schris	        require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php');
588b06d178Schris
598b06d178Schris	        $auth_class = "auth_".$conf['authtype'];
60cd52f92dSchris	        if (class_exists($auth_class)) {
618b06d178Schris	            $auth = new $auth_class();
62d2dde4ebSMatthias Grimm	            if ($auth->success == false) {
630f4f4adfSAndreas Gohr	                // degrade to unauthenticated user
64d2dde4ebSMatthias Grimm	                unset($auth);
650f4f4adfSAndreas Gohr	                auth_logoff();
66cd52f92dSchris	                msg($lang['authtempfail'], -1);
67d2dde4ebSMatthias Grimm	            }
688b06d178Schris	        } else {
693816dcbcSAndreas Gohr	            nice_die($lang['authmodfailed']);
70cd52f92dSchris	        }
71cd52f92dSchris	    } else {
723816dcbcSAndreas Gohr	        nice_die($lang['authmodfailed']);
738b06d178Schris	    }
74*9c29eea5SJan Schumann    }
75f3f0262cSandi
7616905344SAndreas Gohr    if(!$auth) return;
7716905344SAndreas Gohr
7816905344SAndreas Gohr    // do the login either by cookie or provided credentials XXX
79bbbd6568SAndreas Gohr    if (!isset($_REQUEST['u'])) $_REQUEST['u'] = '';
80bbbd6568SAndreas Gohr    if (!isset($_REQUEST['p'])) $_REQUEST['p'] = '';
81bbbd6568SAndreas Gohr    if (!isset($_REQUEST['r'])) $_REQUEST['r'] = '';
82b2c0d874SGina Haeussge    $_REQUEST['http_credentials'] = false;
8317f89d7eSMichael Klier    if (!$conf['rememberme']) $_REQUEST['r'] = false;
84bbbd6568SAndreas Gohr
85b2665af7SMichael Hamann    // handle renamed HTTP_AUTHORIZATION variable (can happen when a fix like
86b2665af7SMichael Hamann    // the one presented at
87b2665af7SMichael Hamann    // http://www.besthostratings.com/articles/http-auth-php-cgi.html is used
88b2665af7SMichael Hamann    // for enabling HTTP authentication with CGI/SuExec)
89b2665af7SMichael Hamann    if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
90b2665af7SMichael Hamann        $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
91528ddc7cSAndreas Gohr    // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
9206156f3cSAndreas Gohr    if(isset($_SERVER['HTTP_AUTHORIZATION'])){
93528ddc7cSAndreas Gohr        list($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']) =
94528ddc7cSAndreas Gohr            explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
95528ddc7cSAndreas Gohr    }
96528ddc7cSAndreas Gohr
971e8c9c90SAndreas Gohr    // if no credentials were given try to use HTTP auth (for SSO)
984a26ad85Schris    if(empty($_REQUEST['u']) && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])){
991e8c9c90SAndreas Gohr        $_REQUEST['u'] = $_SERVER['PHP_AUTH_USER'];
1001e8c9c90SAndreas Gohr        $_REQUEST['p'] = $_SERVER['PHP_AUTH_PW'];
101b2c0d874SGina Haeussge        $_REQUEST['http_credentials'] = true;
1021e8c9c90SAndreas Gohr    }
1031e8c9c90SAndreas Gohr
104191bb90aSAndreas Gohr    // apply cleaning
105191bb90aSAndreas Gohr    $_REQUEST['u'] = $auth->cleanUser($_REQUEST['u']);
106191bb90aSAndreas Gohr
107c66972f2SAdrian Lang    if(isset($_REQUEST['authtok'])){
108f13fa892SAndreas Gohr        // when an authentication token is given, trust the session
109f13fa892SAndreas Gohr        auth_validateToken($_REQUEST['authtok']);
110f13fa892SAndreas Gohr    }elseif(!is_null($auth) && $auth->canDo('external')){
111f13fa892SAndreas Gohr        // external trust mechanism in place
112f5cb575dSAndreas Gohr        $auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
113f5cb575dSAndreas Gohr    }else{
1146080c584SRobin Gareus        $evdata = array(
1156080c584SRobin Gareus                'user'     => $_REQUEST['u'],
1166080c584SRobin Gareus                'password' => $_REQUEST['p'],
1176080c584SRobin Gareus                'sticky'   => $_REQUEST['r'],
1186080c584SRobin Gareus                'silent'   => $_REQUEST['http_credentials'],
1196080c584SRobin Gareus                );
120b5ee21aaSAdrian Lang        trigger_event('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
121f5cb575dSAndreas Gohr    }
122f5cb575dSAndreas Gohr
12316905344SAndreas Gohr    //load ACL into a global array XXX
12475c93b77SAndreas Gohr    $AUTH_ACL = auth_loadACL();
12575c93b77SAndreas Gohr}
12675c93b77SAndreas Gohr
12775c93b77SAndreas Gohr/**
12875c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards
12975c93b77SAndreas Gohr *
13075c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
13175c93b77SAndreas Gohr * @returns array
13275c93b77SAndreas Gohr */
13375c93b77SAndreas Gohrfunction auth_loadACL(){
13475c93b77SAndreas Gohr    global $config_cascade;
13575c93b77SAndreas Gohr
13675c93b77SAndreas Gohr    if(!is_readable($config_cascade['acl']['default'])) return array();
13775c93b77SAndreas Gohr
13875c93b77SAndreas Gohr    $acl = file($config_cascade['acl']['default']);
13975c93b77SAndreas Gohr
140191bb90aSAndreas Gohr    //support user wildcard
141f8cc3354SGuy Brand    if(isset($_SERVER['REMOTE_USER'])){
14275c93b77SAndreas Gohr        $len = count($acl);
14375c93b77SAndreas Gohr        for($i=0; $i<$len; $i++){
14475c93b77SAndreas Gohr            if($acl[$i]{0} == '#') continue;
14575c93b77SAndreas Gohr            list($id,$rest) = preg_split('/\s+/',$acl[$i],2);
14675c93b77SAndreas Gohr            $id   = str_replace('%USER%',cleanID($_SERVER['REMOTE_USER']),$id);
14775c93b77SAndreas Gohr            $rest = str_replace('%USER%',auth_nameencode($_SERVER['REMOTE_USER']),$rest);
14875c93b77SAndreas Gohr            $acl[$i] = "$id\t$rest";
149a8fe108bSGuy Brand        }
15011799630Sandi    }
15175c93b77SAndreas Gohr    return $acl;
152f3f0262cSandi}
153f3f0262cSandi
154b5ee21aaSAdrian Langfunction auth_login_wrapper($evdata) {
155b5ee21aaSAdrian Lang    return auth_login($evdata['user'],
156b5ee21aaSAdrian Lang                      $evdata['password'],
157b5ee21aaSAdrian Lang                      $evdata['sticky'],
158b5ee21aaSAdrian Lang                      $evdata['silent']);
159b5ee21aaSAdrian Lang}
160b5ee21aaSAdrian Lang
161f3f0262cSandi/**
162f3f0262cSandi * This tries to login the user based on the sent auth credentials
163f3f0262cSandi *
164f3f0262cSandi * The authentication works like this: if a username was given
16515fae107Sandi * a new login is assumed and user/password are checked. If they
16615fae107Sandi * are correct the password is encrypted with blowfish and stored
16715fae107Sandi * together with the username in a cookie - the same info is stored
16815fae107Sandi * in the session, too. Additonally a browserID is stored in the
16915fae107Sandi * session.
17015fae107Sandi *
17115fae107Sandi * If no username was given the cookie is checked: if the username,
17215fae107Sandi * crypted password and browserID match between session and cookie
17315fae107Sandi * no further testing is done and the user is accepted
17415fae107Sandi *
17515fae107Sandi * If a cookie was found but no session info was availabe the
176136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
17715fae107Sandi * together with username rechecked by calling this function again.
178f3f0262cSandi *
179f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
180f3f0262cSandi * are set.
18115fae107Sandi *
18215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
18315fae107Sandi *
18415fae107Sandi * @param   string  $user    Username
18515fae107Sandi * @param   string  $pass    Cleartext Password
18615fae107Sandi * @param   bool    $sticky  Cookie should not expire
187f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
18815fae107Sandi * @return  bool             true on successful auth
189f3f0262cSandi */
190f112c2faSAndreas Gohrfunction auth_login($user,$pass,$sticky=false,$silent=false){
191f3f0262cSandi    global $USERINFO;
192f3f0262cSandi    global $conf;
193f3f0262cSandi    global $lang;
194cd52f92dSchris    global $auth;
195132bdbfeSandi    $sticky ? $sticky = true : $sticky = false; //sanity check
196f3f0262cSandi
197beca106aSAdrian Lang    if (!$auth) return false;
198beca106aSAdrian Lang
199bbbd6568SAndreas Gohr    if(!empty($user)){
200132bdbfeSandi        //usual login
201cd52f92dSchris        if ($auth->checkPass($user,$pass)){
202132bdbfeSandi            // make logininfo globally available
203f3f0262cSandi            $_SERVER['REMOTE_USER'] = $user;
20432ed2b36SAndreas Gohr            $secret = auth_cookiesalt(!$sticky); //bind non-sticky to session
205e940aea4SAndreas Gohr            auth_setCookie($user,PMA_blowfish_encrypt($pass,$secret),$sticky);
206132bdbfeSandi            return true;
207f3f0262cSandi        }else{
208f3f0262cSandi            //invalid credentials - log off
209f112c2faSAndreas Gohr            if(!$silent) msg($lang['badlogin'],-1);
210f3f0262cSandi            auth_logoff();
211132bdbfeSandi            return false;
212f3f0262cSandi        }
213f3f0262cSandi    }else{
214132bdbfeSandi        // read cookie information
215645c0a36SAndreas Gohr        list($user,$sticky,$pass) = auth_getCookie();
216132bdbfeSandi        if($user && $pass){
217132bdbfeSandi            // we got a cookie - see if we can trust it
218fa7c70ffSAdrian Lang
219fa7c70ffSAdrian Lang            // get session info
220fa7c70ffSAdrian Lang            $session = $_SESSION[DOKU_COOKIE]['auth'];
221132bdbfeSandi            if(isset($session) &&
2227172dbc0SAndreas Gohr                    $auth->useSessionCache($user) &&
2234c989037SChris Smith                    ($session['time'] >= time()-$conf['auth_security_timeout']) &&
224132bdbfeSandi                    ($session['user'] == $user) &&
225234ce57eSAndreas Gohr                    ($session['pass'] == sha1($pass)) &&  //still crypted
226132bdbfeSandi                    ($session['buid'] == auth_browseruid()) ){
227234ce57eSAndreas Gohr
228132bdbfeSandi                // he has session, cookie and browser right - let him in
229132bdbfeSandi                $_SERVER['REMOTE_USER'] = $user;
230132bdbfeSandi                $USERINFO = $session['info']; //FIXME move all references to session
231132bdbfeSandi                return true;
232132bdbfeSandi            }
233f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
23432ed2b36SAndreas Gohr            $secret = auth_cookiesalt(!$sticky); //bind non-sticky to session
235e940aea4SAndreas Gohr            $pass = PMA_blowfish_decrypt($pass,$secret);
236f112c2faSAndreas Gohr            return auth_login($user,$pass,$sticky,true);
237132bdbfeSandi        }
238132bdbfeSandi    }
239f3f0262cSandi    //just to be sure
240883179a4SAndreas Gohr    auth_logoff(true);
241132bdbfeSandi    return false;
242f3f0262cSandi}
243132bdbfeSandi
244132bdbfeSandi/**
245f13fa892SAndreas Gohr * Checks if a given authentication token was stored in the session
246f13fa892SAndreas Gohr *
247f13fa892SAndreas Gohr * Will setup authentication data using data from the session if the
248f13fa892SAndreas Gohr * token is correct. Will exit with a 401 Status if not.
249f13fa892SAndreas Gohr *
250f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
251f13fa892SAndreas Gohr * @param  string $token The authentication token
252f13fa892SAndreas Gohr * @return boolean true (or will exit on failure)
253f13fa892SAndreas Gohr */
254f13fa892SAndreas Gohrfunction auth_validateToken($token){
255f13fa892SAndreas Gohr    if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']){
256f13fa892SAndreas Gohr        // bad token
257f13fa892SAndreas Gohr        header("HTTP/1.0 401 Unauthorized");
258f13fa892SAndreas Gohr        print 'Invalid auth token - maybe the session timed out';
259f13fa892SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
260f13fa892SAndreas Gohr        exit;
261f13fa892SAndreas Gohr    }
262f13fa892SAndreas Gohr    // still here? trust the session data
263f13fa892SAndreas Gohr    global $USERINFO;
264f13fa892SAndreas Gohr    $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
265f13fa892SAndreas Gohr    $USERINFO = $_SESSION[DOKU_COOKIE]['auth']['info'];
266f13fa892SAndreas Gohr    return true;
267f13fa892SAndreas Gohr}
268f13fa892SAndreas Gohr
269f13fa892SAndreas Gohr/**
270f13fa892SAndreas Gohr * Create an auth token and store it in the session
271f13fa892SAndreas Gohr *
272f13fa892SAndreas Gohr * NOTE: this is completely unrelated to the getSecurityToken() function
273f13fa892SAndreas Gohr *
274f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
275f13fa892SAndreas Gohr * @return string The auth token
276f13fa892SAndreas Gohr */
277f13fa892SAndreas Gohrfunction auth_createToken(){
278f13fa892SAndreas Gohr    $token = md5(mt_rand());
27909c2d803SAndreas Gohr    @session_start(); // reopen the session if needed
280f13fa892SAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
28109c2d803SAndreas Gohr    session_write_close();
282f13fa892SAndreas Gohr    return $token;
283f13fa892SAndreas Gohr}
284f13fa892SAndreas Gohr
285f13fa892SAndreas Gohr/**
286136ce040Sandi * Builds a pseudo UID from browser and IP data
287132bdbfeSandi *
288132bdbfeSandi * This is neither unique nor unfakable - still it adds some
289136ce040Sandi * security. Using the first part of the IP makes sure
290136ce040Sandi * proxy farms like AOLs are stil okay.
29115fae107Sandi *
29215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
29315fae107Sandi *
29415fae107Sandi * @return  string  a MD5 sum of various browser headers
295132bdbfeSandi */
296132bdbfeSandifunction auth_browseruid(){
2972f9daf16SAndreas Gohr    $ip   = clientIP(true);
298132bdbfeSandi    $uid  = '';
299132bdbfeSandi    $uid .= $_SERVER['HTTP_USER_AGENT'];
300132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
301132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
302132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
3032f9daf16SAndreas Gohr    $uid .= substr($ip,0,strpos($ip,'.'));
304132bdbfeSandi    return md5($uid);
305132bdbfeSandi}
306132bdbfeSandi
307132bdbfeSandi/**
308132bdbfeSandi * Creates a random key to encrypt the password in cookies
30915fae107Sandi *
31015fae107Sandi * This function tries to read the password for encrypting
31198407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
31215fae107Sandi * if no such file is found a random key is created and
31315fae107Sandi * and stored in this file.
31415fae107Sandi *
31515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
31632ed2b36SAndreas Gohr * @param   bool $addsession if true, the sessionid is added to the salt
31715fae107Sandi * @return  string
318132bdbfeSandi */
31932ed2b36SAndreas Gohrfunction auth_cookiesalt($addsession=false){
320132bdbfeSandi    global $conf;
32198407a7aSandi    $file = $conf['metadir'].'/_htcookiesalt';
322132bdbfeSandi    $salt = io_readFile($file);
323132bdbfeSandi    if(empty($salt)){
324132bdbfeSandi        $salt = uniqid(rand(),true);
325132bdbfeSandi        io_saveFile($file,$salt);
326132bdbfeSandi    }
32732ed2b36SAndreas Gohr    if($addsession){
32832ed2b36SAndreas Gohr        $salt .= session_id();
32932ed2b36SAndreas Gohr    }
330132bdbfeSandi    return $salt;
331f3f0262cSandi}
332f3f0262cSandi
333f3f0262cSandi/**
334883179a4SAndreas Gohr * Log out the current user
335883179a4SAndreas Gohr *
336f3f0262cSandi * This clears all authentication data and thus log the user
337883179a4SAndreas Gohr * off. It also clears session data.
33815fae107Sandi *
33915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
340883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
341f3f0262cSandi */
342883179a4SAndreas Gohrfunction auth_logoff($keepbc=false){
343f3f0262cSandi    global $conf;
344f3f0262cSandi    global $USERINFO;
3458b06d178Schris    global $INFO, $ID;
3465298a619SAndreas Gohr    global $auth;
34737065e65Sandi
348d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
349e9621d07SAndreas Gohr    @session_start();
350e9621d07SAndreas Gohr
351e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
352e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
353e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
354e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
355e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
356e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
357883179a4SAndreas Gohr    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
358e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
35937065e65Sandi    if(isset($_SERVER['REMOTE_USER']))
360f3f0262cSandi        unset($_SERVER['REMOTE_USER']);
361132bdbfeSandi    $USERINFO=null; //FIXME
362f5c6743cSAndreas Gohr
36373ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
364f5c6743cSAndreas Gohr    if (version_compare(PHP_VERSION, '5.2.0', '>')) {
36573ab87deSGabriel Birke        setcookie(DOKU_COOKIE,'',time()-600000,$cookieDir,'',($conf['securecookie'] && is_ssl()),true);
366f5c6743cSAndreas Gohr    }else{
36773ab87deSGabriel Birke        setcookie(DOKU_COOKIE,'',time()-600000,$cookieDir,'',($conf['securecookie'] && is_ssl()));
368f5c6743cSAndreas Gohr    }
3695298a619SAndreas Gohr
370880f62faSAndreas Gohr    if($auth) $auth->logOff();
371f3f0262cSandi}
372f3f0262cSandi
373f3f0262cSandi/**
374f8cc712eSAndreas Gohr * Check if a user is a manager
375f8cc712eSAndreas Gohr *
376f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
377f8cc712eSAndreas Gohr * user.
378f8cc712eSAndreas Gohr *
379f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
380f8cc712eSAndreas Gohr *
381f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
382f8cc712eSAndreas Gohr * @see    auth_isadmin
383f8cc712eSAndreas Gohr * @param  string user      - Username
384f8cc712eSAndreas Gohr * @param  array  groups    - List of groups the user is in
385f8cc712eSAndreas Gohr * @param  bool   adminonly - when true checks if user is admin
386f8cc712eSAndreas Gohr */
387f8cc712eSAndreas Gohrfunction auth_ismanager($user=null,$groups=null,$adminonly=false){
388f8cc712eSAndreas Gohr    global $conf;
389f8cc712eSAndreas Gohr    global $USERINFO;
390d752aedeSAndreas Gohr    global $auth;
391f8cc712eSAndreas Gohr
392beca106aSAdrian Lang    if (!$auth) return false;
393c66972f2SAdrian Lang    if(is_null($user)) {
394c66972f2SAdrian Lang        if (!isset($_SERVER['REMOTE_USER'])) {
395c66972f2SAdrian Lang            return false;
396c66972f2SAdrian Lang        } else {
397c66972f2SAdrian Lang            $user = $_SERVER['REMOTE_USER'];
398c66972f2SAdrian Lang        }
399c66972f2SAdrian Lang    }
400d6dc956fSAndreas Gohr    if(is_null($groups)){
401d6dc956fSAndreas Gohr        $groups = (array) $USERINFO['grps'];
402e259aa79SAndreas Gohr    }
403e259aa79SAndreas Gohr
404d6dc956fSAndreas Gohr    // check superuser match
405d6dc956fSAndreas Gohr    if(auth_isMember($conf['superuser'],$user, $groups)) return true;
406d6dc956fSAndreas Gohr    if($adminonly) return false;
407e259aa79SAndreas Gohr    // check managers
408d6dc956fSAndreas Gohr    if(auth_isMember($conf['manager'],$user, $groups)) return true;
40900ce12daSChris Smith
410f8cc712eSAndreas Gohr    return false;
411f8cc712eSAndreas Gohr}
412f8cc712eSAndreas Gohr
413f8cc712eSAndreas Gohr/**
414f8cc712eSAndreas Gohr * Check if a user is admin
415f8cc712eSAndreas Gohr *
416f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
417f8cc712eSAndreas Gohr *
418f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
419f8cc712eSAndreas Gohr *
420f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
421f8cc712eSAndreas Gohr * @see auth_ismanager
422f8cc712eSAndreas Gohr */
423f8cc712eSAndreas Gohrfunction auth_isadmin($user=null,$groups=null){
424f8cc712eSAndreas Gohr    return auth_ismanager($user,$groups,true);
425f8cc712eSAndreas Gohr}
426f8cc712eSAndreas Gohr
427d6dc956fSAndreas Gohr
428d6dc956fSAndreas Gohr/**
429d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
430d6dc956fSAndreas Gohr * users and groups to determine membership status
431d6dc956fSAndreas Gohr *
432d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
433d6dc956fSAndreas Gohr *
434d6dc956fSAndreas Gohr * @param $memberlist string commaseparated list of allowed users and groups
435d6dc956fSAndreas Gohr * @param $user       string user to match against
436d6dc956fSAndreas Gohr * @param $groups     array  groups the user is member of
437d6dc956fSAndreas Gohr * @returns bool      true for membership acknowledged
438d6dc956fSAndreas Gohr */
439d6dc956fSAndreas Gohrfunction auth_isMember($memberlist,$user,array $groups){
440d6dc956fSAndreas Gohr    global $auth;
441d6dc956fSAndreas Gohr    if (!$auth) return false;
442d6dc956fSAndreas Gohr
443d6dc956fSAndreas Gohr    // clean user and groups
4444f56ecbfSAdrian Lang    if(!$auth->isCaseSensitive()){
445d6dc956fSAndreas Gohr        $user = utf8_strtolower($user);
446d6dc956fSAndreas Gohr        $groups = array_map('utf8_strtolower',$groups);
447d6dc956fSAndreas Gohr    }
448d6dc956fSAndreas Gohr    $user = $auth->cleanUser($user);
449d6dc956fSAndreas Gohr    $groups = array_map(array($auth,'cleanGroup'),$groups);
450d6dc956fSAndreas Gohr
451d6dc956fSAndreas Gohr    // extract the memberlist
452d6dc956fSAndreas Gohr    $members = explode(',',$memberlist);
453d6dc956fSAndreas Gohr    $members = array_map('trim',$members);
454d6dc956fSAndreas Gohr    $members = array_unique($members);
455d6dc956fSAndreas Gohr    $members = array_filter($members);
456d6dc956fSAndreas Gohr
457d6dc956fSAndreas Gohr    // compare cleaned values
458d6dc956fSAndreas Gohr    foreach($members as $member){
4594f56ecbfSAdrian Lang        if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member);
460d6dc956fSAndreas Gohr        if($member[0] == '@'){
461d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member,1));
462d6dc956fSAndreas Gohr            if(in_array($member, $groups)) return true;
463d6dc956fSAndreas Gohr        }else{
464d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
465d6dc956fSAndreas Gohr            if($member == $user) return true;
466d6dc956fSAndreas Gohr        }
467d6dc956fSAndreas Gohr    }
468d6dc956fSAndreas Gohr
469d6dc956fSAndreas Gohr    // still here? not a member!
470d6dc956fSAndreas Gohr    return false;
471d6dc956fSAndreas Gohr}
472d6dc956fSAndreas Gohr
473f8cc712eSAndreas Gohr/**
47415fae107Sandi * Convinience function for auth_aclcheck()
47515fae107Sandi *
47615fae107Sandi * This checks the permissions for the current user
47715fae107Sandi *
47815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
47915fae107Sandi *
4801698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
48115fae107Sandi * @return int          permission level
482f3f0262cSandi */
483f3f0262cSandifunction auth_quickaclcheck($id){
484f3f0262cSandi    global $conf;
485f3f0262cSandi    global $USERINFO;
486f3f0262cSandi    # if no ACL is used always return upload rights
487f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
488f3f0262cSandi    return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
489f3f0262cSandi}
490f3f0262cSandi
491f3f0262cSandi/**
492f3f0262cSandi * Returns the maximum rights a user has for
493f3f0262cSandi * the given ID or its namespace
49415fae107Sandi *
49515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
49615fae107Sandi *
4971698b983Smichael * @param  string  $id     page ID (needs to be resolved and cleaned)
49815fae107Sandi * @param  string  $user   Username
49915fae107Sandi * @param  array   $groups Array of groups the user is in
50015fae107Sandi * @return int             permission level
501f3f0262cSandi */
502f3f0262cSandifunction auth_aclcheck($id,$user,$groups){
503f3f0262cSandi    global $conf;
504f3f0262cSandi    global $AUTH_ACL;
505d752aedeSAndreas Gohr    global $auth;
506f3f0262cSandi
50785d03f68SAndreas Gohr    // if no ACL is used always return upload rights
508f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
509beca106aSAdrian Lang    if (!$auth) return AUTH_NONE;
510f3f0262cSandi
511074cf26bSandi    //make sure groups is an array
512074cf26bSandi    if(!is_array($groups)) $groups = array();
513074cf26bSandi
51485d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
51585d03f68SAndreas Gohr    if(auth_isadmin($user,$groups)) { return AUTH_ADMIN; }
51685d03f68SAndreas Gohr
517e259aa79SAndreas Gohr    $ci = '';
518e259aa79SAndreas Gohr    if(!$auth->isCaseSensitive()) $ci = 'ui';
519d752aedeSAndreas Gohr
520d752aedeSAndreas Gohr    $user = $auth->cleanUser($user);
521d752aedeSAndreas Gohr    $groups = array_map(array($auth,'cleanGroup'),(array)$groups);
52285d03f68SAndreas Gohr    $user = auth_nameencode($user);
52385d03f68SAndreas Gohr
5246c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
5252cd2db38Sandi    $cnt = count($groups);
5262cd2db38Sandi    for($i=0; $i<$cnt; $i++){
5276c2bb100SAndreas Gohr        $groups[$i] = '@'.auth_nameencode($groups[$i]);
52810a76f6fSfrank    }
52910a76f6fSfrank
530f3f0262cSandi    $ns    = getNS($id);
531f3f0262cSandi    $perm  = -1;
532f3f0262cSandi
53334aeb4afSAndreas Gohr    if($user || count($groups)){
534f3f0262cSandi        //add ALL group
535f3f0262cSandi        $groups[] = '@ALL';
536f3f0262cSandi        //add User
53734aeb4afSAndreas Gohr        if($user) $groups[] = $user;
538f3f0262cSandi        //build regexp
539f3f0262cSandi        $regexp   = join('|',$groups);
540f3f0262cSandi    }else{
541f3f0262cSandi        $regexp = '@ALL';
542f3f0262cSandi    }
543f3f0262cSandi
544f3f0262cSandi    //check exact match first
545e259aa79SAndreas Gohr    $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/'.$ci,$AUTH_ACL);
546f3f0262cSandi    if(count($matches)){
547f3f0262cSandi        foreach($matches as $match){
548f3f0262cSandi            $match = preg_replace('/#.*$/','',$match); //ignore comments
549f3f0262cSandi            $acl   = preg_split('/\s+/',$match);
5508ef6b7caSandi            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
551f3f0262cSandi            if($acl[2] > $perm){
552f3f0262cSandi                $perm = $acl[2];
553f3f0262cSandi            }
554f3f0262cSandi        }
555f3f0262cSandi        if($perm > -1){
556f3f0262cSandi            //we had a match - return it
557f3f0262cSandi            return $perm;
558f3f0262cSandi        }
559f3f0262cSandi    }
560f3f0262cSandi
561f3f0262cSandi    //still here? do the namespace checks
562f3f0262cSandi    if($ns){
5633e304b55SMichael Hamann        $path = $ns.':*';
564f3f0262cSandi    }else{
5653e304b55SMichael Hamann        $path = '*'; //root document
566f3f0262cSandi    }
567f3f0262cSandi
568f3f0262cSandi    do{
5693e304b55SMichael Hamann        $matches = preg_grep('/^'.preg_quote($path,'/').'\s+('.$regexp.')\s+/'.$ci,$AUTH_ACL);
570f3f0262cSandi        if(count($matches)){
571f3f0262cSandi            foreach($matches as $match){
572f3f0262cSandi                $match = preg_replace('/#.*$/','',$match); //ignore comments
573f3f0262cSandi                $acl   = preg_split('/\s+/',$match);
5748ef6b7caSandi                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
575f3f0262cSandi                if($acl[2] > $perm){
576f3f0262cSandi                    $perm = $acl[2];
577f3f0262cSandi                }
578f3f0262cSandi            }
579f3f0262cSandi            //we had a match - return it
580f3f0262cSandi            return $perm;
581f3f0262cSandi        }
582f3f0262cSandi
583f3f0262cSandi        //get next higher namespace
584f3f0262cSandi        $ns   = getNS($ns);
585f3f0262cSandi
5863e304b55SMichael Hamann        if($path != '*'){
5873e304b55SMichael Hamann            $path = $ns.':*';
5883e304b55SMichael Hamann            if($path == ':*') $path = '*';
589f3f0262cSandi        }else{
590f3f0262cSandi            //we did this already
591f3f0262cSandi            //looks like there is something wrong with the ACL
592f3f0262cSandi            //break here
593d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
594d5ce66f6SAndreas Gohr            return AUTH_NONE;
595f3f0262cSandi        }
596f3f0262cSandi    }while(1); //this should never loop endless
59752a5af8dSandi
59852a5af8dSandi    //still here? return no permissions
59952a5af8dSandi    return AUTH_NONE;
600f3f0262cSandi}
601f3f0262cSandi
602f3f0262cSandi/**
6036c2bb100SAndreas Gohr * Encode ASCII special chars
6046c2bb100SAndreas Gohr *
6056c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
6066c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
6076c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
6086c2bb100SAndreas Gohr * urlencoding!).
6096c2bb100SAndreas Gohr *
6106c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
6116c2bb100SAndreas Gohr *
6126c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
6136c2bb100SAndreas Gohr * @see rawurldecode()
6146c2bb100SAndreas Gohr */
615e838fc2eSAndreas Gohrfunction auth_nameencode($name,$skip_group=false){
616a424cd8eSchris    global $cache_authname;
617a424cd8eSchris    $cache =& $cache_authname;
61831784267SAndreas Gohr    $name  = (string) $name;
619a424cd8eSchris
62080601d26SAndreas Gohr    // never encode wildcard FS#1955
62180601d26SAndreas Gohr    if($name == '%USER%') return $name;
62280601d26SAndreas Gohr
623a424cd8eSchris    if (!isset($cache[$name][$skip_group])) {
624e838fc2eSAndreas Gohr        if($skip_group && $name{0} =='@'){
625a424cd8eSchris            $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
6261a9ae8e5SAndreas Gohr                    "'%'.dechex(ord(substr('\\1',-1)))",substr($name,1));
627e838fc2eSAndreas Gohr        }else{
628a424cd8eSchris            $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
6291a9ae8e5SAndreas Gohr                    "'%'.dechex(ord(substr('\\1',-1)))",$name);
630e838fc2eSAndreas Gohr        }
6316c2bb100SAndreas Gohr    }
6326c2bb100SAndreas Gohr
633a424cd8eSchris    return $cache[$name][$skip_group];
634a424cd8eSchris}
635a424cd8eSchris
6366c2bb100SAndreas Gohr/**
637f3f0262cSandi * Create a pronouncable password
638f3f0262cSandi *
63915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
64015fae107Sandi * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
64115fae107Sandi *
64215fae107Sandi * @return string  pronouncable password
643f3f0262cSandi */
644f3f0262cSandifunction auth_pwgen(){
645f3f0262cSandi    $pw = '';
646f3f0262cSandi    $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
647f3f0262cSandi    $v  = 'aeiou';              //vowels
648f3f0262cSandi    $a  = $c.$v;                //both
649f3f0262cSandi
650f3f0262cSandi    //use two syllables...
651f3f0262cSandi    for($i=0;$i < 2; $i++){
652f3f0262cSandi        $pw .= $c[rand(0, strlen($c)-1)];
653f3f0262cSandi        $pw .= $v[rand(0, strlen($v)-1)];
654f3f0262cSandi        $pw .= $a[rand(0, strlen($a)-1)];
655f3f0262cSandi    }
656f3f0262cSandi    //... and add a nice number
657f3f0262cSandi    $pw .= rand(10,99);
658f3f0262cSandi
659f3f0262cSandi    return $pw;
660f3f0262cSandi}
661f3f0262cSandi
662f3f0262cSandi/**
663f3f0262cSandi * Sends a password to the given user
664f3f0262cSandi *
66515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
66615fae107Sandi *
66715fae107Sandi * @return bool  true on success
668f3f0262cSandi */
669f3f0262cSandifunction auth_sendPassword($user,$password){
670f3f0262cSandi    global $conf;
671f3f0262cSandi    global $lang;
672cd52f92dSchris    global $auth;
673beca106aSAdrian Lang    if (!$auth) return false;
674cd52f92dSchris
675f3f0262cSandi    $hdrs  = '';
676d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
677cd52f92dSchris    $userinfo = $auth->getUserData($user);
678f3f0262cSandi
67987ddda95Sandi    if(!$userinfo['mail']) return false;
680f3f0262cSandi
681f3f0262cSandi    $text = rawLocale('password');
682ed7b5f09Sandi    $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
68387ddda95Sandi    $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
684f3f0262cSandi    $text = str_replace('@LOGIN@',$user,$text);
685f3f0262cSandi    $text = str_replace('@PASSWORD@',$password,$text);
686f3f0262cSandi    $text = str_replace('@TITLE@',$conf['title'],$text);
687f3f0262cSandi
6889a2d7c4eSlupo49    if(empty($conf['mailprefix'])) {
6899a2d7c4eSlupo49        $subject = $lang['regpwmail'];
6909a2d7c4eSlupo49    } else {
6919a2d7c4eSlupo49        $subject = '['.$conf['mailprefix'].'] '.$lang['regpwmail'];
6929a2d7c4eSlupo49    }
6939a2d7c4eSlupo49
69444f669e9Sandi    return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
6959a2d7c4eSlupo49            $subject,
69644f669e9Sandi            $text,
69744f669e9Sandi            $conf['mailfrom']);
698f3f0262cSandi}
699f3f0262cSandi
700f3f0262cSandi/**
70115fae107Sandi * Register a new user
702f3f0262cSandi *
70315fae107Sandi * This registers a new user - Data is read directly from $_POST
70415fae107Sandi *
70515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
70615fae107Sandi *
70715fae107Sandi * @return bool  true on success, false on any error
708f3f0262cSandi */
709f3f0262cSandifunction register(){
710f3f0262cSandi    global $lang;
711eb5d07e4Sjan    global $conf;
712cd52f92dSchris    global $auth;
713f3f0262cSandi
714f3f0262cSandi    if(!$_POST['save']) return false;
7153a48618aSAnika Henke    if(!actionOK('register')) return false;
716640145a5Sandi
717f3f0262cSandi    //clean username
718d752aedeSAndreas Gohr    $_POST['login'] = trim($auth->cleanUser($_POST['login']));
719d752aedeSAndreas Gohr
720f3f0262cSandi    //clean fullname and email
72154f0e6eaSAndreas Gohr    $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
72254f0e6eaSAndreas Gohr    $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
723f3f0262cSandi
724f3f0262cSandi    if( empty($_POST['login']) ||
725f3f0262cSandi        empty($_POST['fullname']) ||
726f3f0262cSandi        empty($_POST['email']) ){
727f3f0262cSandi        msg($lang['regmissing'],-1);
728f3f0262cSandi        return false;
729f3f0262cSandi    }
730f3f0262cSandi
731cab2716aSmatthias.grimm    if ($conf['autopasswd']) {
732cab2716aSmatthias.grimm        $pass = auth_pwgen();                // automatically generate password
733cab2716aSmatthias.grimm    } elseif (empty($_POST['pass']) ||
734cab2716aSmatthias.grimm            empty($_POST['passchk'])) {
735bf12ec81Sjan        msg($lang['regmissing'], -1);        // complain about missing passwords
736cab2716aSmatthias.grimm        return false;
737cab2716aSmatthias.grimm    } elseif ($_POST['pass'] != $_POST['passchk']) {
738bf12ec81Sjan        msg($lang['regbadpass'], -1);      // complain about misspelled passwords
739cab2716aSmatthias.grimm        return false;
740cab2716aSmatthias.grimm    } else {
741cab2716aSmatthias.grimm        $pass = $_POST['pass'];              // accept checked and valid password
742cab2716aSmatthias.grimm    }
743cab2716aSmatthias.grimm
744f3f0262cSandi    //check mail
74544f669e9Sandi    if(!mail_isvalid($_POST['email'])){
746f3f0262cSandi        msg($lang['regbadmail'],-1);
747f3f0262cSandi        return false;
748f3f0262cSandi    }
749f3f0262cSandi
750f3f0262cSandi    //okay try to create the user
7517d3c8d42SGabriel Birke    if(!$auth->triggerUserMod('create', array($_POST['login'],$pass,$_POST['fullname'],$_POST['email']))){
752f3f0262cSandi        msg($lang['reguexists'],-1);
753f3f0262cSandi        return false;
754f3f0262cSandi    }
755f3f0262cSandi
75602a498e7Schris    // create substitutions for use in notification email
75702a498e7Schris    $substitutions = array(
75802a498e7Schris            'NEWUSER' => $_POST['login'],
75902a498e7Schris            'NEWNAME' => $_POST['fullname'],
76002a498e7Schris            'NEWEMAIL' => $_POST['email'],
76102a498e7Schris            );
76202a498e7Schris
763cab2716aSmatthias.grimm    if (!$conf['autopasswd']) {
764cab2716aSmatthias.grimm        msg($lang['regsuccess2'],1);
76502a498e7Schris        notify('', 'register', '', $_POST['login'], false, $substitutions);
766cab2716aSmatthias.grimm        return true;
767cab2716aSmatthias.grimm    }
768cab2716aSmatthias.grimm
769cab2716aSmatthias.grimm    // autogenerated password? then send him the password
770f3f0262cSandi    if (auth_sendPassword($_POST['login'],$pass)){
771f3f0262cSandi        msg($lang['regsuccess'],1);
77202a498e7Schris        notify('', 'register', '', $_POST['login'], false, $substitutions);
773f3f0262cSandi        return true;
774f3f0262cSandi    }else{
775f3f0262cSandi        msg($lang['regmailfail'],-1);
776f3f0262cSandi        return false;
777f3f0262cSandi    }
778f3f0262cSandi}
779f3f0262cSandi
78010a76f6fSfrank/**
7818b06d178Schris * Update user profile
7828b06d178Schris *
7838b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
7848b06d178Schris */
7858b06d178Schrisfunction updateprofile() {
7868b06d178Schris    global $conf;
7878b06d178Schris    global $INFO;
7888b06d178Schris    global $lang;
789cd52f92dSchris    global $auth;
7908b06d178Schris
791bb4866bdSchris    if(empty($_POST['save'])) return false;
7921b2a85e8SAndreas Gohr    if(!checkSecurityToken()) return false;
7938b06d178Schris
7943a48618aSAnika Henke    if(!actionOK('profile')) {
7958b06d178Schris        msg($lang['profna'],-1);
7968b06d178Schris        return false;
7978b06d178Schris    }
7988b06d178Schris
7998b06d178Schris    if ($_POST['newpass'] != $_POST['passchk']) {
8008b06d178Schris        msg($lang['regbadpass'], -1);      // complain about misspelled passwords
8018b06d178Schris        return false;
8028b06d178Schris    }
8038b06d178Schris
8048b06d178Schris    //clean fullname and email
80554f0e6eaSAndreas Gohr    $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
80654f0e6eaSAndreas Gohr    $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
8078b06d178Schris
8084369edafSAndy Webber    if ((empty($_POST['fullname']) && $auth->canDo('modName')) ||
8094369edafSAndy Webber        (empty($_POST['email']) && $auth->canDo('modMail'))) {
8108b06d178Schris        msg($lang['profnoempty'],-1);
8118b06d178Schris        return false;
8128b06d178Schris    }
8138b06d178Schris
8144369edafSAndy Webber    if (!mail_isvalid($_POST['email']) && $auth->canDo('modMail')){
8158b06d178Schris        msg($lang['regbadmail'],-1);
8168b06d178Schris        return false;
8178b06d178Schris    }
8188b06d178Schris
8194c21b7eeSAndreas Gohr    if ($_POST['fullname'] != $INFO['userinfo']['name'] && $auth->canDo('modName')) $changes['name'] = $_POST['fullname'];
8204c21b7eeSAndreas Gohr    if ($_POST['email'] != $INFO['userinfo']['mail'] && $auth->canDo('modMail')) $changes['mail'] = $_POST['email'];
821cf626a62SAndreas Gohr    if (!empty($_POST['newpass']) && $auth->canDo('modPass')) $changes['pass'] = $_POST['newpass'];
8224c21b7eeSAndreas Gohr
8238b06d178Schris    if (!count($changes)) {
8248b06d178Schris        msg($lang['profnochange'], -1);
8258b06d178Schris        return false;
8268b06d178Schris    }
8278b06d178Schris
8288b06d178Schris    if ($conf['profileconfirm']) {
829df466c7aSAndreas Gohr        if (!$auth->checkPass($_SERVER['REMOTE_USER'], $_POST['oldpass'])) {
8308b06d178Schris            msg($lang['badlogin'],-1);
8318b06d178Schris            return false;
8328b06d178Schris        }
8338b06d178Schris    }
8348b06d178Schris
835a0b5b007SChris Smith    if ($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
836a0b5b007SChris Smith        // update cookie and session with the changed data
83732ed2b36SAndreas Gohr        if ($changes['pass']){
83832ed2b36SAndreas Gohr            list($user,$sticky,$pass) = auth_getCookie();
83932ed2b36SAndreas Gohr            $pass = PMA_blowfish_encrypt($changes['pass'],auth_cookiesalt(!$sticky));
840a0b5b007SChris Smith            auth_setCookie($_SERVER['REMOTE_USER'],$pass,(bool)$sticky);
84132ed2b36SAndreas Gohr        }
84225b2a98cSMichael Klier        return true;
843a0b5b007SChris Smith    }
8448b06d178Schris}
8458b06d178Schris
8468b06d178Schris/**
8478b06d178Schris * Send a  new password
8488b06d178Schris *
8491d5856cfSAndreas Gohr * This function handles both phases of the password reset:
8501d5856cfSAndreas Gohr *
8511d5856cfSAndreas Gohr *   - handling the first request of password reset
8521d5856cfSAndreas Gohr *   - validating the password reset auth token
8531d5856cfSAndreas Gohr *
8548b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
8558b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
8561d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
8578b06d178Schris *
8588b06d178Schris * @return bool true on success, false on any error
8598b06d178Schris */
8608b06d178Schrisfunction act_resendpwd(){
8618b06d178Schris    global $lang;
8628b06d178Schris    global $conf;
863cd52f92dSchris    global $auth;
8648b06d178Schris
8653a48618aSAnika Henke    if(!actionOK('resendpwd')) {
8668b06d178Schris        msg($lang['resendna'],-1);
8678b06d178Schris        return false;
8688b06d178Schris    }
8698b06d178Schris
8701d5856cfSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
8718b06d178Schris
8721d5856cfSAndreas Gohr    if($token){
8731d5856cfSAndreas Gohr        // we're in token phase
8741d5856cfSAndreas Gohr
8751d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
8761d5856cfSAndreas Gohr        if(!@file_exists($tfile)){
8771d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'],-1);
8781d5856cfSAndreas Gohr            return false;
8791d5856cfSAndreas Gohr        }
8801d5856cfSAndreas Gohr        $user = io_readfile($tfile);
8811d5856cfSAndreas Gohr        @unlink($tfile);
882cd52f92dSchris        $userinfo = $auth->getUserData($user);
8838b06d178Schris        if(!$userinfo['mail']) {
8848b06d178Schris            msg($lang['resendpwdnouser'], -1);
8858b06d178Schris            return false;
8868b06d178Schris        }
8878b06d178Schris
8888b06d178Schris        $pass = auth_pwgen();
8897d3c8d42SGabriel Birke        if (!$auth->triggerUserMod('modify', array($user,array('pass' => $pass)))) {
8908b06d178Schris            msg('error modifying user data',-1);
8918b06d178Schris            return false;
8928b06d178Schris        }
8938b06d178Schris
8948b06d178Schris        if (auth_sendPassword($user,$pass)) {
8958b06d178Schris            msg($lang['resendpwdsuccess'],1);
8968b06d178Schris        } else {
8978b06d178Schris            msg($lang['regmailfail'],-1);
8988b06d178Schris        }
8998b06d178Schris        return true;
9001d5856cfSAndreas Gohr
9011d5856cfSAndreas Gohr    } else {
9021d5856cfSAndreas Gohr        // we're in request phase
9031d5856cfSAndreas Gohr
9041d5856cfSAndreas Gohr        if(!$_POST['save']) return false;
9051d5856cfSAndreas Gohr
9061d5856cfSAndreas Gohr        if (empty($_POST['login'])) {
9071d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
9081d5856cfSAndreas Gohr            return false;
9091d5856cfSAndreas Gohr        } else {
910d752aedeSAndreas Gohr            $user = trim($auth->cleanUser($_POST['login']));
9111d5856cfSAndreas Gohr        }
9121d5856cfSAndreas Gohr
9131d5856cfSAndreas Gohr        $userinfo = $auth->getUserData($user);
9141d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
9151d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
9161d5856cfSAndreas Gohr            return false;
9171d5856cfSAndreas Gohr        }
9181d5856cfSAndreas Gohr
9191d5856cfSAndreas Gohr        // generate auth token
9201d5856cfSAndreas Gohr        $token = md5(auth_cookiesalt().$user); //secret but user based
9211d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
9221d5856cfSAndreas Gohr        $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
9231d5856cfSAndreas Gohr
9241d5856cfSAndreas Gohr        io_saveFile($tfile,$user);
9251d5856cfSAndreas Gohr
9261d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
9271d5856cfSAndreas Gohr        $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
9281d5856cfSAndreas Gohr        $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
9291d5856cfSAndreas Gohr        $text = str_replace('@LOGIN@',$user,$text);
9301d5856cfSAndreas Gohr        $text = str_replace('@TITLE@',$conf['title'],$text);
9311d5856cfSAndreas Gohr        $text = str_replace('@CONFIRM@',$url,$text);
9321d5856cfSAndreas Gohr
9339a2d7c4eSlupo49        if(empty($conf['mailprefix'])) {
9349a2d7c4eSlupo49            $subject = $lang['regpwmail'];
9359a2d7c4eSlupo49        } else {
9369a2d7c4eSlupo49            $subject = '['.$conf['mailprefix'].'] '.$lang['regpwmail'];
9379a2d7c4eSlupo49        }
9389a2d7c4eSlupo49
9391d5856cfSAndreas Gohr        if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
9409a2d7c4eSlupo49                     $subject,
9411d5856cfSAndreas Gohr                     $text,
9421d5856cfSAndreas Gohr                     $conf['mailfrom'])){
9431d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'],1);
9441d5856cfSAndreas Gohr        }else{
9451d5856cfSAndreas Gohr            msg($lang['regmailfail'],-1);
9461d5856cfSAndreas Gohr        }
9471d5856cfSAndreas Gohr        return true;
9481d5856cfSAndreas Gohr    }
9491d5856cfSAndreas Gohr
9501d5856cfSAndreas Gohr    return false; // never reached
9518b06d178Schris}
9528b06d178Schris
9538b06d178Schris/**
954b0855b11Sandi * Encrypts a password using the given method and salt
955b0855b11Sandi *
956b0855b11Sandi * If the selected method needs a salt and none was given, a random one
957b0855b11Sandi * is chosen.
958b0855b11Sandi *
959b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
960b0855b11Sandi * @return  string  The crypted password
961b0855b11Sandi */
962577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear,$method='',$salt=null){
963b0855b11Sandi    global $conf;
964b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
96510a76f6fSfrank
9663a0a2d05SAndreas Gohr    $pass  = new PassHash();
9673a0a2d05SAndreas Gohr    $call  = 'hash_'.$method;
968b0855b11Sandi
9693a0a2d05SAndreas Gohr    if(!method_exists($pass,$call)){
970b0855b11Sandi        msg("Unsupported crypt method $method",-1);
9713a0a2d05SAndreas Gohr        return false;
972b0855b11Sandi    }
9733a0a2d05SAndreas Gohr
9743a0a2d05SAndreas Gohr    return $pass->$call($clear,$salt);
975b0855b11Sandi}
976b0855b11Sandi
977b0855b11Sandi/**
978b0855b11Sandi * Verifies a cleartext password against a crypted hash
979b0855b11Sandi *
980b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
981b0855b11Sandi * @return  bool
982b0855b11Sandi */
983b0855b11Sandifunction auth_verifyPassword($clear,$crypt){
9843a0a2d05SAndreas Gohr    $pass = new PassHash();
9853a0a2d05SAndreas Gohr    return $pass->verify_hash($clear,$crypt);
986b0855b11Sandi}
987340756e4Sandi
988a0b5b007SChris Smith/**
989a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
990a0b5b007SChris Smith *
991a0b5b007SChris Smith * @param string  $user       username
992a0b5b007SChris Smith * @param string  $pass       encrypted password
993a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
994a0b5b007SChris Smith */
995a0b5b007SChris Smithfunction auth_setCookie($user,$pass,$sticky) {
996a0b5b007SChris Smith    global $conf;
997a0b5b007SChris Smith    global $auth;
99879d00841SOliver Geisen    global $USERINFO;
999a0b5b007SChris Smith
1000beca106aSAdrian Lang    if (!$auth) return false;
1001a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1002a0b5b007SChris Smith
1003a0b5b007SChris Smith    // set cookie
1004645c0a36SAndreas Gohr    $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
100573ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1006c66972f2SAdrian Lang    $time = $sticky ? (time()+60*60*24*365) : 0; //one year
1007a0b5b007SChris Smith    if (version_compare(PHP_VERSION, '5.2.0', '>')) {
100873ab87deSGabriel Birke        setcookie(DOKU_COOKIE,$cookie,$time,$cookieDir,'',($conf['securecookie'] && is_ssl()),true);
1009a0b5b007SChris Smith    }else{
101073ab87deSGabriel Birke        setcookie(DOKU_COOKIE,$cookie,$time,$cookieDir,'',($conf['securecookie'] && is_ssl()));
1011a0b5b007SChris Smith    }
1012a0b5b007SChris Smith    // set session
1013a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1014234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1015a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1016a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1017a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1018a0b5b007SChris Smith}
1019a0b5b007SChris Smith
1020645c0a36SAndreas Gohr/**
1021645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1022645c0a36SAndreas Gohr *
1023645c0a36SAndreas Gohr * @returns array
1024645c0a36SAndreas Gohr */
1025645c0a36SAndreas Gohrfunction auth_getCookie(){
1026c66972f2SAdrian Lang    if (!isset($_COOKIE[DOKU_COOKIE])) {
1027c66972f2SAdrian Lang        return array(null, null, null);
1028c66972f2SAdrian Lang    }
1029645c0a36SAndreas Gohr    list($user,$sticky,$pass) = explode('|',$_COOKIE[DOKU_COOKIE],3);
1030645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1031645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1032645c0a36SAndreas Gohr    $user   = base64_decode($user);
1033645c0a36SAndreas Gohr    return array($user,$sticky,$pass);
1034645c0a36SAndreas Gohr}
1035645c0a36SAndreas Gohr
1036e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1037