xref: /dokuwiki/inc/auth.php (revision a6bc56d03c064a1d747ccba79705cbac0e2bd453)
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
73528ddc7cSAndreas Gohr    // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
7406156f3cSAndreas Gohr    if(isset($_SERVER['HTTP_AUTHORIZATION'])){
75528ddc7cSAndreas Gohr        list($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']) =
76528ddc7cSAndreas Gohr            explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
77528ddc7cSAndreas Gohr    }
78528ddc7cSAndreas Gohr
791e8c9c90SAndreas Gohr    // if no credentials were given try to use HTTP auth (for SSO)
804a26ad85Schris    if(empty($_REQUEST['u']) && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])){
811e8c9c90SAndreas Gohr        $_REQUEST['u'] = $_SERVER['PHP_AUTH_USER'];
821e8c9c90SAndreas Gohr        $_REQUEST['p'] = $_SERVER['PHP_AUTH_PW'];
83b2c0d874SGina Haeussge        $_REQUEST['http_credentials'] = true;
841e8c9c90SAndreas Gohr    }
851e8c9c90SAndreas Gohr
86191bb90aSAndreas Gohr    // apply cleaning
87191bb90aSAndreas Gohr    $_REQUEST['u'] = $auth->cleanUser($_REQUEST['u']);
88191bb90aSAndreas Gohr
89c66972f2SAdrian Lang    if(isset($_REQUEST['authtok'])){
90f13fa892SAndreas Gohr        // when an authentication token is given, trust the session
91f13fa892SAndreas Gohr        auth_validateToken($_REQUEST['authtok']);
92f13fa892SAndreas Gohr    }elseif(!is_null($auth) && $auth->canDo('external')){
93f13fa892SAndreas Gohr        // external trust mechanism in place
94f5cb575dSAndreas Gohr        $auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
95f5cb575dSAndreas Gohr    }else{
966080c584SRobin Gareus        $evdata = array(
976080c584SRobin Gareus                'user'     => $_REQUEST['u'],
986080c584SRobin Gareus                'password' => $_REQUEST['p'],
996080c584SRobin Gareus                'sticky'   => $_REQUEST['r'],
1006080c584SRobin Gareus                'silent'   => $_REQUEST['http_credentials'],
1016080c584SRobin Gareus                );
102b5ee21aaSAdrian Lang        trigger_event('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
103f5cb575dSAndreas Gohr    }
104f5cb575dSAndreas Gohr
10516905344SAndreas Gohr    //load ACL into a global array XXX
106c8f80b4eSAndreas Gohr    if(is_readable($config_cascade['acl']['default'])){
107c8f80b4eSAndreas Gohr        $AUTH_ACL = file($config_cascade['acl']['default']);
108191bb90aSAndreas Gohr        //support user wildcard
109f8cc3354SGuy Brand        if(isset($_SERVER['REMOTE_USER'])){
1105d87b2ccSAndreas Gohr            $AUTH_ACL = str_replace('%USER%',$_SERVER['REMOTE_USER'],$AUTH_ACL);
111a8fe108bSGuy Brand        }
11211799630Sandi    }
113f3f0262cSandi}
114f3f0262cSandi
115b5ee21aaSAdrian Langfunction auth_login_wrapper($evdata) {
116b5ee21aaSAdrian Lang    return auth_login($evdata['user'],
117b5ee21aaSAdrian Lang                      $evdata['password'],
118b5ee21aaSAdrian Lang                      $evdata['sticky'],
119b5ee21aaSAdrian Lang                      $evdata['silent']);
120b5ee21aaSAdrian Lang}
121b5ee21aaSAdrian Lang
122f3f0262cSandi/**
123f3f0262cSandi * This tries to login the user based on the sent auth credentials
124f3f0262cSandi *
125f3f0262cSandi * The authentication works like this: if a username was given
12615fae107Sandi * a new login is assumed and user/password are checked. If they
12715fae107Sandi * are correct the password is encrypted with blowfish and stored
12815fae107Sandi * together with the username in a cookie - the same info is stored
12915fae107Sandi * in the session, too. Additonally a browserID is stored in the
13015fae107Sandi * session.
13115fae107Sandi *
13215fae107Sandi * If no username was given the cookie is checked: if the username,
13315fae107Sandi * crypted password and browserID match between session and cookie
13415fae107Sandi * no further testing is done and the user is accepted
13515fae107Sandi *
13615fae107Sandi * If a cookie was found but no session info was availabe the
137136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
13815fae107Sandi * together with username rechecked by calling this function again.
139f3f0262cSandi *
140f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
141f3f0262cSandi * are set.
14215fae107Sandi *
14315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
14415fae107Sandi *
14515fae107Sandi * @param   string  $user    Username
14615fae107Sandi * @param   string  $pass    Cleartext Password
14715fae107Sandi * @param   bool    $sticky  Cookie should not expire
148f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
14915fae107Sandi * @return  bool             true on successful auth
150f3f0262cSandi */
151f112c2faSAndreas Gohrfunction auth_login($user,$pass,$sticky=false,$silent=false){
152f3f0262cSandi    global $USERINFO;
153f3f0262cSandi    global $conf;
154f3f0262cSandi    global $lang;
155cd52f92dSchris    global $auth;
156132bdbfeSandi    $sticky ? $sticky = true : $sticky = false; //sanity check
157f3f0262cSandi
158beca106aSAdrian Lang    if (!$auth) return false;
159beca106aSAdrian Lang
160bbbd6568SAndreas Gohr    if(!empty($user)){
161132bdbfeSandi        //usual login
162cd52f92dSchris        if ($auth->checkPass($user,$pass)){
163132bdbfeSandi            // make logininfo globally available
164f3f0262cSandi            $_SERVER['REMOTE_USER'] = $user;
165a0b5b007SChris Smith            auth_setCookie($user,PMA_blowfish_encrypt($pass,auth_cookiesalt()),$sticky);
166132bdbfeSandi            return true;
167f3f0262cSandi        }else{
168f3f0262cSandi            //invalid credentials - log off
169f112c2faSAndreas Gohr            if(!$silent) msg($lang['badlogin'],-1);
170f3f0262cSandi            auth_logoff();
171132bdbfeSandi            return false;
172f3f0262cSandi        }
173f3f0262cSandi    }else{
174132bdbfeSandi        // read cookie information
175645c0a36SAndreas Gohr        list($user,$sticky,$pass) = auth_getCookie();
176132bdbfeSandi        // get session info
177e71ce681SAndreas Gohr        $session = $_SESSION[DOKU_COOKIE]['auth'];
178132bdbfeSandi        if($user && $pass){
179132bdbfeSandi            // we got a cookie - see if we can trust it
180132bdbfeSandi            if(isset($session) &&
1817172dbc0SAndreas Gohr                    $auth->useSessionCache($user) &&
1824c989037SChris Smith                    ($session['time'] >= time()-$conf['auth_security_timeout']) &&
183132bdbfeSandi                    ($session['user'] == $user) &&
184132bdbfeSandi                    ($session['pass'] == $pass) &&  //still crypted
185132bdbfeSandi                    ($session['buid'] == auth_browseruid()) ){
186132bdbfeSandi                // he has session, cookie and browser right - let him in
187132bdbfeSandi                $_SERVER['REMOTE_USER'] = $user;
188132bdbfeSandi                $USERINFO = $session['info']; //FIXME move all references to session
189132bdbfeSandi                return true;
190132bdbfeSandi            }
191f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
192132bdbfeSandi            $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
193f112c2faSAndreas Gohr            return auth_login($user,$pass,$sticky,true);
194132bdbfeSandi        }
195132bdbfeSandi    }
196f3f0262cSandi    //just to be sure
197883179a4SAndreas Gohr    auth_logoff(true);
198132bdbfeSandi    return false;
199f3f0262cSandi}
200132bdbfeSandi
201132bdbfeSandi/**
202f13fa892SAndreas Gohr * Checks if a given authentication token was stored in the session
203f13fa892SAndreas Gohr *
204f13fa892SAndreas Gohr * Will setup authentication data using data from the session if the
205f13fa892SAndreas Gohr * token is correct. Will exit with a 401 Status if not.
206f13fa892SAndreas Gohr *
207f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
208f13fa892SAndreas Gohr * @param  string $token The authentication token
209f13fa892SAndreas Gohr * @return boolean true (or will exit on failure)
210f13fa892SAndreas Gohr */
211f13fa892SAndreas Gohrfunction auth_validateToken($token){
212f13fa892SAndreas Gohr    if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']){
213f13fa892SAndreas Gohr        // bad token
214f13fa892SAndreas Gohr        header("HTTP/1.0 401 Unauthorized");
215f13fa892SAndreas Gohr        print 'Invalid auth token - maybe the session timed out';
216f13fa892SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
217f13fa892SAndreas Gohr        exit;
218f13fa892SAndreas Gohr    }
219f13fa892SAndreas Gohr    // still here? trust the session data
220f13fa892SAndreas Gohr    global $USERINFO;
221f13fa892SAndreas Gohr    $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
222f13fa892SAndreas Gohr    $USERINFO = $_SESSION[DOKU_COOKIE]['auth']['info'];
223f13fa892SAndreas Gohr    return true;
224f13fa892SAndreas Gohr}
225f13fa892SAndreas Gohr
226f13fa892SAndreas Gohr/**
227f13fa892SAndreas Gohr * Create an auth token and store it in the session
228f13fa892SAndreas Gohr *
229f13fa892SAndreas Gohr * NOTE: this is completely unrelated to the getSecurityToken() function
230f13fa892SAndreas Gohr *
231f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
232f13fa892SAndreas Gohr * @return string The auth token
233f13fa892SAndreas Gohr */
234f13fa892SAndreas Gohrfunction auth_createToken(){
235f13fa892SAndreas Gohr    $token = md5(mt_rand());
23609c2d803SAndreas Gohr    @session_start(); // reopen the session if needed
237f13fa892SAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
23809c2d803SAndreas Gohr    session_write_close();
239f13fa892SAndreas Gohr    return $token;
240f13fa892SAndreas Gohr}
241f13fa892SAndreas Gohr
242f13fa892SAndreas Gohr/**
243136ce040Sandi * Builds a pseudo UID from browser and IP data
244132bdbfeSandi *
245132bdbfeSandi * This is neither unique nor unfakable - still it adds some
246136ce040Sandi * security. Using the first part of the IP makes sure
247136ce040Sandi * proxy farms like AOLs are stil okay.
24815fae107Sandi *
24915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
25015fae107Sandi *
25115fae107Sandi * @return  string  a MD5 sum of various browser headers
252132bdbfeSandi */
253132bdbfeSandifunction auth_browseruid(){
2542f9daf16SAndreas Gohr    $ip   = clientIP(true);
255132bdbfeSandi    $uid  = '';
256132bdbfeSandi    $uid .= $_SERVER['HTTP_USER_AGENT'];
257132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
258132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
259132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
2602f9daf16SAndreas Gohr    $uid .= substr($ip,0,strpos($ip,'.'));
261132bdbfeSandi    return md5($uid);
262132bdbfeSandi}
263132bdbfeSandi
264132bdbfeSandi/**
265132bdbfeSandi * Creates a random key to encrypt the password in cookies
26615fae107Sandi *
26715fae107Sandi * This function tries to read the password for encrypting
26898407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
26915fae107Sandi * if no such file is found a random key is created and
27015fae107Sandi * and stored in this file.
27115fae107Sandi *
27215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
27315fae107Sandi *
27415fae107Sandi * @return  string
275132bdbfeSandi */
276132bdbfeSandifunction auth_cookiesalt(){
277132bdbfeSandi    global $conf;
27898407a7aSandi    $file = $conf['metadir'].'/_htcookiesalt';
279132bdbfeSandi    $salt = io_readFile($file);
280132bdbfeSandi    if(empty($salt)){
281132bdbfeSandi        $salt = uniqid(rand(),true);
282132bdbfeSandi        io_saveFile($file,$salt);
283132bdbfeSandi    }
284132bdbfeSandi    return $salt;
285f3f0262cSandi}
286f3f0262cSandi
287f3f0262cSandi/**
288883179a4SAndreas Gohr * Log out the current user
289883179a4SAndreas Gohr *
290f3f0262cSandi * This clears all authentication data and thus log the user
291883179a4SAndreas Gohr * off. It also clears session data.
29215fae107Sandi *
29315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
294883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
295f3f0262cSandi */
296883179a4SAndreas Gohrfunction auth_logoff($keepbc=false){
297f3f0262cSandi    global $conf;
298f3f0262cSandi    global $USERINFO;
2998b06d178Schris    global $INFO, $ID;
3005298a619SAndreas Gohr    global $auth;
30137065e65Sandi
302d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
303e9621d07SAndreas Gohr    @session_start();
304e9621d07SAndreas Gohr
305e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
306e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
307e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
308e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
309e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
310e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
311883179a4SAndreas Gohr    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
312e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
31337065e65Sandi    if(isset($_SERVER['REMOTE_USER']))
314f3f0262cSandi        unset($_SERVER['REMOTE_USER']);
315132bdbfeSandi    $USERINFO=null; //FIXME
316f5c6743cSAndreas Gohr
317f5c6743cSAndreas Gohr    if (version_compare(PHP_VERSION, '5.2.0', '>')) {
31885c6f7d0SAndreas Gohr        setcookie(DOKU_COOKIE,'',time()-600000,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true);
319f5c6743cSAndreas Gohr    }else{
32085c6f7d0SAndreas Gohr        setcookie(DOKU_COOKIE,'',time()-600000,DOKU_REL,'',($conf['securecookie'] && is_ssl()));
321f5c6743cSAndreas Gohr    }
3225298a619SAndreas Gohr
323880f62faSAndreas Gohr    if($auth) $auth->logOff();
324f3f0262cSandi}
325f3f0262cSandi
326f3f0262cSandi/**
327f8cc712eSAndreas Gohr * Check if a user is a manager
328f8cc712eSAndreas Gohr *
329f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
330f8cc712eSAndreas Gohr * user.
331f8cc712eSAndreas Gohr *
332f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
333f8cc712eSAndreas Gohr *
334f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
335f8cc712eSAndreas Gohr * @see    auth_isadmin
336f8cc712eSAndreas Gohr * @param  string user      - Username
337f8cc712eSAndreas Gohr * @param  array  groups    - List of groups the user is in
338f8cc712eSAndreas Gohr * @param  bool   adminonly - when true checks if user is admin
339f8cc712eSAndreas Gohr */
340f8cc712eSAndreas Gohrfunction auth_ismanager($user=null,$groups=null,$adminonly=false){
341f8cc712eSAndreas Gohr    global $conf;
342f8cc712eSAndreas Gohr    global $USERINFO;
343d752aedeSAndreas Gohr    global $auth;
344f8cc712eSAndreas Gohr
345beca106aSAdrian Lang    if (!$auth) return false;
346c66972f2SAdrian Lang    if(is_null($user)) {
347c66972f2SAdrian Lang        if (!isset($_SERVER['REMOTE_USER'])) {
348c66972f2SAdrian Lang            return false;
349c66972f2SAdrian Lang        } else {
350c66972f2SAdrian Lang            $user = $_SERVER['REMOTE_USER'];
351c66972f2SAdrian Lang        }
352c66972f2SAdrian Lang    }
353*a6bc56d0SAndreas Gohr    $user = trim($auth->cleanUser($user));
354*a6bc56d0SAndreas Gohr    if($user === '') return false;
35590583e9fSAndreas Gohr    if(is_null($groups)) $groups = (array) $USERINFO['grps'];
356d752aedeSAndreas Gohr    $groups = array_map(array($auth,'cleanGroup'),$groups);
357f8cc712eSAndreas Gohr    $user   = auth_nameencode($user);
358f8cc712eSAndreas Gohr
359f8cc712eSAndreas Gohr    // check username against superuser and manager
3607651d633SGuy Brand    $superusers = explode(',', $conf['superuser']);
3617651d633SGuy Brand    $superusers = array_unique($superusers);
3627651d633SGuy Brand    $superusers = array_map('trim', $superusers);
363*a6bc56d0SAndreas Gohr    $superusers = array_filter($superusers);
3647651d633SGuy Brand    // prepare an array containing only true values for array_map call
3657651d633SGuy Brand    $alltrue = array_fill(0, count($superusers), true);
3667651d633SGuy Brand    $superusers = array_map('auth_nameencode', $superusers, $alltrue);
367e259aa79SAndreas Gohr
368e259aa79SAndreas Gohr    // case insensitive?
369e259aa79SAndreas Gohr    if(!$auth->isCaseSensitive()){
370e259aa79SAndreas Gohr        $superusers = array_map('utf8_strtolower',$superusers);
371e259aa79SAndreas Gohr        $user       = utf8_strtolower($user);
372e259aa79SAndreas Gohr    }
373e259aa79SAndreas Gohr
374e259aa79SAndreas Gohr    // check user match
3757651d633SGuy Brand    if(in_array($user, $superusers)) return true;
3767651d633SGuy Brand
377e259aa79SAndreas Gohr    // check managers
378f8cc712eSAndreas Gohr    if(!$adminonly){
3797651d633SGuy Brand        $managers = explode(',', $conf['manager']);
3807651d633SGuy Brand        $managers = array_unique($managers);
3817651d633SGuy Brand        $managers = array_map('trim', $managers);
382*a6bc56d0SAndreas Gohr        $managers = array_filter($managers);
3837651d633SGuy Brand        // prepare an array containing only true values for array_map call
3847651d633SGuy Brand        $alltrue = array_fill(0, count($managers), true);
3857651d633SGuy Brand        $managers = array_map('auth_nameencode', $managers, $alltrue);
386e259aa79SAndreas Gohr        if(!$auth->isCaseSensitive()) $managers = array_map('utf8_strtolower',$managers);
3877651d633SGuy Brand        if(in_array($user, $managers)) return true;
388f8cc712eSAndreas Gohr    }
389f8cc712eSAndreas Gohr
39000ce12daSChris Smith    // check user's groups against superuser and manager
39100ce12daSChris Smith    if (!empty($groups)) {
39200ce12daSChris Smith
393f8cc712eSAndreas Gohr        //prepend groups with @ and nameencode
394f8cc712eSAndreas Gohr        $cnt = count($groups);
395f8cc712eSAndreas Gohr        for($i=0; $i<$cnt; $i++){
396f8cc712eSAndreas Gohr            $groups[$i] = '@'.auth_nameencode($groups[$i]);
397e259aa79SAndreas Gohr            if(!$auth->isCaseSensitive()){
398e259aa79SAndreas Gohr                $groups[$i] = utf8_strtolower($groups[$i]);
399e259aa79SAndreas Gohr            }
400f8cc712eSAndreas Gohr        }
401f8cc712eSAndreas Gohr
402f8cc712eSAndreas Gohr        // check groups against superuser and manager
4037651d633SGuy Brand        foreach($superusers as $supu)
4047651d633SGuy Brand            if(in_array($supu, $groups)) return true;
405f8cc712eSAndreas Gohr        if(!$adminonly){
4067651d633SGuy Brand            foreach($managers as $mana)
4077651d633SGuy Brand                if(in_array($mana, $groups)) return true;
408f8cc712eSAndreas Gohr        }
40900ce12daSChris Smith    }
41000ce12daSChris Smith
411f8cc712eSAndreas Gohr    return false;
412f8cc712eSAndreas Gohr}
413f8cc712eSAndreas Gohr
414f8cc712eSAndreas Gohr/**
415f8cc712eSAndreas Gohr * Check if a user is admin
416f8cc712eSAndreas Gohr *
417f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
418f8cc712eSAndreas Gohr *
419f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
420f8cc712eSAndreas Gohr *
421f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
422f8cc712eSAndreas Gohr * @see auth_ismanager
423f8cc712eSAndreas Gohr */
424f8cc712eSAndreas Gohrfunction auth_isadmin($user=null,$groups=null){
425f8cc712eSAndreas Gohr    return auth_ismanager($user,$groups,true);
426f8cc712eSAndreas Gohr}
427f8cc712eSAndreas Gohr
428f8cc712eSAndreas Gohr/**
42915fae107Sandi * Convinience function for auth_aclcheck()
43015fae107Sandi *
43115fae107Sandi * This checks the permissions for the current user
43215fae107Sandi *
43315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
43415fae107Sandi *
4351698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
43615fae107Sandi * @return int          permission level
437f3f0262cSandi */
438f3f0262cSandifunction auth_quickaclcheck($id){
439f3f0262cSandi    global $conf;
440f3f0262cSandi    global $USERINFO;
441f3f0262cSandi    # if no ACL is used always return upload rights
442f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
443f3f0262cSandi    return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
444f3f0262cSandi}
445f3f0262cSandi
446f3f0262cSandi/**
447f3f0262cSandi * Returns the maximum rights a user has for
448f3f0262cSandi * the given ID or its namespace
44915fae107Sandi *
45015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
45115fae107Sandi *
4521698b983Smichael * @param  string  $id     page ID (needs to be resolved and cleaned)
45315fae107Sandi * @param  string  $user   Username
45415fae107Sandi * @param  array   $groups Array of groups the user is in
45515fae107Sandi * @return int             permission level
456f3f0262cSandi */
457f3f0262cSandifunction auth_aclcheck($id,$user,$groups){
458f3f0262cSandi    global $conf;
459f3f0262cSandi    global $AUTH_ACL;
460d752aedeSAndreas Gohr    global $auth;
461f3f0262cSandi
46285d03f68SAndreas Gohr    // if no ACL is used always return upload rights
463f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
464beca106aSAdrian Lang    if (!$auth) return AUTH_NONE;
465f3f0262cSandi
466074cf26bSandi    //make sure groups is an array
467074cf26bSandi    if(!is_array($groups)) $groups = array();
468074cf26bSandi
46985d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
47085d03f68SAndreas Gohr    if(auth_isadmin($user,$groups)) { return AUTH_ADMIN; }
47185d03f68SAndreas Gohr
472e259aa79SAndreas Gohr    $ci = '';
473e259aa79SAndreas Gohr    if(!$auth->isCaseSensitive()) $ci = 'ui';
474d752aedeSAndreas Gohr
475d752aedeSAndreas Gohr    $user = $auth->cleanUser($user);
476d752aedeSAndreas Gohr    $groups = array_map(array($auth,'cleanGroup'),(array)$groups);
47785d03f68SAndreas Gohr    $user = auth_nameencode($user);
47885d03f68SAndreas Gohr
4796c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
4802cd2db38Sandi    $cnt = count($groups);
4812cd2db38Sandi    for($i=0; $i<$cnt; $i++){
4826c2bb100SAndreas Gohr        $groups[$i] = '@'.auth_nameencode($groups[$i]);
48310a76f6fSfrank    }
48410a76f6fSfrank
485f3f0262cSandi    $ns    = getNS($id);
486f3f0262cSandi    $perm  = -1;
487f3f0262cSandi
48834aeb4afSAndreas Gohr    if($user || count($groups)){
489f3f0262cSandi        //add ALL group
490f3f0262cSandi        $groups[] = '@ALL';
491f3f0262cSandi        //add User
49234aeb4afSAndreas Gohr        if($user) $groups[] = $user;
493f3f0262cSandi        //build regexp
494f3f0262cSandi        $regexp   = join('|',$groups);
495f3f0262cSandi    }else{
496f3f0262cSandi        $regexp = '@ALL';
497f3f0262cSandi    }
498f3f0262cSandi
499f3f0262cSandi    //check exact match first
500e259aa79SAndreas Gohr    $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/'.$ci,$AUTH_ACL);
501f3f0262cSandi    if(count($matches)){
502f3f0262cSandi        foreach($matches as $match){
503f3f0262cSandi            $match = preg_replace('/#.*$/','',$match); //ignore comments
504f3f0262cSandi            $acl   = preg_split('/\s+/',$match);
5058ef6b7caSandi            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
506f3f0262cSandi            if($acl[2] > $perm){
507f3f0262cSandi                $perm = $acl[2];
508f3f0262cSandi            }
509f3f0262cSandi        }
510f3f0262cSandi        if($perm > -1){
511f3f0262cSandi            //we had a match - return it
512f3f0262cSandi            return $perm;
513f3f0262cSandi        }
514f3f0262cSandi    }
515f3f0262cSandi
516f3f0262cSandi    //still here? do the namespace checks
517f3f0262cSandi    if($ns){
518f3f0262cSandi        $path = $ns.':\*';
519f3f0262cSandi    }else{
520f3f0262cSandi        $path = '\*'; //root document
521f3f0262cSandi    }
522f3f0262cSandi
523f3f0262cSandi    do{
524e259aa79SAndreas Gohr        $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/'.$ci,$AUTH_ACL);
525f3f0262cSandi        if(count($matches)){
526f3f0262cSandi            foreach($matches as $match){
527f3f0262cSandi                $match = preg_replace('/#.*$/','',$match); //ignore comments
528f3f0262cSandi                $acl   = preg_split('/\s+/',$match);
5298ef6b7caSandi                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
530f3f0262cSandi                if($acl[2] > $perm){
531f3f0262cSandi                    $perm = $acl[2];
532f3f0262cSandi                }
533f3f0262cSandi            }
534f3f0262cSandi            //we had a match - return it
535f3f0262cSandi            return $perm;
536f3f0262cSandi        }
537f3f0262cSandi
538f3f0262cSandi        //get next higher namespace
539f3f0262cSandi        $ns   = getNS($ns);
540f3f0262cSandi
541f3f0262cSandi        if($path != '\*'){
542f3f0262cSandi            $path = $ns.':\*';
543f3f0262cSandi            if($path == ':\*') $path = '\*';
544f3f0262cSandi        }else{
545f3f0262cSandi            //we did this already
546f3f0262cSandi            //looks like there is something wrong with the ACL
547f3f0262cSandi            //break here
548d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
549d5ce66f6SAndreas Gohr            return AUTH_NONE;
550f3f0262cSandi        }
551f3f0262cSandi    }while(1); //this should never loop endless
55252a5af8dSandi
55352a5af8dSandi    //still here? return no permissions
55452a5af8dSandi    return AUTH_NONE;
555f3f0262cSandi}
556f3f0262cSandi
557f3f0262cSandi/**
5586c2bb100SAndreas Gohr * Encode ASCII special chars
5596c2bb100SAndreas Gohr *
5606c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
5616c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
5626c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
5636c2bb100SAndreas Gohr * urlencoding!).
5646c2bb100SAndreas Gohr *
5656c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
5666c2bb100SAndreas Gohr *
5676c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
5686c2bb100SAndreas Gohr * @see rawurldecode()
5696c2bb100SAndreas Gohr */
570e838fc2eSAndreas Gohrfunction auth_nameencode($name,$skip_group=false){
571a424cd8eSchris    global $cache_authname;
572a424cd8eSchris    $cache =& $cache_authname;
57331784267SAndreas Gohr    $name  = (string) $name;
574a424cd8eSchris
57580601d26SAndreas Gohr    // never encode wildcard FS#1955
57680601d26SAndreas Gohr    if($name == '%USER%') return $name;
57780601d26SAndreas Gohr
578a424cd8eSchris    if (!isset($cache[$name][$skip_group])) {
579e838fc2eSAndreas Gohr        if($skip_group && $name{0} =='@'){
580a424cd8eSchris            $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
5811a9ae8e5SAndreas Gohr                    "'%'.dechex(ord(substr('\\1',-1)))",substr($name,1));
582e838fc2eSAndreas Gohr        }else{
583a424cd8eSchris            $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
5841a9ae8e5SAndreas Gohr                    "'%'.dechex(ord(substr('\\1',-1)))",$name);
585e838fc2eSAndreas Gohr        }
5866c2bb100SAndreas Gohr    }
5876c2bb100SAndreas Gohr
588a424cd8eSchris    return $cache[$name][$skip_group];
589a424cd8eSchris}
590a424cd8eSchris
5916c2bb100SAndreas Gohr/**
592f3f0262cSandi * Create a pronouncable password
593f3f0262cSandi *
59415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
59515fae107Sandi * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
59615fae107Sandi *
59715fae107Sandi * @return string  pronouncable password
598f3f0262cSandi */
599f3f0262cSandifunction auth_pwgen(){
600f3f0262cSandi    $pw = '';
601f3f0262cSandi    $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
602f3f0262cSandi    $v  = 'aeiou';              //vowels
603f3f0262cSandi    $a  = $c.$v;                //both
604f3f0262cSandi
605f3f0262cSandi    //use two syllables...
606f3f0262cSandi    for($i=0;$i < 2; $i++){
607f3f0262cSandi        $pw .= $c[rand(0, strlen($c)-1)];
608f3f0262cSandi        $pw .= $v[rand(0, strlen($v)-1)];
609f3f0262cSandi        $pw .= $a[rand(0, strlen($a)-1)];
610f3f0262cSandi    }
611f3f0262cSandi    //... and add a nice number
612f3f0262cSandi    $pw .= rand(10,99);
613f3f0262cSandi
614f3f0262cSandi    return $pw;
615f3f0262cSandi}
616f3f0262cSandi
617f3f0262cSandi/**
618f3f0262cSandi * Sends a password to the given user
619f3f0262cSandi *
62015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
62115fae107Sandi *
62215fae107Sandi * @return bool  true on success
623f3f0262cSandi */
624f3f0262cSandifunction auth_sendPassword($user,$password){
625f3f0262cSandi    global $conf;
626f3f0262cSandi    global $lang;
627cd52f92dSchris    global $auth;
628beca106aSAdrian Lang    if (!$auth) return false;
629cd52f92dSchris
630f3f0262cSandi    $hdrs  = '';
631d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
632cd52f92dSchris    $userinfo = $auth->getUserData($user);
633f3f0262cSandi
63487ddda95Sandi    if(!$userinfo['mail']) return false;
635f3f0262cSandi
636f3f0262cSandi    $text = rawLocale('password');
637ed7b5f09Sandi    $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
63887ddda95Sandi    $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
639f3f0262cSandi    $text = str_replace('@LOGIN@',$user,$text);
640f3f0262cSandi    $text = str_replace('@PASSWORD@',$password,$text);
641f3f0262cSandi    $text = str_replace('@TITLE@',$conf['title'],$text);
642f3f0262cSandi
64344f669e9Sandi    return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
64444f669e9Sandi            $lang['regpwmail'],
64544f669e9Sandi            $text,
64644f669e9Sandi            $conf['mailfrom']);
647f3f0262cSandi}
648f3f0262cSandi
649f3f0262cSandi/**
65015fae107Sandi * Register a new user
651f3f0262cSandi *
65215fae107Sandi * This registers a new user - Data is read directly from $_POST
65315fae107Sandi *
65415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
65515fae107Sandi *
65615fae107Sandi * @return bool  true on success, false on any error
657f3f0262cSandi */
658f3f0262cSandifunction register(){
659f3f0262cSandi    global $lang;
660eb5d07e4Sjan    global $conf;
661cd52f92dSchris    global $auth;
662f3f0262cSandi
663beca106aSAdrian Lang    if (!$auth) return false;
664f3f0262cSandi    if(!$_POST['save']) return false;
66582fd59b6SAndreas Gohr    if(!$auth->canDo('addUser')) return false;
666640145a5Sandi
667f3f0262cSandi    //clean username
668d752aedeSAndreas Gohr    $_POST['login'] = trim($auth->cleanUser($_POST['login']));
669d752aedeSAndreas Gohr
670f3f0262cSandi    //clean fullname and email
67154f0e6eaSAndreas Gohr    $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
67254f0e6eaSAndreas Gohr    $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
673f3f0262cSandi
674f3f0262cSandi    if( empty($_POST['login']) ||
675f3f0262cSandi        empty($_POST['fullname']) ||
676f3f0262cSandi        empty($_POST['email']) ){
677f3f0262cSandi        msg($lang['regmissing'],-1);
678f3f0262cSandi        return false;
679f3f0262cSandi    }
680f3f0262cSandi
681cab2716aSmatthias.grimm    if ($conf['autopasswd']) {
682cab2716aSmatthias.grimm        $pass = auth_pwgen();                // automatically generate password
683cab2716aSmatthias.grimm    } elseif (empty($_POST['pass']) ||
684cab2716aSmatthias.grimm            empty($_POST['passchk'])) {
685bf12ec81Sjan        msg($lang['regmissing'], -1);        // complain about missing passwords
686cab2716aSmatthias.grimm        return false;
687cab2716aSmatthias.grimm    } elseif ($_POST['pass'] != $_POST['passchk']) {
688bf12ec81Sjan        msg($lang['regbadpass'], -1);      // complain about misspelled passwords
689cab2716aSmatthias.grimm        return false;
690cab2716aSmatthias.grimm    } else {
691cab2716aSmatthias.grimm        $pass = $_POST['pass'];              // accept checked and valid password
692cab2716aSmatthias.grimm    }
693cab2716aSmatthias.grimm
694f3f0262cSandi    //check mail
69544f669e9Sandi    if(!mail_isvalid($_POST['email'])){
696f3f0262cSandi        msg($lang['regbadmail'],-1);
697f3f0262cSandi        return false;
698f3f0262cSandi    }
699f3f0262cSandi
700f3f0262cSandi    //okay try to create the user
7017d3c8d42SGabriel Birke    if(!$auth->triggerUserMod('create', array($_POST['login'],$pass,$_POST['fullname'],$_POST['email']))){
702f3f0262cSandi        msg($lang['reguexists'],-1);
703f3f0262cSandi        return false;
704f3f0262cSandi    }
705f3f0262cSandi
70602a498e7Schris    // create substitutions for use in notification email
70702a498e7Schris    $substitutions = array(
70802a498e7Schris            'NEWUSER' => $_POST['login'],
70902a498e7Schris            'NEWNAME' => $_POST['fullname'],
71002a498e7Schris            'NEWEMAIL' => $_POST['email'],
71102a498e7Schris            );
71202a498e7Schris
713cab2716aSmatthias.grimm    if (!$conf['autopasswd']) {
714cab2716aSmatthias.grimm        msg($lang['regsuccess2'],1);
71502a498e7Schris        notify('', 'register', '', $_POST['login'], false, $substitutions);
716cab2716aSmatthias.grimm        return true;
717cab2716aSmatthias.grimm    }
718cab2716aSmatthias.grimm
719cab2716aSmatthias.grimm    // autogenerated password? then send him the password
720f3f0262cSandi    if (auth_sendPassword($_POST['login'],$pass)){
721f3f0262cSandi        msg($lang['regsuccess'],1);
72202a498e7Schris        notify('', 'register', '', $_POST['login'], false, $substitutions);
723f3f0262cSandi        return true;
724f3f0262cSandi    }else{
725f3f0262cSandi        msg($lang['regmailfail'],-1);
726f3f0262cSandi        return false;
727f3f0262cSandi    }
728f3f0262cSandi}
729f3f0262cSandi
73010a76f6fSfrank/**
7318b06d178Schris * Update user profile
7328b06d178Schris *
7338b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
7348b06d178Schris */
7358b06d178Schrisfunction updateprofile() {
7368b06d178Schris    global $conf;
7378b06d178Schris    global $INFO;
7388b06d178Schris    global $lang;
739cd52f92dSchris    global $auth;
7408b06d178Schris
741beca106aSAdrian Lang    if (!$auth) return false;
742bb4866bdSchris    if(empty($_POST['save'])) return false;
7431b2a85e8SAndreas Gohr    if(!checkSecurityToken()) return false;
7448b06d178Schris
74582fd59b6SAndreas Gohr    // should not be able to get here without Profile being possible...
74682fd59b6SAndreas Gohr    if(!$auth->canDo('Profile')) {
7478b06d178Schris        msg($lang['profna'],-1);
7488b06d178Schris        return false;
7498b06d178Schris    }
7508b06d178Schris
7518b06d178Schris    if ($_POST['newpass'] != $_POST['passchk']) {
7528b06d178Schris        msg($lang['regbadpass'], -1);      // complain about misspelled passwords
7538b06d178Schris        return false;
7548b06d178Schris    }
7558b06d178Schris
7568b06d178Schris    //clean fullname and email
75754f0e6eaSAndreas Gohr    $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
75854f0e6eaSAndreas Gohr    $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
7598b06d178Schris
7604369edafSAndy Webber    if ((empty($_POST['fullname']) && $auth->canDo('modName')) ||
7614369edafSAndy Webber        (empty($_POST['email']) && $auth->canDo('modMail'))) {
7628b06d178Schris        msg($lang['profnoempty'],-1);
7638b06d178Schris        return false;
7648b06d178Schris    }
7658b06d178Schris
7664369edafSAndy Webber    if (!mail_isvalid($_POST['email']) && $auth->canDo('modMail')){
7678b06d178Schris        msg($lang['regbadmail'],-1);
7688b06d178Schris        return false;
7698b06d178Schris    }
7708b06d178Schris
7714c21b7eeSAndreas Gohr    if ($_POST['fullname'] != $INFO['userinfo']['name'] && $auth->canDo('modName')) $changes['name'] = $_POST['fullname'];
7724c21b7eeSAndreas Gohr    if ($_POST['email'] != $INFO['userinfo']['mail'] && $auth->canDo('modMail')) $changes['mail'] = $_POST['email'];
773cf626a62SAndreas Gohr    if (!empty($_POST['newpass']) && $auth->canDo('modPass')) $changes['pass'] = $_POST['newpass'];
7744c21b7eeSAndreas Gohr
7758b06d178Schris    if (!count($changes)) {
7768b06d178Schris        msg($lang['profnochange'], -1);
7778b06d178Schris        return false;
7788b06d178Schris    }
7798b06d178Schris
7808b06d178Schris    if ($conf['profileconfirm']) {
781df466c7aSAndreas Gohr        if (!$auth->checkPass($_SERVER['REMOTE_USER'], $_POST['oldpass'])) {
7828b06d178Schris            msg($lang['badlogin'],-1);
7838b06d178Schris            return false;
7848b06d178Schris        }
7858b06d178Schris    }
7868b06d178Schris
787a0b5b007SChris Smith    if ($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
788a0b5b007SChris Smith        // update cookie and session with the changed data
789a0b5b007SChris Smith        $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
7904b7f9e70STom N Harris        list($user,$sticky,$pass) = explode('|',$cookie,3);
791a0b5b007SChris Smith        if ($changes['pass']) $pass = PMA_blowfish_encrypt($changes['pass'],auth_cookiesalt());
792a0b5b007SChris Smith
793a0b5b007SChris Smith        auth_setCookie($_SERVER['REMOTE_USER'],$pass,(bool)$sticky);
79425b2a98cSMichael Klier        return true;
795a0b5b007SChris Smith    }
7968b06d178Schris}
7978b06d178Schris
7988b06d178Schris/**
7998b06d178Schris * Send a  new password
8008b06d178Schris *
8011d5856cfSAndreas Gohr * This function handles both phases of the password reset:
8021d5856cfSAndreas Gohr *
8031d5856cfSAndreas Gohr *   - handling the first request of password reset
8041d5856cfSAndreas Gohr *   - validating the password reset auth token
8051d5856cfSAndreas Gohr *
8068b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
8078b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
8081d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
8098b06d178Schris *
8108b06d178Schris * @return bool true on success, false on any error
8118b06d178Schris */
8128b06d178Schrisfunction act_resendpwd(){
8138b06d178Schris    global $lang;
8148b06d178Schris    global $conf;
815cd52f92dSchris    global $auth;
8168b06d178Schris
817409d7af7SAndreas Gohr    if(!actionOK('resendpwd')) return false;
818beca106aSAdrian Lang    if (!$auth) return false;
8198b06d178Schris
82082fd59b6SAndreas Gohr    // should not be able to get here without modPass being possible...
82182fd59b6SAndreas Gohr    if(!$auth->canDo('modPass')) {
8228b06d178Schris        msg($lang['resendna'],-1);
8238b06d178Schris        return false;
8248b06d178Schris    }
8258b06d178Schris
8261d5856cfSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
8278b06d178Schris
8281d5856cfSAndreas Gohr    if($token){
8291d5856cfSAndreas Gohr        // we're in token phase
8301d5856cfSAndreas Gohr
8311d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
8321d5856cfSAndreas Gohr        if(!@file_exists($tfile)){
8331d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'],-1);
8341d5856cfSAndreas Gohr            return false;
8351d5856cfSAndreas Gohr        }
8361d5856cfSAndreas Gohr        $user = io_readfile($tfile);
8371d5856cfSAndreas Gohr        @unlink($tfile);
838cd52f92dSchris        $userinfo = $auth->getUserData($user);
8398b06d178Schris        if(!$userinfo['mail']) {
8408b06d178Schris            msg($lang['resendpwdnouser'], -1);
8418b06d178Schris            return false;
8428b06d178Schris        }
8438b06d178Schris
8448b06d178Schris        $pass = auth_pwgen();
8457d3c8d42SGabriel Birke        if (!$auth->triggerUserMod('modify', array($user,array('pass' => $pass)))) {
8468b06d178Schris            msg('error modifying user data',-1);
8478b06d178Schris            return false;
8488b06d178Schris        }
8498b06d178Schris
8508b06d178Schris        if (auth_sendPassword($user,$pass)) {
8518b06d178Schris            msg($lang['resendpwdsuccess'],1);
8528b06d178Schris        } else {
8538b06d178Schris            msg($lang['regmailfail'],-1);
8548b06d178Schris        }
8558b06d178Schris        return true;
8561d5856cfSAndreas Gohr
8571d5856cfSAndreas Gohr    } else {
8581d5856cfSAndreas Gohr        // we're in request phase
8591d5856cfSAndreas Gohr
8601d5856cfSAndreas Gohr        if(!$_POST['save']) return false;
8611d5856cfSAndreas Gohr
8621d5856cfSAndreas Gohr        if (empty($_POST['login'])) {
8631d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
8641d5856cfSAndreas Gohr            return false;
8651d5856cfSAndreas Gohr        } else {
866d752aedeSAndreas Gohr            $user = trim($auth->cleanUser($_POST['login']));
8671d5856cfSAndreas Gohr        }
8681d5856cfSAndreas Gohr
8691d5856cfSAndreas Gohr        $userinfo = $auth->getUserData($user);
8701d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
8711d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
8721d5856cfSAndreas Gohr            return false;
8731d5856cfSAndreas Gohr        }
8741d5856cfSAndreas Gohr
8751d5856cfSAndreas Gohr        // generate auth token
8761d5856cfSAndreas Gohr        $token = md5(auth_cookiesalt().$user); //secret but user based
8771d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
8781d5856cfSAndreas Gohr        $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
8791d5856cfSAndreas Gohr
8801d5856cfSAndreas Gohr        io_saveFile($tfile,$user);
8811d5856cfSAndreas Gohr
8821d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
8831d5856cfSAndreas Gohr        $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
8841d5856cfSAndreas Gohr        $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
8851d5856cfSAndreas Gohr        $text = str_replace('@LOGIN@',$user,$text);
8861d5856cfSAndreas Gohr        $text = str_replace('@TITLE@',$conf['title'],$text);
8871d5856cfSAndreas Gohr        $text = str_replace('@CONFIRM@',$url,$text);
8881d5856cfSAndreas Gohr
8891d5856cfSAndreas Gohr        if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
8901d5856cfSAndreas Gohr                     $lang['regpwmail'],
8911d5856cfSAndreas Gohr                     $text,
8921d5856cfSAndreas Gohr                     $conf['mailfrom'])){
8931d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'],1);
8941d5856cfSAndreas Gohr        }else{
8951d5856cfSAndreas Gohr            msg($lang['regmailfail'],-1);
8961d5856cfSAndreas Gohr        }
8971d5856cfSAndreas Gohr        return true;
8981d5856cfSAndreas Gohr    }
8991d5856cfSAndreas Gohr
9001d5856cfSAndreas Gohr    return false; // never reached
9018b06d178Schris}
9028b06d178Schris
9038b06d178Schris/**
904b0855b11Sandi * Encrypts a password using the given method and salt
905b0855b11Sandi *
906b0855b11Sandi * If the selected method needs a salt and none was given, a random one
907b0855b11Sandi * is chosen.
908b0855b11Sandi *
909b0855b11Sandi * The following methods are understood:
910b0855b11Sandi *
911b0855b11Sandi *   smd5  - Salted MD5 hashing
912577c7cdaSAndreas Gohr *   apr1  - Apache salted MD5 hashing
913b0855b11Sandi *   md5   - Simple MD5 hashing
914b0855b11Sandi *   sha1  - SHA1 hashing
915b0855b11Sandi *   ssha  - Salted SHA1 hashing
916d7be6245Sandi *   crypt - Unix crypt
917d7be6245Sandi *   mysql - MySQL password (old method)
918d7be6245Sandi *   my411 - MySQL 4.1.1 password
91943ee7484SAndreas Gohr *   kmd5  - Salted MD5 hashing as used by UNB
920b0855b11Sandi *
921b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
922b0855b11Sandi * @return  string  The crypted password
923b0855b11Sandi */
924577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear,$method='',$salt=null){
925b0855b11Sandi    global $conf;
926b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
92710a76f6fSfrank
928b0855b11Sandi    //prepare a salt
929577c7cdaSAndreas Gohr    if(is_null($salt)) $salt = md5(uniqid(rand(), true));
930b0855b11Sandi
931b0855b11Sandi    switch(strtolower($method)){
932b0855b11Sandi        case 'smd5':
933056cb2ccSChris Smith            if(defined('CRYPT_MD5') && CRYPT_MD5) return crypt($clear,'$1$'.substr($salt,0,8).'$');
934577c7cdaSAndreas Gohr            // when crypt can't handle SMD5, falls through to pure PHP implementation
935577c7cdaSAndreas Gohr            $magic = '1';
936577c7cdaSAndreas Gohr        case 'apr1':
937577c7cdaSAndreas Gohr            //from http://de.php.net/manual/en/function.crypt.php#73619 comment by <mikey_nich at hotmail dot com>
9383371a8b4SAdrian Lang            if(!isset($magic)) $magic = 'apr1';
939577c7cdaSAndreas Gohr            $salt = substr($salt,0,8);
940577c7cdaSAndreas Gohr            $len = strlen($clear);
941577c7cdaSAndreas Gohr            $text = $clear.'$'.$magic.'$'.$salt;
942577c7cdaSAndreas Gohr            $bin = pack("H32", md5($clear.$salt.$clear));
943db959ae3SAndreas Gohr            for($i = $len; $i > 0; $i -= 16) {
944db959ae3SAndreas Gohr                $text .= substr($bin, 0, min(16, $i));
945db959ae3SAndreas Gohr            }
946db959ae3SAndreas Gohr            for($i = $len; $i > 0; $i >>= 1) {
947db959ae3SAndreas Gohr                $text .= ($i & 1) ? chr(0) : $clear{0};
948db959ae3SAndreas Gohr            }
949577c7cdaSAndreas Gohr            $bin = pack("H32", md5($text));
950577c7cdaSAndreas Gohr            for($i = 0; $i < 1000; $i++) {
951577c7cdaSAndreas Gohr                $new = ($i & 1) ? $clear : $bin;
952577c7cdaSAndreas Gohr                if ($i % 3) $new .= $salt;
953577c7cdaSAndreas Gohr                if ($i % 7) $new .= $clear;
954577c7cdaSAndreas Gohr                $new .= ($i & 1) ? $bin : $clear;
955577c7cdaSAndreas Gohr                $bin = pack("H32", md5($new));
956577c7cdaSAndreas Gohr            }
957577c7cdaSAndreas Gohr            $tmp = '';
958577c7cdaSAndreas Gohr            for ($i = 0; $i < 5; $i++) {
959577c7cdaSAndreas Gohr                $k = $i + 6;
960577c7cdaSAndreas Gohr                $j = $i + 12;
961577c7cdaSAndreas Gohr                if ($j == 16) $j = 5;
962577c7cdaSAndreas Gohr                $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
963577c7cdaSAndreas Gohr            }
964577c7cdaSAndreas Gohr            $tmp = chr(0).chr(0).$bin[11].$tmp;
965577c7cdaSAndreas Gohr            $tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
966577c7cdaSAndreas Gohr                    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
967577c7cdaSAndreas Gohr                    "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
968577c7cdaSAndreas Gohr            return '$'.$magic.'$'.$salt.'$'.$tmp;
969b0855b11Sandi        case 'md5':
970b0855b11Sandi            return md5($clear);
971b0855b11Sandi        case 'sha1':
972b0855b11Sandi            return sha1($clear);
973b0855b11Sandi        case 'ssha':
974b0855b11Sandi            $salt=substr($salt,0,4);
975d6e54e02Smatthiasgrimm            return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
976b0855b11Sandi        case 'crypt':
977b0855b11Sandi            return crypt($clear,substr($salt,0,2));
978d7be6245Sandi        case 'mysql':
979d7be6245Sandi            //from http://www.php.net/mysql comment by <soren at byu dot edu>
980d7be6245Sandi            $nr=0x50305735;
981d7be6245Sandi            $nr2=0x12345671;
982d7be6245Sandi            $add=7;
983d7be6245Sandi            $charArr = preg_split("//", $clear);
984d7be6245Sandi            foreach ($charArr as $char) {
985d7be6245Sandi                if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
986d7be6245Sandi                $charVal = ord($char);
987d7be6245Sandi                $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
988d7be6245Sandi                $nr2 += ($nr2 << 8) ^ $nr;
989d7be6245Sandi                $add += $charVal;
990d7be6245Sandi            }
991d7be6245Sandi            return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
992d7be6245Sandi        case 'my411':
993d7be6245Sandi            return '*'.sha1(pack("H*", sha1($clear)));
99443ee7484SAndreas Gohr        case 'kmd5':
99543ee7484SAndreas Gohr            $key = substr($salt, 16, 2);
99643ee7484SAndreas Gohr            $hash1 = strtolower(md5($key . md5($clear)));
99743ee7484SAndreas Gohr            $hash2 = substr($hash1, 0, 16) . $key . substr($hash1, 16);
99843ee7484SAndreas Gohr            return $hash2;
999b0855b11Sandi        default:
1000b0855b11Sandi            msg("Unsupported crypt method $method",-1);
1001b0855b11Sandi    }
1002b0855b11Sandi}
1003b0855b11Sandi
1004b0855b11Sandi/**
1005b0855b11Sandi * Verifies a cleartext password against a crypted hash
1006b0855b11Sandi *
1007b0855b11Sandi * The method and salt used for the crypted hash is determined automatically
1008b0855b11Sandi * then the clear text password is crypted using the same method. If both hashs
1009b0855b11Sandi * match true is is returned else false
1010b0855b11Sandi *
1011b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
1012b0855b11Sandi * @return  bool
1013b0855b11Sandi */
1014b0855b11Sandifunction auth_verifyPassword($clear,$crypt){
1015b0855b11Sandi    $method='';
1016b0855b11Sandi    $salt='';
1017b0855b11Sandi
1018b0855b11Sandi    //determine the used method and salt
1019d7be6245Sandi    $len = strlen($crypt);
1020577c7cdaSAndreas Gohr    if(preg_match('/^\$1\$([^\$]{0,8})\$/',$crypt,$m)){
1021b0855b11Sandi        $method = 'smd5';
1022577c7cdaSAndreas Gohr        $salt   = $m[1];
1023577c7cdaSAndreas Gohr    }elseif(preg_match('/^\$apr1\$([^\$]{0,8})\$/',$crypt,$m)){
1024577c7cdaSAndreas Gohr        $method = 'apr1';
1025577c7cdaSAndreas Gohr        $salt   = $m[1];
1026b0855b11Sandi    }elseif(substr($crypt,0,6) == '{SSHA}'){
1027b0855b11Sandi        $method = 'ssha';
1028b0855b11Sandi        $salt   = substr(base64_decode(substr($crypt, 6)),20);
1029d7be6245Sandi    }elseif($len == 32){
1030b0855b11Sandi        $method = 'md5';
1031d7be6245Sandi    }elseif($len == 40){
1032b0855b11Sandi        $method = 'sha1';
1033d7be6245Sandi    }elseif($len == 16){
1034d7be6245Sandi        $method = 'mysql';
1035d7be6245Sandi    }elseif($len == 41 && $crypt[0] == '*'){
1036d7be6245Sandi        $method = 'my411';
103743ee7484SAndreas Gohr    }elseif($len == 34){
103843ee7484SAndreas Gohr        $method = 'kmd5';
103943ee7484SAndreas Gohr        $salt   = $crypt;
1040b0855b11Sandi    }else{
1041b0855b11Sandi        $method = 'crypt';
1042b0855b11Sandi        $salt   = substr($crypt,0,2);
1043b0855b11Sandi    }
1044b0855b11Sandi
1045b0855b11Sandi    //crypt and compare
1046b0855b11Sandi    if(auth_cryptPassword($clear,$method,$salt) === $crypt){
1047b0855b11Sandi        return true;
1048b0855b11Sandi    }
1049b0855b11Sandi    return false;
1050b0855b11Sandi}
1051340756e4Sandi
1052a0b5b007SChris Smith/**
1053a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1054a0b5b007SChris Smith *
1055a0b5b007SChris Smith * @param string  $user       username
1056a0b5b007SChris Smith * @param string  $pass       encrypted password
1057a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1058a0b5b007SChris Smith */
1059a0b5b007SChris Smithfunction auth_setCookie($user,$pass,$sticky) {
1060a0b5b007SChris Smith    global $conf;
1061a0b5b007SChris Smith    global $auth;
106279d00841SOliver Geisen    global $USERINFO;
1063a0b5b007SChris Smith
1064beca106aSAdrian Lang    if (!$auth) return false;
1065a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1066a0b5b007SChris Smith
1067a0b5b007SChris Smith    // set cookie
1068645c0a36SAndreas Gohr    $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
1069c66972f2SAdrian Lang    $time = $sticky ? (time()+60*60*24*365) : 0; //one year
1070a0b5b007SChris Smith    if (version_compare(PHP_VERSION, '5.2.0', '>')) {
1071a0b5b007SChris Smith        setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true);
1072a0b5b007SChris Smith    }else{
1073a0b5b007SChris Smith        setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()));
1074a0b5b007SChris Smith    }
1075a0b5b007SChris Smith    // set session
1076a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1077a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['pass'] = $pass;
1078a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1079a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1080a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1081a0b5b007SChris Smith}
1082a0b5b007SChris Smith
1083645c0a36SAndreas Gohr/**
1084645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1085645c0a36SAndreas Gohr *
1086645c0a36SAndreas Gohr * @returns array
1087645c0a36SAndreas Gohr */
1088645c0a36SAndreas Gohrfunction auth_getCookie(){
1089c66972f2SAdrian Lang    if (!isset($_COOKIE[DOKU_COOKIE])) {
1090c66972f2SAdrian Lang        return array(null, null, null);
1091c66972f2SAdrian Lang    }
1092645c0a36SAndreas Gohr    list($user,$sticky,$pass) = explode('|',$_COOKIE[DOKU_COOKIE],3);
1093645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1094645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1095645c0a36SAndreas Gohr    $user   = base64_decode($user);
1096645c0a36SAndreas Gohr    return array($user,$sticky,$pass);
1097645c0a36SAndreas Gohr}
1098645c0a36SAndreas Gohr
1099340756e4Sandi//Setup VIM: ex: et ts=2 enc=utf-8 :
1100