xref: /dokuwiki/inc/auth.php (revision 75c93b7798bed5fafb8b75066adce3af14ebb524)
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
106*75c93b77SAndreas Gohr    $AUTH_ACL = auth_loadACL();
107*75c93b77SAndreas Gohr}
108*75c93b77SAndreas Gohr
109*75c93b77SAndreas Gohr/**
110*75c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards
111*75c93b77SAndreas Gohr *
112*75c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
113*75c93b77SAndreas Gohr * @returns array
114*75c93b77SAndreas Gohr */
115*75c93b77SAndreas Gohrfunction auth_loadACL(){
116*75c93b77SAndreas Gohr    global $config_cascade;
117*75c93b77SAndreas Gohr
118*75c93b77SAndreas Gohr    if(!is_readable($config_cascade['acl']['default'])) return array();
119*75c93b77SAndreas Gohr
120*75c93b77SAndreas Gohr    $acl = file($config_cascade['acl']['default']);
121*75c93b77SAndreas Gohr
122191bb90aSAndreas Gohr    //support user wildcard
123f8cc3354SGuy Brand    if(isset($_SERVER['REMOTE_USER'])){
124*75c93b77SAndreas Gohr        $len = count($acl);
125*75c93b77SAndreas Gohr        for($i=0; $i<$len; $i++){
126*75c93b77SAndreas Gohr            if($acl[$i]{0} == '#') continue;
127*75c93b77SAndreas Gohr            list($id,$rest) = preg_split('/\s+/',$acl[$i],2);
128*75c93b77SAndreas Gohr            $id   = str_replace('%USER%',cleanID($_SERVER['REMOTE_USER']),$id);
129*75c93b77SAndreas Gohr            $rest = str_replace('%USER%',auth_nameencode($_SERVER['REMOTE_USER']),$rest);
130*75c93b77SAndreas Gohr            $acl[$i] = "$id\t$rest";
131a8fe108bSGuy Brand        }
13211799630Sandi    }
133*75c93b77SAndreas Gohr    return $acl;
134f3f0262cSandi}
135f3f0262cSandi
136b5ee21aaSAdrian Langfunction auth_login_wrapper($evdata) {
137b5ee21aaSAdrian Lang    return auth_login($evdata['user'],
138b5ee21aaSAdrian Lang                      $evdata['password'],
139b5ee21aaSAdrian Lang                      $evdata['sticky'],
140b5ee21aaSAdrian Lang                      $evdata['silent']);
141b5ee21aaSAdrian Lang}
142b5ee21aaSAdrian Lang
143f3f0262cSandi/**
144f3f0262cSandi * This tries to login the user based on the sent auth credentials
145f3f0262cSandi *
146f3f0262cSandi * The authentication works like this: if a username was given
14715fae107Sandi * a new login is assumed and user/password are checked. If they
14815fae107Sandi * are correct the password is encrypted with blowfish and stored
14915fae107Sandi * together with the username in a cookie - the same info is stored
15015fae107Sandi * in the session, too. Additonally a browserID is stored in the
15115fae107Sandi * session.
15215fae107Sandi *
15315fae107Sandi * If no username was given the cookie is checked: if the username,
15415fae107Sandi * crypted password and browserID match between session and cookie
15515fae107Sandi * no further testing is done and the user is accepted
15615fae107Sandi *
15715fae107Sandi * If a cookie was found but no session info was availabe the
158136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
15915fae107Sandi * together with username rechecked by calling this function again.
160f3f0262cSandi *
161f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
162f3f0262cSandi * are set.
16315fae107Sandi *
16415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
16515fae107Sandi *
16615fae107Sandi * @param   string  $user    Username
16715fae107Sandi * @param   string  $pass    Cleartext Password
16815fae107Sandi * @param   bool    $sticky  Cookie should not expire
169f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
17015fae107Sandi * @return  bool             true on successful auth
171f3f0262cSandi */
172f112c2faSAndreas Gohrfunction auth_login($user,$pass,$sticky=false,$silent=false){
173f3f0262cSandi    global $USERINFO;
174f3f0262cSandi    global $conf;
175f3f0262cSandi    global $lang;
176cd52f92dSchris    global $auth;
177132bdbfeSandi    $sticky ? $sticky = true : $sticky = false; //sanity check
178f3f0262cSandi
179beca106aSAdrian Lang    if (!$auth) return false;
180beca106aSAdrian Lang
181bbbd6568SAndreas Gohr    if(!empty($user)){
182132bdbfeSandi        //usual login
183cd52f92dSchris        if ($auth->checkPass($user,$pass)){
184132bdbfeSandi            // make logininfo globally available
185f3f0262cSandi            $_SERVER['REMOTE_USER'] = $user;
186a0b5b007SChris Smith            auth_setCookie($user,PMA_blowfish_encrypt($pass,auth_cookiesalt()),$sticky);
187132bdbfeSandi            return true;
188f3f0262cSandi        }else{
189f3f0262cSandi            //invalid credentials - log off
190f112c2faSAndreas Gohr            if(!$silent) msg($lang['badlogin'],-1);
191f3f0262cSandi            auth_logoff();
192132bdbfeSandi            return false;
193f3f0262cSandi        }
194f3f0262cSandi    }else{
195132bdbfeSandi        // read cookie information
196645c0a36SAndreas Gohr        list($user,$sticky,$pass) = auth_getCookie();
197132bdbfeSandi        // get session info
198e71ce681SAndreas Gohr        $session = $_SESSION[DOKU_COOKIE]['auth'];
199132bdbfeSandi        if($user && $pass){
200132bdbfeSandi            // we got a cookie - see if we can trust it
201132bdbfeSandi            if(isset($session) &&
2027172dbc0SAndreas Gohr                    $auth->useSessionCache($user) &&
2034c989037SChris Smith                    ($session['time'] >= time()-$conf['auth_security_timeout']) &&
204132bdbfeSandi                    ($session['user'] == $user) &&
205132bdbfeSandi                    ($session['pass'] == $pass) &&  //still crypted
206132bdbfeSandi                    ($session['buid'] == auth_browseruid()) ){
207132bdbfeSandi                // he has session, cookie and browser right - let him in
208132bdbfeSandi                $_SERVER['REMOTE_USER'] = $user;
209132bdbfeSandi                $USERINFO = $session['info']; //FIXME move all references to session
210132bdbfeSandi                return true;
211132bdbfeSandi            }
212f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
213132bdbfeSandi            $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
214f112c2faSAndreas Gohr            return auth_login($user,$pass,$sticky,true);
215132bdbfeSandi        }
216132bdbfeSandi    }
217f3f0262cSandi    //just to be sure
218883179a4SAndreas Gohr    auth_logoff(true);
219132bdbfeSandi    return false;
220f3f0262cSandi}
221132bdbfeSandi
222132bdbfeSandi/**
223f13fa892SAndreas Gohr * Checks if a given authentication token was stored in the session
224f13fa892SAndreas Gohr *
225f13fa892SAndreas Gohr * Will setup authentication data using data from the session if the
226f13fa892SAndreas Gohr * token is correct. Will exit with a 401 Status if not.
227f13fa892SAndreas Gohr *
228f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
229f13fa892SAndreas Gohr * @param  string $token The authentication token
230f13fa892SAndreas Gohr * @return boolean true (or will exit on failure)
231f13fa892SAndreas Gohr */
232f13fa892SAndreas Gohrfunction auth_validateToken($token){
233f13fa892SAndreas Gohr    if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']){
234f13fa892SAndreas Gohr        // bad token
235f13fa892SAndreas Gohr        header("HTTP/1.0 401 Unauthorized");
236f13fa892SAndreas Gohr        print 'Invalid auth token - maybe the session timed out';
237f13fa892SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
238f13fa892SAndreas Gohr        exit;
239f13fa892SAndreas Gohr    }
240f13fa892SAndreas Gohr    // still here? trust the session data
241f13fa892SAndreas Gohr    global $USERINFO;
242f13fa892SAndreas Gohr    $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
243f13fa892SAndreas Gohr    $USERINFO = $_SESSION[DOKU_COOKIE]['auth']['info'];
244f13fa892SAndreas Gohr    return true;
245f13fa892SAndreas Gohr}
246f13fa892SAndreas Gohr
247f13fa892SAndreas Gohr/**
248f13fa892SAndreas Gohr * Create an auth token and store it in the session
249f13fa892SAndreas Gohr *
250f13fa892SAndreas Gohr * NOTE: this is completely unrelated to the getSecurityToken() function
251f13fa892SAndreas Gohr *
252f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
253f13fa892SAndreas Gohr * @return string The auth token
254f13fa892SAndreas Gohr */
255f13fa892SAndreas Gohrfunction auth_createToken(){
256f13fa892SAndreas Gohr    $token = md5(mt_rand());
25709c2d803SAndreas Gohr    @session_start(); // reopen the session if needed
258f13fa892SAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
25909c2d803SAndreas Gohr    session_write_close();
260f13fa892SAndreas Gohr    return $token;
261f13fa892SAndreas Gohr}
262f13fa892SAndreas Gohr
263f13fa892SAndreas Gohr/**
264136ce040Sandi * Builds a pseudo UID from browser and IP data
265132bdbfeSandi *
266132bdbfeSandi * This is neither unique nor unfakable - still it adds some
267136ce040Sandi * security. Using the first part of the IP makes sure
268136ce040Sandi * proxy farms like AOLs are stil okay.
26915fae107Sandi *
27015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
27115fae107Sandi *
27215fae107Sandi * @return  string  a MD5 sum of various browser headers
273132bdbfeSandi */
274132bdbfeSandifunction auth_browseruid(){
2752f9daf16SAndreas Gohr    $ip   = clientIP(true);
276132bdbfeSandi    $uid  = '';
277132bdbfeSandi    $uid .= $_SERVER['HTTP_USER_AGENT'];
278132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
279132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
280132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
2812f9daf16SAndreas Gohr    $uid .= substr($ip,0,strpos($ip,'.'));
282132bdbfeSandi    return md5($uid);
283132bdbfeSandi}
284132bdbfeSandi
285132bdbfeSandi/**
286132bdbfeSandi * Creates a random key to encrypt the password in cookies
28715fae107Sandi *
28815fae107Sandi * This function tries to read the password for encrypting
28998407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
29015fae107Sandi * if no such file is found a random key is created and
29115fae107Sandi * and stored in this file.
29215fae107Sandi *
29315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
29415fae107Sandi *
29515fae107Sandi * @return  string
296132bdbfeSandi */
297132bdbfeSandifunction auth_cookiesalt(){
298132bdbfeSandi    global $conf;
29998407a7aSandi    $file = $conf['metadir'].'/_htcookiesalt';
300132bdbfeSandi    $salt = io_readFile($file);
301132bdbfeSandi    if(empty($salt)){
302132bdbfeSandi        $salt = uniqid(rand(),true);
303132bdbfeSandi        io_saveFile($file,$salt);
304132bdbfeSandi    }
305132bdbfeSandi    return $salt;
306f3f0262cSandi}
307f3f0262cSandi
308f3f0262cSandi/**
309883179a4SAndreas Gohr * Log out the current user
310883179a4SAndreas Gohr *
311f3f0262cSandi * This clears all authentication data and thus log the user
312883179a4SAndreas Gohr * off. It also clears session data.
31315fae107Sandi *
31415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
315883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
316f3f0262cSandi */
317883179a4SAndreas Gohrfunction auth_logoff($keepbc=false){
318f3f0262cSandi    global $conf;
319f3f0262cSandi    global $USERINFO;
3208b06d178Schris    global $INFO, $ID;
3215298a619SAndreas Gohr    global $auth;
32237065e65Sandi
323d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
324e9621d07SAndreas Gohr    @session_start();
325e9621d07SAndreas Gohr
326e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
327e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
328e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
329e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
330e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
331e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
332883179a4SAndreas Gohr    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
333e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
33437065e65Sandi    if(isset($_SERVER['REMOTE_USER']))
335f3f0262cSandi        unset($_SERVER['REMOTE_USER']);
336132bdbfeSandi    $USERINFO=null; //FIXME
337f5c6743cSAndreas Gohr
338f5c6743cSAndreas Gohr    if (version_compare(PHP_VERSION, '5.2.0', '>')) {
33985c6f7d0SAndreas Gohr        setcookie(DOKU_COOKIE,'',time()-600000,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true);
340f5c6743cSAndreas Gohr    }else{
34185c6f7d0SAndreas Gohr        setcookie(DOKU_COOKIE,'',time()-600000,DOKU_REL,'',($conf['securecookie'] && is_ssl()));
342f5c6743cSAndreas Gohr    }
3435298a619SAndreas Gohr
344880f62faSAndreas Gohr    if($auth) $auth->logOff();
345f3f0262cSandi}
346f3f0262cSandi
347f3f0262cSandi/**
348f8cc712eSAndreas Gohr * Check if a user is a manager
349f8cc712eSAndreas Gohr *
350f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
351f8cc712eSAndreas Gohr * user.
352f8cc712eSAndreas Gohr *
353f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
354f8cc712eSAndreas Gohr *
355f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
356f8cc712eSAndreas Gohr * @see    auth_isadmin
357f8cc712eSAndreas Gohr * @param  string user      - Username
358f8cc712eSAndreas Gohr * @param  array  groups    - List of groups the user is in
359f8cc712eSAndreas Gohr * @param  bool   adminonly - when true checks if user is admin
360f8cc712eSAndreas Gohr */
361f8cc712eSAndreas Gohrfunction auth_ismanager($user=null,$groups=null,$adminonly=false){
362f8cc712eSAndreas Gohr    global $conf;
363f8cc712eSAndreas Gohr    global $USERINFO;
364d752aedeSAndreas Gohr    global $auth;
365f8cc712eSAndreas Gohr
366beca106aSAdrian Lang    if (!$auth) return false;
367c66972f2SAdrian Lang    if(is_null($user)) {
368c66972f2SAdrian Lang        if (!isset($_SERVER['REMOTE_USER'])) {
369c66972f2SAdrian Lang            return false;
370c66972f2SAdrian Lang        } else {
371c66972f2SAdrian Lang            $user = $_SERVER['REMOTE_USER'];
372c66972f2SAdrian Lang        }
373c66972f2SAdrian Lang    }
374a6bc56d0SAndreas Gohr    $user = trim($auth->cleanUser($user));
375a6bc56d0SAndreas Gohr    if($user === '') return false;
37690583e9fSAndreas Gohr    if(is_null($groups)) $groups = (array) $USERINFO['grps'];
377d752aedeSAndreas Gohr    $groups = array_map(array($auth,'cleanGroup'),$groups);
378f8cc712eSAndreas Gohr    $user   = auth_nameencode($user);
379f8cc712eSAndreas Gohr
380f8cc712eSAndreas Gohr    // check username against superuser and manager
3817651d633SGuy Brand    $superusers = explode(',', $conf['superuser']);
3827651d633SGuy Brand    $superusers = array_unique($superusers);
3837651d633SGuy Brand    $superusers = array_map('trim', $superusers);
384a6bc56d0SAndreas Gohr    $superusers = array_filter($superusers);
3857651d633SGuy Brand    // prepare an array containing only true values for array_map call
3867651d633SGuy Brand    $alltrue = array_fill(0, count($superusers), true);
3877651d633SGuy Brand    $superusers = array_map('auth_nameencode', $superusers, $alltrue);
388e259aa79SAndreas Gohr
389e259aa79SAndreas Gohr    // case insensitive?
390e259aa79SAndreas Gohr    if(!$auth->isCaseSensitive()){
391e259aa79SAndreas Gohr        $superusers = array_map('utf8_strtolower',$superusers);
392e259aa79SAndreas Gohr        $user       = utf8_strtolower($user);
393e259aa79SAndreas Gohr    }
394e259aa79SAndreas Gohr
395e259aa79SAndreas Gohr    // check user match
3967651d633SGuy Brand    if(in_array($user, $superusers)) return true;
3977651d633SGuy Brand
398e259aa79SAndreas Gohr    // check managers
399f8cc712eSAndreas Gohr    if(!$adminonly){
4007651d633SGuy Brand        $managers = explode(',', $conf['manager']);
4017651d633SGuy Brand        $managers = array_unique($managers);
4027651d633SGuy Brand        $managers = array_map('trim', $managers);
403a6bc56d0SAndreas Gohr        $managers = array_filter($managers);
4047651d633SGuy Brand        // prepare an array containing only true values for array_map call
4057651d633SGuy Brand        $alltrue = array_fill(0, count($managers), true);
4067651d633SGuy Brand        $managers = array_map('auth_nameencode', $managers, $alltrue);
407e259aa79SAndreas Gohr        if(!$auth->isCaseSensitive()) $managers = array_map('utf8_strtolower',$managers);
4087651d633SGuy Brand        if(in_array($user, $managers)) return true;
409f8cc712eSAndreas Gohr    }
410f8cc712eSAndreas Gohr
41100ce12daSChris Smith    // check user's groups against superuser and manager
41200ce12daSChris Smith    if (!empty($groups)) {
41300ce12daSChris Smith
414f8cc712eSAndreas Gohr        //prepend groups with @ and nameencode
415f8cc712eSAndreas Gohr        $cnt = count($groups);
416f8cc712eSAndreas Gohr        for($i=0; $i<$cnt; $i++){
417f8cc712eSAndreas Gohr            $groups[$i] = '@'.auth_nameencode($groups[$i]);
418e259aa79SAndreas Gohr            if(!$auth->isCaseSensitive()){
419e259aa79SAndreas Gohr                $groups[$i] = utf8_strtolower($groups[$i]);
420e259aa79SAndreas Gohr            }
421f8cc712eSAndreas Gohr        }
422f8cc712eSAndreas Gohr
423f8cc712eSAndreas Gohr        // check groups against superuser and manager
4247651d633SGuy Brand        foreach($superusers as $supu)
4257651d633SGuy Brand            if(in_array($supu, $groups)) return true;
426f8cc712eSAndreas Gohr        if(!$adminonly){
4277651d633SGuy Brand            foreach($managers as $mana)
4287651d633SGuy Brand                if(in_array($mana, $groups)) return true;
429f8cc712eSAndreas Gohr        }
43000ce12daSChris Smith    }
43100ce12daSChris Smith
432f8cc712eSAndreas Gohr    return false;
433f8cc712eSAndreas Gohr}
434f8cc712eSAndreas Gohr
435f8cc712eSAndreas Gohr/**
436f8cc712eSAndreas Gohr * Check if a user is admin
437f8cc712eSAndreas Gohr *
438f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
439f8cc712eSAndreas Gohr *
440f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
441f8cc712eSAndreas Gohr *
442f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
443f8cc712eSAndreas Gohr * @see auth_ismanager
444f8cc712eSAndreas Gohr */
445f8cc712eSAndreas Gohrfunction auth_isadmin($user=null,$groups=null){
446f8cc712eSAndreas Gohr    return auth_ismanager($user,$groups,true);
447f8cc712eSAndreas Gohr}
448f8cc712eSAndreas Gohr
449f8cc712eSAndreas Gohr/**
45015fae107Sandi * Convinience function for auth_aclcheck()
45115fae107Sandi *
45215fae107Sandi * This checks the permissions for the current user
45315fae107Sandi *
45415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
45515fae107Sandi *
4561698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
45715fae107Sandi * @return int          permission level
458f3f0262cSandi */
459f3f0262cSandifunction auth_quickaclcheck($id){
460f3f0262cSandi    global $conf;
461f3f0262cSandi    global $USERINFO;
462f3f0262cSandi    # if no ACL is used always return upload rights
463f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
464f3f0262cSandi    return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
465f3f0262cSandi}
466f3f0262cSandi
467f3f0262cSandi/**
468f3f0262cSandi * Returns the maximum rights a user has for
469f3f0262cSandi * the given ID or its namespace
47015fae107Sandi *
47115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
47215fae107Sandi *
4731698b983Smichael * @param  string  $id     page ID (needs to be resolved and cleaned)
47415fae107Sandi * @param  string  $user   Username
47515fae107Sandi * @param  array   $groups Array of groups the user is in
47615fae107Sandi * @return int             permission level
477f3f0262cSandi */
478f3f0262cSandifunction auth_aclcheck($id,$user,$groups){
479f3f0262cSandi    global $conf;
480f3f0262cSandi    global $AUTH_ACL;
481d752aedeSAndreas Gohr    global $auth;
482f3f0262cSandi
48385d03f68SAndreas Gohr    // if no ACL is used always return upload rights
484f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
485beca106aSAdrian Lang    if (!$auth) return AUTH_NONE;
486f3f0262cSandi
487074cf26bSandi    //make sure groups is an array
488074cf26bSandi    if(!is_array($groups)) $groups = array();
489074cf26bSandi
49085d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
49185d03f68SAndreas Gohr    if(auth_isadmin($user,$groups)) { return AUTH_ADMIN; }
49285d03f68SAndreas Gohr
493e259aa79SAndreas Gohr    $ci = '';
494e259aa79SAndreas Gohr    if(!$auth->isCaseSensitive()) $ci = 'ui';
495d752aedeSAndreas Gohr
496d752aedeSAndreas Gohr    $user = $auth->cleanUser($user);
497d752aedeSAndreas Gohr    $groups = array_map(array($auth,'cleanGroup'),(array)$groups);
49885d03f68SAndreas Gohr    $user = auth_nameencode($user);
49985d03f68SAndreas Gohr
5006c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
5012cd2db38Sandi    $cnt = count($groups);
5022cd2db38Sandi    for($i=0; $i<$cnt; $i++){
5036c2bb100SAndreas Gohr        $groups[$i] = '@'.auth_nameencode($groups[$i]);
50410a76f6fSfrank    }
50510a76f6fSfrank
506f3f0262cSandi    $ns    = getNS($id);
507f3f0262cSandi    $perm  = -1;
508f3f0262cSandi
50934aeb4afSAndreas Gohr    if($user || count($groups)){
510f3f0262cSandi        //add ALL group
511f3f0262cSandi        $groups[] = '@ALL';
512f3f0262cSandi        //add User
51334aeb4afSAndreas Gohr        if($user) $groups[] = $user;
514f3f0262cSandi        //build regexp
515f3f0262cSandi        $regexp   = join('|',$groups);
516f3f0262cSandi    }else{
517f3f0262cSandi        $regexp = '@ALL';
518f3f0262cSandi    }
519f3f0262cSandi
520f3f0262cSandi    //check exact match first
521e259aa79SAndreas Gohr    $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/'.$ci,$AUTH_ACL);
522f3f0262cSandi    if(count($matches)){
523f3f0262cSandi        foreach($matches as $match){
524f3f0262cSandi            $match = preg_replace('/#.*$/','',$match); //ignore comments
525f3f0262cSandi            $acl   = preg_split('/\s+/',$match);
5268ef6b7caSandi            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
527f3f0262cSandi            if($acl[2] > $perm){
528f3f0262cSandi                $perm = $acl[2];
529f3f0262cSandi            }
530f3f0262cSandi        }
531f3f0262cSandi        if($perm > -1){
532f3f0262cSandi            //we had a match - return it
533f3f0262cSandi            return $perm;
534f3f0262cSandi        }
535f3f0262cSandi    }
536f3f0262cSandi
537f3f0262cSandi    //still here? do the namespace checks
538f3f0262cSandi    if($ns){
539f3f0262cSandi        $path = $ns.':\*';
540f3f0262cSandi    }else{
541f3f0262cSandi        $path = '\*'; //root document
542f3f0262cSandi    }
543f3f0262cSandi
544f3f0262cSandi    do{
545e259aa79SAndreas Gohr        $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/'.$ci,$AUTH_ACL);
546f3f0262cSandi        if(count($matches)){
547f3f0262cSandi            foreach($matches as $match){
548f3f0262cSandi                $match = preg_replace('/#.*$/','',$match); //ignore comments
549f3f0262cSandi                $acl   = preg_split('/\s+/',$match);
5508ef6b7caSandi                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
551f3f0262cSandi                if($acl[2] > $perm){
552f3f0262cSandi                    $perm = $acl[2];
553f3f0262cSandi                }
554f3f0262cSandi            }
555f3f0262cSandi            //we had a match - return it
556f3f0262cSandi            return $perm;
557f3f0262cSandi        }
558f3f0262cSandi
559f3f0262cSandi        //get next higher namespace
560f3f0262cSandi        $ns   = getNS($ns);
561f3f0262cSandi
562f3f0262cSandi        if($path != '\*'){
563f3f0262cSandi            $path = $ns.':\*';
564f3f0262cSandi            if($path == ':\*') $path = '\*';
565f3f0262cSandi        }else{
566f3f0262cSandi            //we did this already
567f3f0262cSandi            //looks like there is something wrong with the ACL
568f3f0262cSandi            //break here
569d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
570d5ce66f6SAndreas Gohr            return AUTH_NONE;
571f3f0262cSandi        }
572f3f0262cSandi    }while(1); //this should never loop endless
57352a5af8dSandi
57452a5af8dSandi    //still here? return no permissions
57552a5af8dSandi    return AUTH_NONE;
576f3f0262cSandi}
577f3f0262cSandi
578f3f0262cSandi/**
5796c2bb100SAndreas Gohr * Encode ASCII special chars
5806c2bb100SAndreas Gohr *
5816c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
5826c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
5836c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
5846c2bb100SAndreas Gohr * urlencoding!).
5856c2bb100SAndreas Gohr *
5866c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
5876c2bb100SAndreas Gohr *
5886c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
5896c2bb100SAndreas Gohr * @see rawurldecode()
5906c2bb100SAndreas Gohr */
591e838fc2eSAndreas Gohrfunction auth_nameencode($name,$skip_group=false){
592a424cd8eSchris    global $cache_authname;
593a424cd8eSchris    $cache =& $cache_authname;
59431784267SAndreas Gohr    $name  = (string) $name;
595a424cd8eSchris
59680601d26SAndreas Gohr    // never encode wildcard FS#1955
59780601d26SAndreas Gohr    if($name == '%USER%') return $name;
59880601d26SAndreas Gohr
599a424cd8eSchris    if (!isset($cache[$name][$skip_group])) {
600e838fc2eSAndreas Gohr        if($skip_group && $name{0} =='@'){
601a424cd8eSchris            $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
6021a9ae8e5SAndreas Gohr                    "'%'.dechex(ord(substr('\\1',-1)))",substr($name,1));
603e838fc2eSAndreas Gohr        }else{
604a424cd8eSchris            $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
6051a9ae8e5SAndreas Gohr                    "'%'.dechex(ord(substr('\\1',-1)))",$name);
606e838fc2eSAndreas Gohr        }
6076c2bb100SAndreas Gohr    }
6086c2bb100SAndreas Gohr
609a424cd8eSchris    return $cache[$name][$skip_group];
610a424cd8eSchris}
611a424cd8eSchris
6126c2bb100SAndreas Gohr/**
613f3f0262cSandi * Create a pronouncable password
614f3f0262cSandi *
61515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
61615fae107Sandi * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
61715fae107Sandi *
61815fae107Sandi * @return string  pronouncable password
619f3f0262cSandi */
620f3f0262cSandifunction auth_pwgen(){
621f3f0262cSandi    $pw = '';
622f3f0262cSandi    $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
623f3f0262cSandi    $v  = 'aeiou';              //vowels
624f3f0262cSandi    $a  = $c.$v;                //both
625f3f0262cSandi
626f3f0262cSandi    //use two syllables...
627f3f0262cSandi    for($i=0;$i < 2; $i++){
628f3f0262cSandi        $pw .= $c[rand(0, strlen($c)-1)];
629f3f0262cSandi        $pw .= $v[rand(0, strlen($v)-1)];
630f3f0262cSandi        $pw .= $a[rand(0, strlen($a)-1)];
631f3f0262cSandi    }
632f3f0262cSandi    //... and add a nice number
633f3f0262cSandi    $pw .= rand(10,99);
634f3f0262cSandi
635f3f0262cSandi    return $pw;
636f3f0262cSandi}
637f3f0262cSandi
638f3f0262cSandi/**
639f3f0262cSandi * Sends a password to the given user
640f3f0262cSandi *
64115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
64215fae107Sandi *
64315fae107Sandi * @return bool  true on success
644f3f0262cSandi */
645f3f0262cSandifunction auth_sendPassword($user,$password){
646f3f0262cSandi    global $conf;
647f3f0262cSandi    global $lang;
648cd52f92dSchris    global $auth;
649beca106aSAdrian Lang    if (!$auth) return false;
650cd52f92dSchris
651f3f0262cSandi    $hdrs  = '';
652d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
653cd52f92dSchris    $userinfo = $auth->getUserData($user);
654f3f0262cSandi
65587ddda95Sandi    if(!$userinfo['mail']) return false;
656f3f0262cSandi
657f3f0262cSandi    $text = rawLocale('password');
658ed7b5f09Sandi    $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
65987ddda95Sandi    $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
660f3f0262cSandi    $text = str_replace('@LOGIN@',$user,$text);
661f3f0262cSandi    $text = str_replace('@PASSWORD@',$password,$text);
662f3f0262cSandi    $text = str_replace('@TITLE@',$conf['title'],$text);
663f3f0262cSandi
66444f669e9Sandi    return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
66544f669e9Sandi            $lang['regpwmail'],
66644f669e9Sandi            $text,
66744f669e9Sandi            $conf['mailfrom']);
668f3f0262cSandi}
669f3f0262cSandi
670f3f0262cSandi/**
67115fae107Sandi * Register a new user
672f3f0262cSandi *
67315fae107Sandi * This registers a new user - Data is read directly from $_POST
67415fae107Sandi *
67515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
67615fae107Sandi *
67715fae107Sandi * @return bool  true on success, false on any error
678f3f0262cSandi */
679f3f0262cSandifunction register(){
680f3f0262cSandi    global $lang;
681eb5d07e4Sjan    global $conf;
682cd52f92dSchris    global $auth;
683f3f0262cSandi
684beca106aSAdrian Lang    if (!$auth) return false;
685f3f0262cSandi    if(!$_POST['save']) return false;
68682fd59b6SAndreas Gohr    if(!$auth->canDo('addUser')) return false;
687640145a5Sandi
688f3f0262cSandi    //clean username
689d752aedeSAndreas Gohr    $_POST['login'] = trim($auth->cleanUser($_POST['login']));
690d752aedeSAndreas Gohr
691f3f0262cSandi    //clean fullname and email
69254f0e6eaSAndreas Gohr    $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
69354f0e6eaSAndreas Gohr    $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
694f3f0262cSandi
695f3f0262cSandi    if( empty($_POST['login']) ||
696f3f0262cSandi        empty($_POST['fullname']) ||
697f3f0262cSandi        empty($_POST['email']) ){
698f3f0262cSandi        msg($lang['regmissing'],-1);
699f3f0262cSandi        return false;
700f3f0262cSandi    }
701f3f0262cSandi
702cab2716aSmatthias.grimm    if ($conf['autopasswd']) {
703cab2716aSmatthias.grimm        $pass = auth_pwgen();                // automatically generate password
704cab2716aSmatthias.grimm    } elseif (empty($_POST['pass']) ||
705cab2716aSmatthias.grimm            empty($_POST['passchk'])) {
706bf12ec81Sjan        msg($lang['regmissing'], -1);        // complain about missing passwords
707cab2716aSmatthias.grimm        return false;
708cab2716aSmatthias.grimm    } elseif ($_POST['pass'] != $_POST['passchk']) {
709bf12ec81Sjan        msg($lang['regbadpass'], -1);      // complain about misspelled passwords
710cab2716aSmatthias.grimm        return false;
711cab2716aSmatthias.grimm    } else {
712cab2716aSmatthias.grimm        $pass = $_POST['pass'];              // accept checked and valid password
713cab2716aSmatthias.grimm    }
714cab2716aSmatthias.grimm
715f3f0262cSandi    //check mail
71644f669e9Sandi    if(!mail_isvalid($_POST['email'])){
717f3f0262cSandi        msg($lang['regbadmail'],-1);
718f3f0262cSandi        return false;
719f3f0262cSandi    }
720f3f0262cSandi
721f3f0262cSandi    //okay try to create the user
7227d3c8d42SGabriel Birke    if(!$auth->triggerUserMod('create', array($_POST['login'],$pass,$_POST['fullname'],$_POST['email']))){
723f3f0262cSandi        msg($lang['reguexists'],-1);
724f3f0262cSandi        return false;
725f3f0262cSandi    }
726f3f0262cSandi
72702a498e7Schris    // create substitutions for use in notification email
72802a498e7Schris    $substitutions = array(
72902a498e7Schris            'NEWUSER' => $_POST['login'],
73002a498e7Schris            'NEWNAME' => $_POST['fullname'],
73102a498e7Schris            'NEWEMAIL' => $_POST['email'],
73202a498e7Schris            );
73302a498e7Schris
734cab2716aSmatthias.grimm    if (!$conf['autopasswd']) {
735cab2716aSmatthias.grimm        msg($lang['regsuccess2'],1);
73602a498e7Schris        notify('', 'register', '', $_POST['login'], false, $substitutions);
737cab2716aSmatthias.grimm        return true;
738cab2716aSmatthias.grimm    }
739cab2716aSmatthias.grimm
740cab2716aSmatthias.grimm    // autogenerated password? then send him the password
741f3f0262cSandi    if (auth_sendPassword($_POST['login'],$pass)){
742f3f0262cSandi        msg($lang['regsuccess'],1);
74302a498e7Schris        notify('', 'register', '', $_POST['login'], false, $substitutions);
744f3f0262cSandi        return true;
745f3f0262cSandi    }else{
746f3f0262cSandi        msg($lang['regmailfail'],-1);
747f3f0262cSandi        return false;
748f3f0262cSandi    }
749f3f0262cSandi}
750f3f0262cSandi
75110a76f6fSfrank/**
7528b06d178Schris * Update user profile
7538b06d178Schris *
7548b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
7558b06d178Schris */
7568b06d178Schrisfunction updateprofile() {
7578b06d178Schris    global $conf;
7588b06d178Schris    global $INFO;
7598b06d178Schris    global $lang;
760cd52f92dSchris    global $auth;
7618b06d178Schris
762beca106aSAdrian Lang    if (!$auth) return false;
763bb4866bdSchris    if(empty($_POST['save'])) return false;
7641b2a85e8SAndreas Gohr    if(!checkSecurityToken()) return false;
7658b06d178Schris
76682fd59b6SAndreas Gohr    // should not be able to get here without Profile being possible...
76782fd59b6SAndreas Gohr    if(!$auth->canDo('Profile')) {
7688b06d178Schris        msg($lang['profna'],-1);
7698b06d178Schris        return false;
7708b06d178Schris    }
7718b06d178Schris
7728b06d178Schris    if ($_POST['newpass'] != $_POST['passchk']) {
7738b06d178Schris        msg($lang['regbadpass'], -1);      // complain about misspelled passwords
7748b06d178Schris        return false;
7758b06d178Schris    }
7768b06d178Schris
7778b06d178Schris    //clean fullname and email
77854f0e6eaSAndreas Gohr    $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
77954f0e6eaSAndreas Gohr    $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
7808b06d178Schris
7814369edafSAndy Webber    if ((empty($_POST['fullname']) && $auth->canDo('modName')) ||
7824369edafSAndy Webber        (empty($_POST['email']) && $auth->canDo('modMail'))) {
7838b06d178Schris        msg($lang['profnoempty'],-1);
7848b06d178Schris        return false;
7858b06d178Schris    }
7868b06d178Schris
7874369edafSAndy Webber    if (!mail_isvalid($_POST['email']) && $auth->canDo('modMail')){
7888b06d178Schris        msg($lang['regbadmail'],-1);
7898b06d178Schris        return false;
7908b06d178Schris    }
7918b06d178Schris
7924c21b7eeSAndreas Gohr    if ($_POST['fullname'] != $INFO['userinfo']['name'] && $auth->canDo('modName')) $changes['name'] = $_POST['fullname'];
7934c21b7eeSAndreas Gohr    if ($_POST['email'] != $INFO['userinfo']['mail'] && $auth->canDo('modMail')) $changes['mail'] = $_POST['email'];
794cf626a62SAndreas Gohr    if (!empty($_POST['newpass']) && $auth->canDo('modPass')) $changes['pass'] = $_POST['newpass'];
7954c21b7eeSAndreas Gohr
7968b06d178Schris    if (!count($changes)) {
7978b06d178Schris        msg($lang['profnochange'], -1);
7988b06d178Schris        return false;
7998b06d178Schris    }
8008b06d178Schris
8018b06d178Schris    if ($conf['profileconfirm']) {
802df466c7aSAndreas Gohr        if (!$auth->checkPass($_SERVER['REMOTE_USER'], $_POST['oldpass'])) {
8038b06d178Schris            msg($lang['badlogin'],-1);
8048b06d178Schris            return false;
8058b06d178Schris        }
8068b06d178Schris    }
8078b06d178Schris
808a0b5b007SChris Smith    if ($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
809a0b5b007SChris Smith        // update cookie and session with the changed data
810a0b5b007SChris Smith        $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
8114b7f9e70STom N Harris        list($user,$sticky,$pass) = explode('|',$cookie,3);
812a0b5b007SChris Smith        if ($changes['pass']) $pass = PMA_blowfish_encrypt($changes['pass'],auth_cookiesalt());
813a0b5b007SChris Smith
814a0b5b007SChris Smith        auth_setCookie($_SERVER['REMOTE_USER'],$pass,(bool)$sticky);
81525b2a98cSMichael Klier        return true;
816a0b5b007SChris Smith    }
8178b06d178Schris}
8188b06d178Schris
8198b06d178Schris/**
8208b06d178Schris * Send a  new password
8218b06d178Schris *
8221d5856cfSAndreas Gohr * This function handles both phases of the password reset:
8231d5856cfSAndreas Gohr *
8241d5856cfSAndreas Gohr *   - handling the first request of password reset
8251d5856cfSAndreas Gohr *   - validating the password reset auth token
8261d5856cfSAndreas Gohr *
8278b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
8288b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
8291d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
8308b06d178Schris *
8318b06d178Schris * @return bool true on success, false on any error
8328b06d178Schris */
8338b06d178Schrisfunction act_resendpwd(){
8348b06d178Schris    global $lang;
8358b06d178Schris    global $conf;
836cd52f92dSchris    global $auth;
8378b06d178Schris
838409d7af7SAndreas Gohr    if(!actionOK('resendpwd')) return false;
839beca106aSAdrian Lang    if (!$auth) return false;
8408b06d178Schris
84182fd59b6SAndreas Gohr    // should not be able to get here without modPass being possible...
84282fd59b6SAndreas Gohr    if(!$auth->canDo('modPass')) {
8438b06d178Schris        msg($lang['resendna'],-1);
8448b06d178Schris        return false;
8458b06d178Schris    }
8468b06d178Schris
8471d5856cfSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
8488b06d178Schris
8491d5856cfSAndreas Gohr    if($token){
8501d5856cfSAndreas Gohr        // we're in token phase
8511d5856cfSAndreas Gohr
8521d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
8531d5856cfSAndreas Gohr        if(!@file_exists($tfile)){
8541d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'],-1);
8551d5856cfSAndreas Gohr            return false;
8561d5856cfSAndreas Gohr        }
8571d5856cfSAndreas Gohr        $user = io_readfile($tfile);
8581d5856cfSAndreas Gohr        @unlink($tfile);
859cd52f92dSchris        $userinfo = $auth->getUserData($user);
8608b06d178Schris        if(!$userinfo['mail']) {
8618b06d178Schris            msg($lang['resendpwdnouser'], -1);
8628b06d178Schris            return false;
8638b06d178Schris        }
8648b06d178Schris
8658b06d178Schris        $pass = auth_pwgen();
8667d3c8d42SGabriel Birke        if (!$auth->triggerUserMod('modify', array($user,array('pass' => $pass)))) {
8678b06d178Schris            msg('error modifying user data',-1);
8688b06d178Schris            return false;
8698b06d178Schris        }
8708b06d178Schris
8718b06d178Schris        if (auth_sendPassword($user,$pass)) {
8728b06d178Schris            msg($lang['resendpwdsuccess'],1);
8738b06d178Schris        } else {
8748b06d178Schris            msg($lang['regmailfail'],-1);
8758b06d178Schris        }
8768b06d178Schris        return true;
8771d5856cfSAndreas Gohr
8781d5856cfSAndreas Gohr    } else {
8791d5856cfSAndreas Gohr        // we're in request phase
8801d5856cfSAndreas Gohr
8811d5856cfSAndreas Gohr        if(!$_POST['save']) return false;
8821d5856cfSAndreas Gohr
8831d5856cfSAndreas Gohr        if (empty($_POST['login'])) {
8841d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
8851d5856cfSAndreas Gohr            return false;
8861d5856cfSAndreas Gohr        } else {
887d752aedeSAndreas Gohr            $user = trim($auth->cleanUser($_POST['login']));
8881d5856cfSAndreas Gohr        }
8891d5856cfSAndreas Gohr
8901d5856cfSAndreas Gohr        $userinfo = $auth->getUserData($user);
8911d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
8921d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
8931d5856cfSAndreas Gohr            return false;
8941d5856cfSAndreas Gohr        }
8951d5856cfSAndreas Gohr
8961d5856cfSAndreas Gohr        // generate auth token
8971d5856cfSAndreas Gohr        $token = md5(auth_cookiesalt().$user); //secret but user based
8981d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
8991d5856cfSAndreas Gohr        $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
9001d5856cfSAndreas Gohr
9011d5856cfSAndreas Gohr        io_saveFile($tfile,$user);
9021d5856cfSAndreas Gohr
9031d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
9041d5856cfSAndreas Gohr        $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
9051d5856cfSAndreas Gohr        $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
9061d5856cfSAndreas Gohr        $text = str_replace('@LOGIN@',$user,$text);
9071d5856cfSAndreas Gohr        $text = str_replace('@TITLE@',$conf['title'],$text);
9081d5856cfSAndreas Gohr        $text = str_replace('@CONFIRM@',$url,$text);
9091d5856cfSAndreas Gohr
9101d5856cfSAndreas Gohr        if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
9111d5856cfSAndreas Gohr                     $lang['regpwmail'],
9121d5856cfSAndreas Gohr                     $text,
9131d5856cfSAndreas Gohr                     $conf['mailfrom'])){
9141d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'],1);
9151d5856cfSAndreas Gohr        }else{
9161d5856cfSAndreas Gohr            msg($lang['regmailfail'],-1);
9171d5856cfSAndreas Gohr        }
9181d5856cfSAndreas Gohr        return true;
9191d5856cfSAndreas Gohr    }
9201d5856cfSAndreas Gohr
9211d5856cfSAndreas Gohr    return false; // never reached
9228b06d178Schris}
9238b06d178Schris
9248b06d178Schris/**
925b0855b11Sandi * Encrypts a password using the given method and salt
926b0855b11Sandi *
927b0855b11Sandi * If the selected method needs a salt and none was given, a random one
928b0855b11Sandi * is chosen.
929b0855b11Sandi *
930b0855b11Sandi * The following methods are understood:
931b0855b11Sandi *
932b0855b11Sandi *   smd5  - Salted MD5 hashing
933577c7cdaSAndreas Gohr *   apr1  - Apache salted MD5 hashing
934b0855b11Sandi *   md5   - Simple MD5 hashing
935b0855b11Sandi *   sha1  - SHA1 hashing
936b0855b11Sandi *   ssha  - Salted SHA1 hashing
937d7be6245Sandi *   crypt - Unix crypt
938d7be6245Sandi *   mysql - MySQL password (old method)
939d7be6245Sandi *   my411 - MySQL 4.1.1 password
94043ee7484SAndreas Gohr *   kmd5  - Salted MD5 hashing as used by UNB
941b0855b11Sandi *
942b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
943b0855b11Sandi * @return  string  The crypted password
944b0855b11Sandi */
945577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear,$method='',$salt=null){
946b0855b11Sandi    global $conf;
947b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
94810a76f6fSfrank
949b0855b11Sandi    //prepare a salt
950577c7cdaSAndreas Gohr    if(is_null($salt)) $salt = md5(uniqid(rand(), true));
951b0855b11Sandi
952b0855b11Sandi    switch(strtolower($method)){
953b0855b11Sandi        case 'smd5':
954056cb2ccSChris Smith            if(defined('CRYPT_MD5') && CRYPT_MD5) return crypt($clear,'$1$'.substr($salt,0,8).'$');
955577c7cdaSAndreas Gohr            // when crypt can't handle SMD5, falls through to pure PHP implementation
956577c7cdaSAndreas Gohr            $magic = '1';
957577c7cdaSAndreas Gohr        case 'apr1':
958577c7cdaSAndreas Gohr            //from http://de.php.net/manual/en/function.crypt.php#73619 comment by <mikey_nich at hotmail dot com>
9593371a8b4SAdrian Lang            if(!isset($magic)) $magic = 'apr1';
960577c7cdaSAndreas Gohr            $salt = substr($salt,0,8);
961577c7cdaSAndreas Gohr            $len = strlen($clear);
962577c7cdaSAndreas Gohr            $text = $clear.'$'.$magic.'$'.$salt;
963577c7cdaSAndreas Gohr            $bin = pack("H32", md5($clear.$salt.$clear));
964db959ae3SAndreas Gohr            for($i = $len; $i > 0; $i -= 16) {
965db959ae3SAndreas Gohr                $text .= substr($bin, 0, min(16, $i));
966db959ae3SAndreas Gohr            }
967db959ae3SAndreas Gohr            for($i = $len; $i > 0; $i >>= 1) {
968db959ae3SAndreas Gohr                $text .= ($i & 1) ? chr(0) : $clear{0};
969db959ae3SAndreas Gohr            }
970577c7cdaSAndreas Gohr            $bin = pack("H32", md5($text));
971577c7cdaSAndreas Gohr            for($i = 0; $i < 1000; $i++) {
972577c7cdaSAndreas Gohr                $new = ($i & 1) ? $clear : $bin;
973577c7cdaSAndreas Gohr                if ($i % 3) $new .= $salt;
974577c7cdaSAndreas Gohr                if ($i % 7) $new .= $clear;
975577c7cdaSAndreas Gohr                $new .= ($i & 1) ? $bin : $clear;
976577c7cdaSAndreas Gohr                $bin = pack("H32", md5($new));
977577c7cdaSAndreas Gohr            }
978577c7cdaSAndreas Gohr            $tmp = '';
979577c7cdaSAndreas Gohr            for ($i = 0; $i < 5; $i++) {
980577c7cdaSAndreas Gohr                $k = $i + 6;
981577c7cdaSAndreas Gohr                $j = $i + 12;
982577c7cdaSAndreas Gohr                if ($j == 16) $j = 5;
983577c7cdaSAndreas Gohr                $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
984577c7cdaSAndreas Gohr            }
985577c7cdaSAndreas Gohr            $tmp = chr(0).chr(0).$bin[11].$tmp;
986577c7cdaSAndreas Gohr            $tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
987577c7cdaSAndreas Gohr                    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
988577c7cdaSAndreas Gohr                    "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
989577c7cdaSAndreas Gohr            return '$'.$magic.'$'.$salt.'$'.$tmp;
990b0855b11Sandi        case 'md5':
991b0855b11Sandi            return md5($clear);
992b0855b11Sandi        case 'sha1':
993b0855b11Sandi            return sha1($clear);
994b0855b11Sandi        case 'ssha':
995b0855b11Sandi            $salt=substr($salt,0,4);
996d6e54e02Smatthiasgrimm            return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
997b0855b11Sandi        case 'crypt':
998b0855b11Sandi            return crypt($clear,substr($salt,0,2));
999d7be6245Sandi        case 'mysql':
1000d7be6245Sandi            //from http://www.php.net/mysql comment by <soren at byu dot edu>
1001d7be6245Sandi            $nr=0x50305735;
1002d7be6245Sandi            $nr2=0x12345671;
1003d7be6245Sandi            $add=7;
1004d7be6245Sandi            $charArr = preg_split("//", $clear);
1005d7be6245Sandi            foreach ($charArr as $char) {
1006d7be6245Sandi                if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
1007d7be6245Sandi                $charVal = ord($char);
1008d7be6245Sandi                $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
1009d7be6245Sandi                $nr2 += ($nr2 << 8) ^ $nr;
1010d7be6245Sandi                $add += $charVal;
1011d7be6245Sandi            }
1012d7be6245Sandi            return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
1013d7be6245Sandi        case 'my411':
1014d7be6245Sandi            return '*'.sha1(pack("H*", sha1($clear)));
101543ee7484SAndreas Gohr        case 'kmd5':
101643ee7484SAndreas Gohr            $key = substr($salt, 16, 2);
101743ee7484SAndreas Gohr            $hash1 = strtolower(md5($key . md5($clear)));
101843ee7484SAndreas Gohr            $hash2 = substr($hash1, 0, 16) . $key . substr($hash1, 16);
101943ee7484SAndreas Gohr            return $hash2;
1020b0855b11Sandi        default:
1021b0855b11Sandi            msg("Unsupported crypt method $method",-1);
1022b0855b11Sandi    }
1023b0855b11Sandi}
1024b0855b11Sandi
1025b0855b11Sandi/**
1026b0855b11Sandi * Verifies a cleartext password against a crypted hash
1027b0855b11Sandi *
1028b0855b11Sandi * The method and salt used for the crypted hash is determined automatically
1029b0855b11Sandi * then the clear text password is crypted using the same method. If both hashs
1030b0855b11Sandi * match true is is returned else false
1031b0855b11Sandi *
1032b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
1033b0855b11Sandi * @return  bool
1034b0855b11Sandi */
1035b0855b11Sandifunction auth_verifyPassword($clear,$crypt){
1036b0855b11Sandi    $method='';
1037b0855b11Sandi    $salt='';
1038b0855b11Sandi
1039b0855b11Sandi    //determine the used method and salt
1040d7be6245Sandi    $len = strlen($crypt);
1041577c7cdaSAndreas Gohr    if(preg_match('/^\$1\$([^\$]{0,8})\$/',$crypt,$m)){
1042b0855b11Sandi        $method = 'smd5';
1043577c7cdaSAndreas Gohr        $salt   = $m[1];
1044577c7cdaSAndreas Gohr    }elseif(preg_match('/^\$apr1\$([^\$]{0,8})\$/',$crypt,$m)){
1045577c7cdaSAndreas Gohr        $method = 'apr1';
1046577c7cdaSAndreas Gohr        $salt   = $m[1];
1047b0855b11Sandi    }elseif(substr($crypt,0,6) == '{SSHA}'){
1048b0855b11Sandi        $method = 'ssha';
1049b0855b11Sandi        $salt   = substr(base64_decode(substr($crypt, 6)),20);
1050d7be6245Sandi    }elseif($len == 32){
1051b0855b11Sandi        $method = 'md5';
1052d7be6245Sandi    }elseif($len == 40){
1053b0855b11Sandi        $method = 'sha1';
1054d7be6245Sandi    }elseif($len == 16){
1055d7be6245Sandi        $method = 'mysql';
1056d7be6245Sandi    }elseif($len == 41 && $crypt[0] == '*'){
1057d7be6245Sandi        $method = 'my411';
105843ee7484SAndreas Gohr    }elseif($len == 34){
105943ee7484SAndreas Gohr        $method = 'kmd5';
106043ee7484SAndreas Gohr        $salt   = $crypt;
1061b0855b11Sandi    }else{
1062b0855b11Sandi        $method = 'crypt';
1063b0855b11Sandi        $salt   = substr($crypt,0,2);
1064b0855b11Sandi    }
1065b0855b11Sandi
1066b0855b11Sandi    //crypt and compare
1067b0855b11Sandi    if(auth_cryptPassword($clear,$method,$salt) === $crypt){
1068b0855b11Sandi        return true;
1069b0855b11Sandi    }
1070b0855b11Sandi    return false;
1071b0855b11Sandi}
1072340756e4Sandi
1073a0b5b007SChris Smith/**
1074a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1075a0b5b007SChris Smith *
1076a0b5b007SChris Smith * @param string  $user       username
1077a0b5b007SChris Smith * @param string  $pass       encrypted password
1078a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1079a0b5b007SChris Smith */
1080a0b5b007SChris Smithfunction auth_setCookie($user,$pass,$sticky) {
1081a0b5b007SChris Smith    global $conf;
1082a0b5b007SChris Smith    global $auth;
108379d00841SOliver Geisen    global $USERINFO;
1084a0b5b007SChris Smith
1085beca106aSAdrian Lang    if (!$auth) return false;
1086a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1087a0b5b007SChris Smith
1088a0b5b007SChris Smith    // set cookie
1089645c0a36SAndreas Gohr    $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
1090c66972f2SAdrian Lang    $time = $sticky ? (time()+60*60*24*365) : 0; //one year
1091a0b5b007SChris Smith    if (version_compare(PHP_VERSION, '5.2.0', '>')) {
1092a0b5b007SChris Smith        setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true);
1093a0b5b007SChris Smith    }else{
1094a0b5b007SChris Smith        setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()));
1095a0b5b007SChris Smith    }
1096a0b5b007SChris Smith    // set session
1097a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1098a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['pass'] = $pass;
1099a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1100a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1101a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1102a0b5b007SChris Smith}
1103a0b5b007SChris Smith
1104645c0a36SAndreas Gohr/**
1105645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1106645c0a36SAndreas Gohr *
1107645c0a36SAndreas Gohr * @returns array
1108645c0a36SAndreas Gohr */
1109645c0a36SAndreas Gohrfunction auth_getCookie(){
1110c66972f2SAdrian Lang    if (!isset($_COOKIE[DOKU_COOKIE])) {
1111c66972f2SAdrian Lang        return array(null, null, null);
1112c66972f2SAdrian Lang    }
1113645c0a36SAndreas Gohr    list($user,$sticky,$pass) = explode('|',$_COOKIE[DOKU_COOKIE],3);
1114645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1115645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1116645c0a36SAndreas Gohr    $user   = base64_decode($user);
1117645c0a36SAndreas Gohr    return array($user,$sticky,$pass);
1118645c0a36SAndreas Gohr}
1119645c0a36SAndreas Gohr
1120340756e4Sandi//Setup VIM: ex: et ts=2 enc=utf-8 :
1121