xref: /dokuwiki/inc/auth.php (revision 191bb90af90d4b063435ee55d67082e7453ed1fb)
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.');
13ed7b5f09Sandirequire_once(DOKU_INC.'inc/common.php');
14ed7b5f09Sandirequire_once(DOKU_INC.'inc/io.php');
151c73890cSAndreas Gohr
16ebf97c8fSAndreas Gohr// some ACL level defines
17ebf97c8fSAndreas Gohrdefine('AUTH_NONE',0);
18ebf97c8fSAndreas Gohrdefine('AUTH_READ',1);
19ebf97c8fSAndreas Gohrdefine('AUTH_EDIT',2);
20ebf97c8fSAndreas Gohrdefine('AUTH_CREATE',4);
21ebf97c8fSAndreas Gohrdefine('AUTH_UPLOAD',8);
22ebf97c8fSAndreas Gohrdefine('AUTH_DELETE',16);
23ebf97c8fSAndreas Gohrdefine('AUTH_ADMIN',255);
24ebf97c8fSAndreas Gohr
25742c66f8Schrisglobal $conf;
26742c66f8Schris
271c73890cSAndreas Gohrif($conf['useacl']){
28ed7b5f09Sandi    require_once(DOKU_INC.'inc/blowfish.php');
29ed7b5f09Sandi    require_once(DOKU_INC.'inc/mail.php');
308b06d178Schris
3103c4aec3Schris    global $auth;
3203c4aec3Schris
338b06d178Schris    // load the the backend auth functions and instantiate the auth object
348b06d178Schris    if (@file_exists(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php')) {
358b06d178Schris        require_once(DOKU_INC.'inc/auth/basic.class.php');
368b06d178Schris        require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php');
378b06d178Schris
388b06d178Schris        $auth_class = "auth_".$conf['authtype'];
39cd52f92dSchris        if (class_exists($auth_class)) {
408b06d178Schris            $auth = new $auth_class();
41d2dde4ebSMatthias Grimm            if ($auth->success == false) {
420f4f4adfSAndreas Gohr                // degrade to unauthenticated user
43d2dde4ebSMatthias Grimm                unset($auth);
440f4f4adfSAndreas Gohr                auth_logoff();
45cd52f92dSchris                msg($lang['authtempfail'], -1);
46d2dde4ebSMatthias Grimm            }
478b06d178Schris        } else {
483816dcbcSAndreas Gohr            nice_die($lang['authmodfailed']);
49cd52f92dSchris        }
50cd52f92dSchris    } else {
513816dcbcSAndreas Gohr        nice_die($lang['authmodfailed']);
528b06d178Schris    }
531c73890cSAndreas Gohr}
54f3f0262cSandi
55f5cb575dSAndreas Gohr// do the login either by cookie or provided credentials
561ec50243SAndreas Gohrif($conf['useacl']){
571ec50243SAndreas Gohr    if($auth){
58bbbd6568SAndreas Gohr        if (!isset($_REQUEST['u'])) $_REQUEST['u'] = '';
59bbbd6568SAndreas Gohr        if (!isset($_REQUEST['p'])) $_REQUEST['p'] = '';
60bbbd6568SAndreas Gohr        if (!isset($_REQUEST['r'])) $_REQUEST['r'] = '';
61b2c0d874SGina Haeussge        $_REQUEST['http_credentials'] = false;
6217f89d7eSMichael Klier        if (!$conf['rememberme']) $_REQUEST['r'] = false;
63bbbd6568SAndreas Gohr
64528ddc7cSAndreas Gohr        // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
6506156f3cSAndreas Gohr        if(isset($_SERVER['HTTP_AUTHORIZATION'])){
66528ddc7cSAndreas Gohr            list($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']) =
67528ddc7cSAndreas Gohr                explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
68528ddc7cSAndreas Gohr        }
69528ddc7cSAndreas Gohr
701e8c9c90SAndreas Gohr        // if no credentials were given try to use HTTP auth (for SSO)
714a26ad85Schris        if(empty($_REQUEST['u']) && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])){
721e8c9c90SAndreas Gohr            $_REQUEST['u'] = $_SERVER['PHP_AUTH_USER'];
731e8c9c90SAndreas Gohr            $_REQUEST['p'] = $_SERVER['PHP_AUTH_PW'];
74b2c0d874SGina Haeussge            $_REQUEST['http_credentials'] = true;
751e8c9c90SAndreas Gohr        }
761e8c9c90SAndreas Gohr
77*191bb90aSAndreas Gohr        // apply cleaning
78*191bb90aSAndreas Gohr        $_REQUEST['u'] = $auth->cleanUser($_REQUEST['u']);
79*191bb90aSAndreas Gohr
80c66972f2SAdrian Lang        if(isset($_REQUEST['authtok'])){
81f13fa892SAndreas Gohr            // when an authentication token is given, trust the session
82f13fa892SAndreas Gohr            auth_validateToken($_REQUEST['authtok']);
83f13fa892SAndreas Gohr        }elseif(!is_null($auth) && $auth->canDo('external')){
84f13fa892SAndreas Gohr            // external trust mechanism in place
85f5cb575dSAndreas Gohr            $auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
86f5cb575dSAndreas Gohr        }else{
876080c584SRobin Gareus            $evdata = array(
886080c584SRobin Gareus                    'user'     => $_REQUEST['u'],
896080c584SRobin Gareus                    'password' => $_REQUEST['p'],
906080c584SRobin Gareus                    'sticky'   => $_REQUEST['r'],
916080c584SRobin Gareus                    'silent'   => $_REQUEST['http_credentials'],
926080c584SRobin Gareus                    );
93643bdba8SAndreas Gohr            $evt = new Doku_Event('AUTH_LOGIN_CHECK',$evdata);
946080c584SRobin Gareus            if($evt->advise_before()){
956080c584SRobin Gareus                auth_login($evdata['user'],
966080c584SRobin Gareus                           $evdata['password'],
976080c584SRobin Gareus                           $evdata['sticky'],
986080c584SRobin Gareus                           $evdata['silent']);
996080c584SRobin Gareus            }
100f5cb575dSAndreas Gohr        }
1011ec50243SAndreas Gohr    }
102f5cb575dSAndreas Gohr
10315fae107Sandi    //load ACL into a global array
10488e6a4f2SAndreas Gohr    global $AUTH_ACL;
105e7cb32dcSAndreas Gohr    if(is_readable(DOKU_CONF.'acl.auth.php')){
106e7cb32dcSAndreas Gohr        $AUTH_ACL = file(DOKU_CONF.'acl.auth.php');
107*191bb90aSAndreas Gohr        //support user wildcard
108f8cc3354SGuy Brand        if(isset($_SERVER['REMOTE_USER'])){
1095d87b2ccSAndreas Gohr            $AUTH_ACL = str_replace('%USER%',$_SERVER['REMOTE_USER'],$AUTH_ACL);
1105d87b2ccSAndreas Gohr            $AUTH_ACL = str_replace('@USER@',$_SERVER['REMOTE_USER'],$AUTH_ACL); //legacy
111a8fe108bSGuy Brand        }
11211799630Sandi    }else{
11311799630Sandi        $AUTH_ACL = array();
11411799630Sandi    }
115f3f0262cSandi}
116f3f0262cSandi
117f3f0262cSandi/**
118f3f0262cSandi * This tries to login the user based on the sent auth credentials
119f3f0262cSandi *
120f3f0262cSandi * The authentication works like this: if a username was given
12115fae107Sandi * a new login is assumed and user/password are checked. If they
12215fae107Sandi * are correct the password is encrypted with blowfish and stored
12315fae107Sandi * together with the username in a cookie - the same info is stored
12415fae107Sandi * in the session, too. Additonally a browserID is stored in the
12515fae107Sandi * session.
12615fae107Sandi *
12715fae107Sandi * If no username was given the cookie is checked: if the username,
12815fae107Sandi * crypted password and browserID match between session and cookie
12915fae107Sandi * no further testing is done and the user is accepted
13015fae107Sandi *
13115fae107Sandi * If a cookie was found but no session info was availabe the
132136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
13315fae107Sandi * together with username rechecked by calling this function again.
134f3f0262cSandi *
135f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
136f3f0262cSandi * are set.
13715fae107Sandi *
13815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
13915fae107Sandi *
14015fae107Sandi * @param   string  $user    Username
14115fae107Sandi * @param   string  $pass    Cleartext Password
14215fae107Sandi * @param   bool    $sticky  Cookie should not expire
143f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
14415fae107Sandi * @return  bool             true on successful auth
145f3f0262cSandi */
146f112c2faSAndreas Gohrfunction auth_login($user,$pass,$sticky=false,$silent=false){
147f3f0262cSandi    global $USERINFO;
148f3f0262cSandi    global $conf;
149f3f0262cSandi    global $lang;
150cd52f92dSchris    global $auth;
151132bdbfeSandi    $sticky ? $sticky = true : $sticky = false; //sanity check
152f3f0262cSandi
153bbbd6568SAndreas Gohr    if(!empty($user)){
154132bdbfeSandi        //usual login
155cd52f92dSchris        if ($auth->checkPass($user,$pass)){
156132bdbfeSandi            // make logininfo globally available
157f3f0262cSandi            $_SERVER['REMOTE_USER'] = $user;
158a0b5b007SChris Smith            auth_setCookie($user,PMA_blowfish_encrypt($pass,auth_cookiesalt()),$sticky);
159132bdbfeSandi            return true;
160f3f0262cSandi        }else{
161f3f0262cSandi            //invalid credentials - log off
162f112c2faSAndreas Gohr            if(!$silent) msg($lang['badlogin'],-1);
163f3f0262cSandi            auth_logoff();
164132bdbfeSandi            return false;
165f3f0262cSandi        }
166f3f0262cSandi    }else{
167132bdbfeSandi        // read cookie information
168645c0a36SAndreas Gohr        list($user,$sticky,$pass) = auth_getCookie();
169132bdbfeSandi        // get session info
170e71ce681SAndreas Gohr        $session = $_SESSION[DOKU_COOKIE]['auth'];
171132bdbfeSandi        if($user && $pass){
172132bdbfeSandi            // we got a cookie - see if we can trust it
173132bdbfeSandi            if(isset($session) &&
1747172dbc0SAndreas Gohr                    $auth->useSessionCache($user) &&
1754c989037SChris Smith                    ($session['time'] >= time()-$conf['auth_security_timeout']) &&
176132bdbfeSandi                    ($session['user'] == $user) &&
177132bdbfeSandi                    ($session['pass'] == $pass) &&  //still crypted
178132bdbfeSandi                    ($session['buid'] == auth_browseruid()) ){
179132bdbfeSandi                // he has session, cookie and browser right - let him in
180132bdbfeSandi                $_SERVER['REMOTE_USER'] = $user;
181132bdbfeSandi                $USERINFO = $session['info']; //FIXME move all references to session
182132bdbfeSandi                return true;
183132bdbfeSandi            }
184f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
185132bdbfeSandi            $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
186f112c2faSAndreas Gohr            return auth_login($user,$pass,$sticky,true);
187132bdbfeSandi        }
188132bdbfeSandi    }
189f3f0262cSandi    //just to be sure
190883179a4SAndreas Gohr    auth_logoff(true);
191132bdbfeSandi    return false;
192f3f0262cSandi}
193132bdbfeSandi
194132bdbfeSandi/**
195f13fa892SAndreas Gohr * Checks if a given authentication token was stored in the session
196f13fa892SAndreas Gohr *
197f13fa892SAndreas Gohr * Will setup authentication data using data from the session if the
198f13fa892SAndreas Gohr * token is correct. Will exit with a 401 Status if not.
199f13fa892SAndreas Gohr *
200f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
201f13fa892SAndreas Gohr * @param  string $token The authentication token
202f13fa892SAndreas Gohr * @return boolean true (or will exit on failure)
203f13fa892SAndreas Gohr */
204f13fa892SAndreas Gohrfunction auth_validateToken($token){
205f13fa892SAndreas Gohr    if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']){
206f13fa892SAndreas Gohr        // bad token
207f13fa892SAndreas Gohr        header("HTTP/1.0 401 Unauthorized");
208f13fa892SAndreas Gohr        print 'Invalid auth token - maybe the session timed out';
209f13fa892SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
210f13fa892SAndreas Gohr        exit;
211f13fa892SAndreas Gohr    }
212f13fa892SAndreas Gohr    // still here? trust the session data
213f13fa892SAndreas Gohr    global $USERINFO;
214f13fa892SAndreas Gohr    $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
215f13fa892SAndreas Gohr    $USERINFO = $_SESSION[DOKU_COOKIE]['auth']['info'];
216f13fa892SAndreas Gohr    return true;
217f13fa892SAndreas Gohr}
218f13fa892SAndreas Gohr
219f13fa892SAndreas Gohr/**
220f13fa892SAndreas Gohr * Create an auth token and store it in the session
221f13fa892SAndreas Gohr *
222f13fa892SAndreas Gohr * NOTE: this is completely unrelated to the getSecurityToken() function
223f13fa892SAndreas Gohr *
224f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
225f13fa892SAndreas Gohr * @return string The auth token
226f13fa892SAndreas Gohr */
227f13fa892SAndreas Gohrfunction auth_createToken(){
228f13fa892SAndreas Gohr    $token = md5(mt_rand());
22909c2d803SAndreas Gohr    @session_start(); // reopen the session if needed
230f13fa892SAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
23109c2d803SAndreas Gohr    session_write_close();
232f13fa892SAndreas Gohr    return $token;
233f13fa892SAndreas Gohr}
234f13fa892SAndreas Gohr
235f13fa892SAndreas Gohr/**
236136ce040Sandi * Builds a pseudo UID from browser and IP data
237132bdbfeSandi *
238132bdbfeSandi * This is neither unique nor unfakable - still it adds some
239136ce040Sandi * security. Using the first part of the IP makes sure
240136ce040Sandi * proxy farms like AOLs are stil okay.
24115fae107Sandi *
24215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
24315fae107Sandi *
24415fae107Sandi * @return  string  a MD5 sum of various browser headers
245132bdbfeSandi */
246132bdbfeSandifunction auth_browseruid(){
2472f9daf16SAndreas Gohr    $ip   = clientIP(true);
248132bdbfeSandi    $uid  = '';
249132bdbfeSandi    $uid .= $_SERVER['HTTP_USER_AGENT'];
250132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
251132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
252132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
2532f9daf16SAndreas Gohr    $uid .= substr($ip,0,strpos($ip,'.'));
254132bdbfeSandi    return md5($uid);
255132bdbfeSandi}
256132bdbfeSandi
257132bdbfeSandi/**
258132bdbfeSandi * Creates a random key to encrypt the password in cookies
25915fae107Sandi *
26015fae107Sandi * This function tries to read the password for encrypting
26198407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
26215fae107Sandi * if no such file is found a random key is created and
26315fae107Sandi * and stored in this file.
26415fae107Sandi *
26515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
26615fae107Sandi *
26715fae107Sandi * @return  string
268132bdbfeSandi */
269132bdbfeSandifunction auth_cookiesalt(){
270132bdbfeSandi    global $conf;
27198407a7aSandi    $file = $conf['metadir'].'/_htcookiesalt';
272132bdbfeSandi    $salt = io_readFile($file);
273132bdbfeSandi    if(empty($salt)){
274132bdbfeSandi        $salt = uniqid(rand(),true);
275132bdbfeSandi        io_saveFile($file,$salt);
276132bdbfeSandi    }
277132bdbfeSandi    return $salt;
278f3f0262cSandi}
279f3f0262cSandi
280f3f0262cSandi/**
281883179a4SAndreas Gohr * Log out the current user
282883179a4SAndreas Gohr *
283f3f0262cSandi * This clears all authentication data and thus log the user
284883179a4SAndreas Gohr * off. It also clears session data.
28515fae107Sandi *
28615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
287883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
288f3f0262cSandi */
289883179a4SAndreas Gohrfunction auth_logoff($keepbc=false){
290f3f0262cSandi    global $conf;
291f3f0262cSandi    global $USERINFO;
2928b06d178Schris    global $INFO, $ID;
2935298a619SAndreas Gohr    global $auth;
29437065e65Sandi
295d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
296e9621d07SAndreas Gohr    @session_start();
297e9621d07SAndreas Gohr
298e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
299e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
300e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
301e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
302e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
303e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
304883179a4SAndreas Gohr    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
305e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
30637065e65Sandi    if(isset($_SERVER['REMOTE_USER']))
307f3f0262cSandi        unset($_SERVER['REMOTE_USER']);
308132bdbfeSandi    $USERINFO=null; //FIXME
309f5c6743cSAndreas Gohr
310f5c6743cSAndreas Gohr    if (version_compare(PHP_VERSION, '5.2.0', '>')) {
31185c6f7d0SAndreas Gohr        setcookie(DOKU_COOKIE,'',time()-600000,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true);
312f5c6743cSAndreas Gohr    }else{
31385c6f7d0SAndreas Gohr        setcookie(DOKU_COOKIE,'',time()-600000,DOKU_REL,'',($conf['securecookie'] && is_ssl()));
314f5c6743cSAndreas Gohr    }
3155298a619SAndreas Gohr
3165298a619SAndreas Gohr    if($auth && $auth->canDo('logoff')){
3175298a619SAndreas Gohr        $auth->logOff();
3185298a619SAndreas Gohr    }
319f3f0262cSandi}
320f3f0262cSandi
321f3f0262cSandi/**
322f8cc712eSAndreas Gohr * Check if a user is a manager
323f8cc712eSAndreas Gohr *
324f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
325f8cc712eSAndreas Gohr * user.
326f8cc712eSAndreas Gohr *
327f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
328f8cc712eSAndreas Gohr *
329f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
330f8cc712eSAndreas Gohr * @see    auth_isadmin
331f8cc712eSAndreas Gohr * @param  string user      - Username
332f8cc712eSAndreas Gohr * @param  array  groups    - List of groups the user is in
333f8cc712eSAndreas Gohr * @param  bool   adminonly - when true checks if user is admin
334f8cc712eSAndreas Gohr */
335f8cc712eSAndreas Gohrfunction auth_ismanager($user=null,$groups=null,$adminonly=false){
336f8cc712eSAndreas Gohr    global $conf;
337f8cc712eSAndreas Gohr    global $USERINFO;
338f8cc712eSAndreas Gohr
339f8cc712eSAndreas Gohr    if(!$conf['useacl']) return false;
340c66972f2SAdrian Lang    if(is_null($user)) {
341c66972f2SAdrian Lang        if (!isset($_SERVER['REMOTE_USER'])) {
342c66972f2SAdrian Lang            return false;
343c66972f2SAdrian Lang        } else {
344c66972f2SAdrian Lang            $user = $_SERVER['REMOTE_USER'];
345c66972f2SAdrian Lang        }
346c66972f2SAdrian Lang    }
34790583e9fSAndreas Gohr    if(is_null($groups)) $groups = (array) $USERINFO['grps'];
348f8cc712eSAndreas Gohr    $user   = auth_nameencode($user);
349f8cc712eSAndreas Gohr
350f8cc712eSAndreas Gohr    // check username against superuser and manager
3517651d633SGuy Brand    $superusers = explode(',', $conf['superuser']);
3527651d633SGuy Brand    $superusers = array_unique($superusers);
3537651d633SGuy Brand    $superusers = array_map('trim', $superusers);
3547651d633SGuy Brand    // prepare an array containing only true values for array_map call
3557651d633SGuy Brand    $alltrue = array_fill(0, count($superusers), true);
3567651d633SGuy Brand    $superusers = array_map('auth_nameencode', $superusers, $alltrue);
3577651d633SGuy Brand    if(in_array($user, $superusers)) return true;
3587651d633SGuy Brand
359f8cc712eSAndreas Gohr    if(!$adminonly){
3607651d633SGuy Brand        $managers = explode(',', $conf['manager']);
3617651d633SGuy Brand        $managers = array_unique($managers);
3627651d633SGuy Brand        $managers = array_map('trim', $managers);
3637651d633SGuy Brand        // prepare an array containing only true values for array_map call
3647651d633SGuy Brand        $alltrue = array_fill(0, count($managers), true);
3657651d633SGuy Brand        $managers = array_map('auth_nameencode', $managers, $alltrue);
3667651d633SGuy Brand        if(in_array($user, $managers)) return true;
367f8cc712eSAndreas Gohr    }
368f8cc712eSAndreas Gohr
36900ce12daSChris Smith    // check user's groups against superuser and manager
37000ce12daSChris Smith    if (!empty($groups)) {
37100ce12daSChris Smith
372f8cc712eSAndreas Gohr        //prepend groups with @ and nameencode
373f8cc712eSAndreas Gohr        $cnt = count($groups);
374f8cc712eSAndreas Gohr        for($i=0; $i<$cnt; $i++){
375f8cc712eSAndreas Gohr            $groups[$i] = '@'.auth_nameencode($groups[$i]);
376f8cc712eSAndreas Gohr        }
377f8cc712eSAndreas Gohr
378f8cc712eSAndreas Gohr        // check groups against superuser and manager
3797651d633SGuy Brand        foreach($superusers as $supu)
3807651d633SGuy Brand            if(in_array($supu, $groups)) return true;
381f8cc712eSAndreas Gohr        if(!$adminonly){
3827651d633SGuy Brand            foreach($managers as $mana)
3837651d633SGuy Brand                if(in_array($mana, $groups)) return true;
384f8cc712eSAndreas Gohr        }
38500ce12daSChris Smith    }
38600ce12daSChris Smith
387f8cc712eSAndreas Gohr    return false;
388f8cc712eSAndreas Gohr}
389f8cc712eSAndreas Gohr
390f8cc712eSAndreas Gohr/**
391f8cc712eSAndreas Gohr * Check if a user is admin
392f8cc712eSAndreas Gohr *
393f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
394f8cc712eSAndreas Gohr *
395f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
396f8cc712eSAndreas Gohr *
397f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
398f8cc712eSAndreas Gohr * @see auth_ismanager
399f8cc712eSAndreas Gohr */
400f8cc712eSAndreas Gohrfunction auth_isadmin($user=null,$groups=null){
401f8cc712eSAndreas Gohr    return auth_ismanager($user,$groups,true);
402f8cc712eSAndreas Gohr}
403f8cc712eSAndreas Gohr
404f8cc712eSAndreas Gohr/**
40515fae107Sandi * Convinience function for auth_aclcheck()
40615fae107Sandi *
40715fae107Sandi * This checks the permissions for the current user
40815fae107Sandi *
40915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
41015fae107Sandi *
4111698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
41215fae107Sandi * @return int          permission level
413f3f0262cSandi */
414f3f0262cSandifunction auth_quickaclcheck($id){
415f3f0262cSandi    global $conf;
416f3f0262cSandi    global $USERINFO;
417f3f0262cSandi    # if no ACL is used always return upload rights
418f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
419f3f0262cSandi    return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
420f3f0262cSandi}
421f3f0262cSandi
422f3f0262cSandi/**
423f3f0262cSandi * Returns the maximum rights a user has for
424f3f0262cSandi * the given ID or its namespace
42515fae107Sandi *
42615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
42715fae107Sandi *
4281698b983Smichael * @param  string  $id     page ID (needs to be resolved and cleaned)
42915fae107Sandi * @param  string  $user   Username
43015fae107Sandi * @param  array   $groups Array of groups the user is in
43115fae107Sandi * @return int             permission level
432f3f0262cSandi */
433f3f0262cSandifunction auth_aclcheck($id,$user,$groups){
434f3f0262cSandi    global $conf;
435f3f0262cSandi    global $AUTH_ACL;
436f3f0262cSandi
43785d03f68SAndreas Gohr    // if no ACL is used always return upload rights
438f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
439f3f0262cSandi
440074cf26bSandi    //make sure groups is an array
441074cf26bSandi    if(!is_array($groups)) $groups = array();
442074cf26bSandi
44385d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
44485d03f68SAndreas Gohr    if(auth_isadmin($user,$groups)) { return AUTH_ADMIN; }
44585d03f68SAndreas Gohr
44685d03f68SAndreas Gohr    $user = auth_nameencode($user);
44785d03f68SAndreas Gohr
4486c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
4492cd2db38Sandi    $cnt = count($groups);
4502cd2db38Sandi    for($i=0; $i<$cnt; $i++){
4516c2bb100SAndreas Gohr        $groups[$i] = '@'.auth_nameencode($groups[$i]);
45210a76f6fSfrank    }
45310a76f6fSfrank
454f3f0262cSandi    $ns    = getNS($id);
455f3f0262cSandi    $perm  = -1;
456f3f0262cSandi
45734aeb4afSAndreas Gohr    if($user || count($groups)){
458f3f0262cSandi        //add ALL group
459f3f0262cSandi        $groups[] = '@ALL';
460f3f0262cSandi        //add User
46134aeb4afSAndreas Gohr        if($user) $groups[] = $user;
462f3f0262cSandi        //build regexp
463f3f0262cSandi        $regexp   = join('|',$groups);
464f3f0262cSandi    }else{
465f3f0262cSandi        $regexp = '@ALL';
466f3f0262cSandi    }
467f3f0262cSandi
468f3f0262cSandi    //check exact match first
46942905504SAndreas Gohr    $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/',$AUTH_ACL);
470f3f0262cSandi    if(count($matches)){
471f3f0262cSandi        foreach($matches as $match){
472f3f0262cSandi            $match = preg_replace('/#.*$/','',$match); //ignore comments
473f3f0262cSandi            $acl   = preg_split('/\s+/',$match);
4748ef6b7caSandi            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
475f3f0262cSandi            if($acl[2] > $perm){
476f3f0262cSandi                $perm = $acl[2];
477f3f0262cSandi            }
478f3f0262cSandi        }
479f3f0262cSandi        if($perm > -1){
480f3f0262cSandi            //we had a match - return it
481f3f0262cSandi            return $perm;
482f3f0262cSandi        }
483f3f0262cSandi    }
484f3f0262cSandi
485f3f0262cSandi    //still here? do the namespace checks
486f3f0262cSandi    if($ns){
487f3f0262cSandi        $path = $ns.':\*';
488f3f0262cSandi    }else{
489f3f0262cSandi        $path = '\*'; //root document
490f3f0262cSandi    }
491f3f0262cSandi
492f3f0262cSandi    do{
493f3f0262cSandi        $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
494f3f0262cSandi        if(count($matches)){
495f3f0262cSandi            foreach($matches as $match){
496f3f0262cSandi                $match = preg_replace('/#.*$/','',$match); //ignore comments
497f3f0262cSandi                $acl   = preg_split('/\s+/',$match);
4988ef6b7caSandi                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
499f3f0262cSandi                if($acl[2] > $perm){
500f3f0262cSandi                    $perm = $acl[2];
501f3f0262cSandi                }
502f3f0262cSandi            }
503f3f0262cSandi            //we had a match - return it
504f3f0262cSandi            return $perm;
505f3f0262cSandi        }
506f3f0262cSandi
507f3f0262cSandi        //get next higher namespace
508f3f0262cSandi        $ns   = getNS($ns);
509f3f0262cSandi
510f3f0262cSandi        if($path != '\*'){
511f3f0262cSandi            $path = $ns.':\*';
512f3f0262cSandi            if($path == ':\*') $path = '\*';
513f3f0262cSandi        }else{
514f3f0262cSandi            //we did this already
515f3f0262cSandi            //looks like there is something wrong with the ACL
516f3f0262cSandi            //break here
517d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
518d5ce66f6SAndreas Gohr            return AUTH_NONE;
519f3f0262cSandi        }
520f3f0262cSandi    }while(1); //this should never loop endless
52152a5af8dSandi
52252a5af8dSandi    //still here? return no permissions
52352a5af8dSandi    return AUTH_NONE;
524f3f0262cSandi}
525f3f0262cSandi
526f3f0262cSandi/**
5276c2bb100SAndreas Gohr * Encode ASCII special chars
5286c2bb100SAndreas Gohr *
5296c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
5306c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
5316c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
5326c2bb100SAndreas Gohr * urlencoding!).
5336c2bb100SAndreas Gohr *
5346c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
5356c2bb100SAndreas Gohr *
5366c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
5376c2bb100SAndreas Gohr * @see rawurldecode()
5386c2bb100SAndreas Gohr */
539e838fc2eSAndreas Gohrfunction auth_nameencode($name,$skip_group=false){
540a424cd8eSchris    global $cache_authname;
541a424cd8eSchris    $cache =& $cache_authname;
54231784267SAndreas Gohr    $name  = (string) $name;
543a424cd8eSchris
544a424cd8eSchris    if (!isset($cache[$name][$skip_group])) {
545e838fc2eSAndreas Gohr        if($skip_group && $name{0} =='@'){
546a424cd8eSchris            $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
5471a9ae8e5SAndreas Gohr                    "'%'.dechex(ord(substr('\\1',-1)))",substr($name,1));
548e838fc2eSAndreas Gohr        }else{
549a424cd8eSchris            $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
5501a9ae8e5SAndreas Gohr                    "'%'.dechex(ord(substr('\\1',-1)))",$name);
551e838fc2eSAndreas Gohr        }
5526c2bb100SAndreas Gohr    }
5536c2bb100SAndreas Gohr
554a424cd8eSchris    return $cache[$name][$skip_group];
555a424cd8eSchris}
556a424cd8eSchris
5576c2bb100SAndreas Gohr/**
558f3f0262cSandi * Create a pronouncable password
559f3f0262cSandi *
56015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
56115fae107Sandi * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
56215fae107Sandi *
56315fae107Sandi * @return string  pronouncable password
564f3f0262cSandi */
565f3f0262cSandifunction auth_pwgen(){
566f3f0262cSandi    $pw = '';
567f3f0262cSandi    $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
568f3f0262cSandi    $v  = 'aeiou';              //vowels
569f3f0262cSandi    $a  = $c.$v;                //both
570f3f0262cSandi
571f3f0262cSandi    //use two syllables...
572f3f0262cSandi    for($i=0;$i < 2; $i++){
573f3f0262cSandi        $pw .= $c[rand(0, strlen($c)-1)];
574f3f0262cSandi        $pw .= $v[rand(0, strlen($v)-1)];
575f3f0262cSandi        $pw .= $a[rand(0, strlen($a)-1)];
576f3f0262cSandi    }
577f3f0262cSandi    //... and add a nice number
578f3f0262cSandi    $pw .= rand(10,99);
579f3f0262cSandi
580f3f0262cSandi    return $pw;
581f3f0262cSandi}
582f3f0262cSandi
583f3f0262cSandi/**
584f3f0262cSandi * Sends a password to the given user
585f3f0262cSandi *
58615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
58715fae107Sandi *
58815fae107Sandi * @return bool  true on success
589f3f0262cSandi */
590f3f0262cSandifunction auth_sendPassword($user,$password){
591f3f0262cSandi    global $conf;
592f3f0262cSandi    global $lang;
593cd52f92dSchris    global $auth;
594cd52f92dSchris
595f3f0262cSandi    $hdrs  = '';
596cd52f92dSchris    $userinfo = $auth->getUserData($user);
597f3f0262cSandi
59887ddda95Sandi    if(!$userinfo['mail']) return false;
599f3f0262cSandi
600f3f0262cSandi    $text = rawLocale('password');
601ed7b5f09Sandi    $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
60287ddda95Sandi    $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
603f3f0262cSandi    $text = str_replace('@LOGIN@',$user,$text);
604f3f0262cSandi    $text = str_replace('@PASSWORD@',$password,$text);
605f3f0262cSandi    $text = str_replace('@TITLE@',$conf['title'],$text);
606f3f0262cSandi
60744f669e9Sandi    return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
60844f669e9Sandi            $lang['regpwmail'],
60944f669e9Sandi            $text,
61044f669e9Sandi            $conf['mailfrom']);
611f3f0262cSandi}
612f3f0262cSandi
613f3f0262cSandi/**
61415fae107Sandi * Register a new user
615f3f0262cSandi *
61615fae107Sandi * This registers a new user - Data is read directly from $_POST
61715fae107Sandi *
61815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
61915fae107Sandi *
62015fae107Sandi * @return bool  true on success, false on any error
621f3f0262cSandi */
622f3f0262cSandifunction register(){
623f3f0262cSandi    global $lang;
624eb5d07e4Sjan    global $conf;
625cd52f92dSchris    global $auth;
626f3f0262cSandi
627f3f0262cSandi    if(!$_POST['save']) return false;
62882fd59b6SAndreas Gohr    if(!$auth->canDo('addUser')) return false;
629640145a5Sandi
630f3f0262cSandi    //clean username
631f3f0262cSandi    $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
632f3f0262cSandi    $_POST['login'] = cleanID($_POST['login']);
633f3f0262cSandi    //clean fullname and email
63454f0e6eaSAndreas Gohr    $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
63554f0e6eaSAndreas Gohr    $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
636f3f0262cSandi
637f3f0262cSandi    if( empty($_POST['login']) ||
638f3f0262cSandi        empty($_POST['fullname']) ||
639f3f0262cSandi        empty($_POST['email']) ){
640f3f0262cSandi        msg($lang['regmissing'],-1);
641f3f0262cSandi        return false;
642f3f0262cSandi    }
643f3f0262cSandi
644cab2716aSmatthias.grimm    if ($conf['autopasswd']) {
645cab2716aSmatthias.grimm        $pass = auth_pwgen();                // automatically generate password
646cab2716aSmatthias.grimm    } elseif (empty($_POST['pass']) ||
647cab2716aSmatthias.grimm            empty($_POST['passchk'])) {
648bf12ec81Sjan        msg($lang['regmissing'], -1);        // complain about missing passwords
649cab2716aSmatthias.grimm        return false;
650cab2716aSmatthias.grimm    } elseif ($_POST['pass'] != $_POST['passchk']) {
651bf12ec81Sjan        msg($lang['regbadpass'], -1);      // complain about misspelled passwords
652cab2716aSmatthias.grimm        return false;
653cab2716aSmatthias.grimm    } else {
654cab2716aSmatthias.grimm        $pass = $_POST['pass'];              // accept checked and valid password
655cab2716aSmatthias.grimm    }
656cab2716aSmatthias.grimm
657f3f0262cSandi    //check mail
65844f669e9Sandi    if(!mail_isvalid($_POST['email'])){
659f3f0262cSandi        msg($lang['regbadmail'],-1);
660f3f0262cSandi        return false;
661f3f0262cSandi    }
662f3f0262cSandi
663f3f0262cSandi    //okay try to create the user
6647d3c8d42SGabriel Birke    if(!$auth->triggerUserMod('create', array($_POST['login'],$pass,$_POST['fullname'],$_POST['email']))){
665f3f0262cSandi        msg($lang['reguexists'],-1);
666f3f0262cSandi        return false;
667f3f0262cSandi    }
668f3f0262cSandi
66902a498e7Schris    // create substitutions for use in notification email
67002a498e7Schris    $substitutions = array(
67102a498e7Schris            'NEWUSER' => $_POST['login'],
67202a498e7Schris            'NEWNAME' => $_POST['fullname'],
67302a498e7Schris            'NEWEMAIL' => $_POST['email'],
67402a498e7Schris            );
67502a498e7Schris
676cab2716aSmatthias.grimm    if (!$conf['autopasswd']) {
677cab2716aSmatthias.grimm        msg($lang['regsuccess2'],1);
67802a498e7Schris        notify('', 'register', '', $_POST['login'], false, $substitutions);
679cab2716aSmatthias.grimm        return true;
680cab2716aSmatthias.grimm    }
681cab2716aSmatthias.grimm
682cab2716aSmatthias.grimm    // autogenerated password? then send him the password
683f3f0262cSandi    if (auth_sendPassword($_POST['login'],$pass)){
684f3f0262cSandi        msg($lang['regsuccess'],1);
68502a498e7Schris        notify('', 'register', '', $_POST['login'], false, $substitutions);
686f3f0262cSandi        return true;
687f3f0262cSandi    }else{
688f3f0262cSandi        msg($lang['regmailfail'],-1);
689f3f0262cSandi        return false;
690f3f0262cSandi    }
691f3f0262cSandi}
692f3f0262cSandi
69310a76f6fSfrank/**
6948b06d178Schris * Update user profile
6958b06d178Schris *
6968b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
6978b06d178Schris */
6988b06d178Schrisfunction updateprofile() {
6998b06d178Schris    global $conf;
7008b06d178Schris    global $INFO;
7018b06d178Schris    global $lang;
702cd52f92dSchris    global $auth;
7038b06d178Schris
704bb4866bdSchris    if(empty($_POST['save'])) return false;
7051b2a85e8SAndreas Gohr    if(!checkSecurityToken()) return false;
7068b06d178Schris
70782fd59b6SAndreas Gohr    // should not be able to get here without Profile being possible...
70882fd59b6SAndreas Gohr    if(!$auth->canDo('Profile')) {
7098b06d178Schris        msg($lang['profna'],-1);
7108b06d178Schris        return false;
7118b06d178Schris    }
7128b06d178Schris
7138b06d178Schris    if ($_POST['newpass'] != $_POST['passchk']) {
7148b06d178Schris        msg($lang['regbadpass'], -1);      // complain about misspelled passwords
7158b06d178Schris        return false;
7168b06d178Schris    }
7178b06d178Schris
7188b06d178Schris    //clean fullname and email
71954f0e6eaSAndreas Gohr    $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
72054f0e6eaSAndreas Gohr    $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
7218b06d178Schris
7228b06d178Schris    if (empty($_POST['fullname']) || empty($_POST['email'])) {
7238b06d178Schris        msg($lang['profnoempty'],-1);
7248b06d178Schris        return false;
7258b06d178Schris    }
7268b06d178Schris
7278b06d178Schris    if (!mail_isvalid($_POST['email'])){
7288b06d178Schris        msg($lang['regbadmail'],-1);
7298b06d178Schris        return false;
7308b06d178Schris    }
7318b06d178Schris
7324c21b7eeSAndreas Gohr    if ($_POST['fullname'] != $INFO['userinfo']['name'] && $auth->canDo('modName')) $changes['name'] = $_POST['fullname'];
7334c21b7eeSAndreas Gohr    if ($_POST['email'] != $INFO['userinfo']['mail'] && $auth->canDo('modMail')) $changes['mail'] = $_POST['email'];
734cf626a62SAndreas Gohr    if (!empty($_POST['newpass']) && $auth->canDo('modPass')) $changes['pass'] = $_POST['newpass'];
7354c21b7eeSAndreas Gohr
7368b06d178Schris    if (!count($changes)) {
7378b06d178Schris        msg($lang['profnochange'], -1);
7388b06d178Schris        return false;
7398b06d178Schris    }
7408b06d178Schris
7418b06d178Schris    if ($conf['profileconfirm']) {
742df466c7aSAndreas Gohr        if (!$auth->checkPass($_SERVER['REMOTE_USER'], $_POST['oldpass'])) {
7438b06d178Schris            msg($lang['badlogin'],-1);
7448b06d178Schris            return false;
7458b06d178Schris        }
7468b06d178Schris    }
7478b06d178Schris
748a0b5b007SChris Smith    if ($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
749a0b5b007SChris Smith        // update cookie and session with the changed data
750a0b5b007SChris Smith        $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
7514b7f9e70STom N Harris        list($user,$sticky,$pass) = explode('|',$cookie,3);
752a0b5b007SChris Smith        if ($changes['pass']) $pass = PMA_blowfish_encrypt($changes['pass'],auth_cookiesalt());
753a0b5b007SChris Smith
754a0b5b007SChris Smith        auth_setCookie($_SERVER['REMOTE_USER'],$pass,(bool)$sticky);
75525b2a98cSMichael Klier        return true;
756a0b5b007SChris Smith    }
7578b06d178Schris}
7588b06d178Schris
7598b06d178Schris/**
7608b06d178Schris * Send a  new password
7618b06d178Schris *
7621d5856cfSAndreas Gohr * This function handles both phases of the password reset:
7631d5856cfSAndreas Gohr *
7641d5856cfSAndreas Gohr *   - handling the first request of password reset
7651d5856cfSAndreas Gohr *   - validating the password reset auth token
7661d5856cfSAndreas Gohr *
7678b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
7688b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
7691d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
7708b06d178Schris *
7718b06d178Schris * @return bool true on success, false on any error
7728b06d178Schris */
7738b06d178Schrisfunction act_resendpwd(){
7748b06d178Schris    global $lang;
7758b06d178Schris    global $conf;
776cd52f92dSchris    global $auth;
7778b06d178Schris
778409d7af7SAndreas Gohr    if(!actionOK('resendpwd')) return false;
7798b06d178Schris
78082fd59b6SAndreas Gohr    // should not be able to get here without modPass being possible...
78182fd59b6SAndreas Gohr    if(!$auth->canDo('modPass')) {
7828b06d178Schris        msg($lang['resendna'],-1);
7838b06d178Schris        return false;
7848b06d178Schris    }
7858b06d178Schris
7861d5856cfSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
7878b06d178Schris
7881d5856cfSAndreas Gohr    if($token){
7891d5856cfSAndreas Gohr        // we're in token phase
7901d5856cfSAndreas Gohr
7911d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
7921d5856cfSAndreas Gohr        if(!@file_exists($tfile)){
7931d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'],-1);
7941d5856cfSAndreas Gohr            return false;
7951d5856cfSAndreas Gohr        }
7961d5856cfSAndreas Gohr        $user = io_readfile($tfile);
7971d5856cfSAndreas Gohr        @unlink($tfile);
798cd52f92dSchris        $userinfo = $auth->getUserData($user);
7998b06d178Schris        if(!$userinfo['mail']) {
8008b06d178Schris            msg($lang['resendpwdnouser'], -1);
8018b06d178Schris            return false;
8028b06d178Schris        }
8038b06d178Schris
8048b06d178Schris        $pass = auth_pwgen();
8057d3c8d42SGabriel Birke        if (!$auth->triggerUserMod('modify', array($user,array('pass' => $pass)))) {
8068b06d178Schris            msg('error modifying user data',-1);
8078b06d178Schris            return false;
8088b06d178Schris        }
8098b06d178Schris
8108b06d178Schris        if (auth_sendPassword($user,$pass)) {
8118b06d178Schris            msg($lang['resendpwdsuccess'],1);
8128b06d178Schris        } else {
8138b06d178Schris            msg($lang['regmailfail'],-1);
8148b06d178Schris        }
8158b06d178Schris        return true;
8161d5856cfSAndreas Gohr
8171d5856cfSAndreas Gohr    } else {
8181d5856cfSAndreas Gohr        // we're in request phase
8191d5856cfSAndreas Gohr
8201d5856cfSAndreas Gohr        if(!$_POST['save']) return false;
8211d5856cfSAndreas Gohr
8221d5856cfSAndreas Gohr        if (empty($_POST['login'])) {
8231d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
8241d5856cfSAndreas Gohr            return false;
8251d5856cfSAndreas Gohr        } else {
82616470b1dSchris            $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
82716470b1dSchris            $user = cleanID($_POST['login']);
8281d5856cfSAndreas Gohr        }
8291d5856cfSAndreas Gohr
8301d5856cfSAndreas Gohr        $userinfo = $auth->getUserData($user);
8311d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
8321d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
8331d5856cfSAndreas Gohr            return false;
8341d5856cfSAndreas Gohr        }
8351d5856cfSAndreas Gohr
8361d5856cfSAndreas Gohr        // generate auth token
8371d5856cfSAndreas Gohr        $token = md5(auth_cookiesalt().$user); //secret but user based
8381d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
8391d5856cfSAndreas Gohr        $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
8401d5856cfSAndreas Gohr
8411d5856cfSAndreas Gohr        io_saveFile($tfile,$user);
8421d5856cfSAndreas Gohr
8431d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
8441d5856cfSAndreas Gohr        $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
8451d5856cfSAndreas Gohr        $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
8461d5856cfSAndreas Gohr        $text = str_replace('@LOGIN@',$user,$text);
8471d5856cfSAndreas Gohr        $text = str_replace('@TITLE@',$conf['title'],$text);
8481d5856cfSAndreas Gohr        $text = str_replace('@CONFIRM@',$url,$text);
8491d5856cfSAndreas Gohr
8501d5856cfSAndreas Gohr        if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
8511d5856cfSAndreas Gohr                     $lang['regpwmail'],
8521d5856cfSAndreas Gohr                     $text,
8531d5856cfSAndreas Gohr                     $conf['mailfrom'])){
8541d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'],1);
8551d5856cfSAndreas Gohr        }else{
8561d5856cfSAndreas Gohr            msg($lang['regmailfail'],-1);
8571d5856cfSAndreas Gohr        }
8581d5856cfSAndreas Gohr        return true;
8591d5856cfSAndreas Gohr    }
8601d5856cfSAndreas Gohr
8611d5856cfSAndreas Gohr    return false; // never reached
8628b06d178Schris}
8638b06d178Schris
8648b06d178Schris/**
865b0855b11Sandi * Encrypts a password using the given method and salt
866b0855b11Sandi *
867b0855b11Sandi * If the selected method needs a salt and none was given, a random one
868b0855b11Sandi * is chosen.
869b0855b11Sandi *
870b0855b11Sandi * The following methods are understood:
871b0855b11Sandi *
872b0855b11Sandi *   smd5  - Salted MD5 hashing
873577c7cdaSAndreas Gohr *   apr1  - Apache salted MD5 hashing
874b0855b11Sandi *   md5   - Simple MD5 hashing
875b0855b11Sandi *   sha1  - SHA1 hashing
876b0855b11Sandi *   ssha  - Salted SHA1 hashing
877d7be6245Sandi *   crypt - Unix crypt
878d7be6245Sandi *   mysql - MySQL password (old method)
879d7be6245Sandi *   my411 - MySQL 4.1.1 password
88043ee7484SAndreas Gohr *   kmd5  - Salted MD5 hashing as used by UNB
881b0855b11Sandi *
882b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
883b0855b11Sandi * @return  string  The crypted password
884b0855b11Sandi */
885577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear,$method='',$salt=null){
886b0855b11Sandi    global $conf;
887b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
88810a76f6fSfrank
889b0855b11Sandi    //prepare a salt
890577c7cdaSAndreas Gohr    if(is_null($salt)) $salt = md5(uniqid(rand(), true));
891b0855b11Sandi
892b0855b11Sandi    switch(strtolower($method)){
893b0855b11Sandi        case 'smd5':
894056cb2ccSChris Smith            if(defined('CRYPT_MD5') && CRYPT_MD5) return crypt($clear,'$1$'.substr($salt,0,8).'$');
895577c7cdaSAndreas Gohr            // when crypt can't handle SMD5, falls through to pure PHP implementation
896577c7cdaSAndreas Gohr            $magic = '1';
897577c7cdaSAndreas Gohr        case 'apr1':
898577c7cdaSAndreas Gohr            //from http://de.php.net/manual/en/function.crypt.php#73619 comment by <mikey_nich at hotmail dot com>
899577c7cdaSAndreas Gohr            if(!$magic) $magic = 'apr1';
900577c7cdaSAndreas Gohr            $salt = substr($salt,0,8);
901577c7cdaSAndreas Gohr            $len = strlen($clear);
902577c7cdaSAndreas Gohr            $text = $clear.'$'.$magic.'$'.$salt;
903577c7cdaSAndreas Gohr            $bin = pack("H32", md5($clear.$salt.$clear));
904db959ae3SAndreas Gohr            for($i = $len; $i > 0; $i -= 16) {
905db959ae3SAndreas Gohr                $text .= substr($bin, 0, min(16, $i));
906db959ae3SAndreas Gohr            }
907db959ae3SAndreas Gohr            for($i = $len; $i > 0; $i >>= 1) {
908db959ae3SAndreas Gohr                $text .= ($i & 1) ? chr(0) : $clear{0};
909db959ae3SAndreas Gohr            }
910577c7cdaSAndreas Gohr            $bin = pack("H32", md5($text));
911577c7cdaSAndreas Gohr            for($i = 0; $i < 1000; $i++) {
912577c7cdaSAndreas Gohr                $new = ($i & 1) ? $clear : $bin;
913577c7cdaSAndreas Gohr                if ($i % 3) $new .= $salt;
914577c7cdaSAndreas Gohr                if ($i % 7) $new .= $clear;
915577c7cdaSAndreas Gohr                $new .= ($i & 1) ? $bin : $clear;
916577c7cdaSAndreas Gohr                $bin = pack("H32", md5($new));
917577c7cdaSAndreas Gohr            }
918577c7cdaSAndreas Gohr            $tmp = '';
919577c7cdaSAndreas Gohr            for ($i = 0; $i < 5; $i++) {
920577c7cdaSAndreas Gohr                $k = $i + 6;
921577c7cdaSAndreas Gohr                $j = $i + 12;
922577c7cdaSAndreas Gohr                if ($j == 16) $j = 5;
923577c7cdaSAndreas Gohr                $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
924577c7cdaSAndreas Gohr            }
925577c7cdaSAndreas Gohr            $tmp = chr(0).chr(0).$bin[11].$tmp;
926577c7cdaSAndreas Gohr            $tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
927577c7cdaSAndreas Gohr                    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
928577c7cdaSAndreas Gohr                    "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
929577c7cdaSAndreas Gohr            return '$'.$magic.'$'.$salt.'$'.$tmp;
930b0855b11Sandi        case 'md5':
931b0855b11Sandi            return md5($clear);
932b0855b11Sandi        case 'sha1':
933b0855b11Sandi            return sha1($clear);
934b0855b11Sandi        case 'ssha':
935b0855b11Sandi            $salt=substr($salt,0,4);
936d6e54e02Smatthiasgrimm            return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
937b0855b11Sandi        case 'crypt':
938b0855b11Sandi            return crypt($clear,substr($salt,0,2));
939d7be6245Sandi        case 'mysql':
940d7be6245Sandi            //from http://www.php.net/mysql comment by <soren at byu dot edu>
941d7be6245Sandi            $nr=0x50305735;
942d7be6245Sandi            $nr2=0x12345671;
943d7be6245Sandi            $add=7;
944d7be6245Sandi            $charArr = preg_split("//", $clear);
945d7be6245Sandi            foreach ($charArr as $char) {
946d7be6245Sandi                if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
947d7be6245Sandi                $charVal = ord($char);
948d7be6245Sandi                $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
949d7be6245Sandi                $nr2 += ($nr2 << 8) ^ $nr;
950d7be6245Sandi                $add += $charVal;
951d7be6245Sandi            }
952d7be6245Sandi            return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
953d7be6245Sandi        case 'my411':
954d7be6245Sandi            return '*'.sha1(pack("H*", sha1($clear)));
95543ee7484SAndreas Gohr        case 'kmd5':
95643ee7484SAndreas Gohr            $key = substr($salt, 16, 2);
95743ee7484SAndreas Gohr            $hash1 = strtolower(md5($key . md5($clear)));
95843ee7484SAndreas Gohr            $hash2 = substr($hash1, 0, 16) . $key . substr($hash1, 16);
95943ee7484SAndreas Gohr            return $hash2;
960b0855b11Sandi        default:
961b0855b11Sandi            msg("Unsupported crypt method $method",-1);
962b0855b11Sandi    }
963b0855b11Sandi}
964b0855b11Sandi
965b0855b11Sandi/**
966b0855b11Sandi * Verifies a cleartext password against a crypted hash
967b0855b11Sandi *
968b0855b11Sandi * The method and salt used for the crypted hash is determined automatically
969b0855b11Sandi * then the clear text password is crypted using the same method. If both hashs
970b0855b11Sandi * match true is is returned else false
971b0855b11Sandi *
972b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
973b0855b11Sandi * @return  bool
974b0855b11Sandi */
975b0855b11Sandifunction auth_verifyPassword($clear,$crypt){
976b0855b11Sandi    $method='';
977b0855b11Sandi    $salt='';
978b0855b11Sandi
979b0855b11Sandi    //determine the used method and salt
980d7be6245Sandi    $len = strlen($crypt);
981577c7cdaSAndreas Gohr    if(preg_match('/^\$1\$([^\$]{0,8})\$/',$crypt,$m)){
982b0855b11Sandi        $method = 'smd5';
983577c7cdaSAndreas Gohr        $salt   = $m[1];
984577c7cdaSAndreas Gohr    }elseif(preg_match('/^\$apr1\$([^\$]{0,8})\$/',$crypt,$m)){
985577c7cdaSAndreas Gohr        $method = 'apr1';
986577c7cdaSAndreas Gohr        $salt   = $m[1];
987b0855b11Sandi    }elseif(substr($crypt,0,6) == '{SSHA}'){
988b0855b11Sandi        $method = 'ssha';
989b0855b11Sandi        $salt   = substr(base64_decode(substr($crypt, 6)),20);
990d7be6245Sandi    }elseif($len == 32){
991b0855b11Sandi        $method = 'md5';
992d7be6245Sandi    }elseif($len == 40){
993b0855b11Sandi        $method = 'sha1';
994d7be6245Sandi    }elseif($len == 16){
995d7be6245Sandi        $method = 'mysql';
996d7be6245Sandi    }elseif($len == 41 && $crypt[0] == '*'){
997d7be6245Sandi        $method = 'my411';
99843ee7484SAndreas Gohr    }elseif($len == 34){
99943ee7484SAndreas Gohr        $method = 'kmd5';
100043ee7484SAndreas Gohr        $salt   = $crypt;
1001b0855b11Sandi    }else{
1002b0855b11Sandi        $method = 'crypt';
1003b0855b11Sandi        $salt   = substr($crypt,0,2);
1004b0855b11Sandi    }
1005b0855b11Sandi
1006b0855b11Sandi    //crypt and compare
1007b0855b11Sandi    if(auth_cryptPassword($clear,$method,$salt) === $crypt){
1008b0855b11Sandi        return true;
1009b0855b11Sandi    }
1010b0855b11Sandi    return false;
1011b0855b11Sandi}
1012340756e4Sandi
1013a0b5b007SChris Smith/**
1014a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1015a0b5b007SChris Smith *
1016a0b5b007SChris Smith * @param string  $user       username
1017a0b5b007SChris Smith * @param string  $pass       encrypted password
1018a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1019a0b5b007SChris Smith */
1020a0b5b007SChris Smithfunction auth_setCookie($user,$pass,$sticky) {
1021a0b5b007SChris Smith    global $conf;
1022a0b5b007SChris Smith    global $auth;
102379d00841SOliver Geisen    global $USERINFO;
1024a0b5b007SChris Smith
1025a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1026a0b5b007SChris Smith
1027a0b5b007SChris Smith    // set cookie
1028645c0a36SAndreas Gohr    $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
1029c66972f2SAdrian Lang    $time = $sticky ? (time()+60*60*24*365) : 0; //one year
1030a0b5b007SChris Smith    if (version_compare(PHP_VERSION, '5.2.0', '>')) {
1031a0b5b007SChris Smith        setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true);
1032a0b5b007SChris Smith    }else{
1033a0b5b007SChris Smith        setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()));
1034a0b5b007SChris Smith    }
1035a0b5b007SChris Smith    // set session
1036a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1037a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['pass'] = $pass;
1038a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1039a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1040a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1041a0b5b007SChris Smith}
1042a0b5b007SChris Smith
1043645c0a36SAndreas Gohr/**
1044645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1045645c0a36SAndreas Gohr *
1046645c0a36SAndreas Gohr * @returns array
1047645c0a36SAndreas Gohr */
1048645c0a36SAndreas Gohrfunction auth_getCookie(){
1049c66972f2SAdrian Lang    if (!isset($_COOKIE[DOKU_COOKIE])) {
1050c66972f2SAdrian Lang        return array(null, null, null);
1051c66972f2SAdrian Lang    }
1052645c0a36SAndreas Gohr    list($user,$sticky,$pass) = explode('|',$_COOKIE[DOKU_COOKIE],3);
1053645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1054645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1055645c0a36SAndreas Gohr    $user   = base64_decode($user);
1056645c0a36SAndreas Gohr    return array($user,$sticky,$pass);
1057645c0a36SAndreas Gohr}
1058645c0a36SAndreas Gohr
1059340756e4Sandi//Setup VIM: ex: et ts=2 enc=utf-8 :
1060