xref: /dokuwiki/inc/auth.php (revision d0f8d50b16073494dc8ccc16905d445467e648cd)
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
32ab5d26daSAndreas Gohr * @triggers AUTH_LOGIN_CHECK
33ab5d26daSAndreas Gohr * @return bool
3416905344SAndreas Gohr */
3516905344SAndreas Gohrfunction auth_setup() {
36742c66f8Schris    global $conf;
37ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
3803c4aec3Schris    global $auth;
39bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
40bcc94b2cSAndreas Gohr    global $INPUT;
419a9714acSDominik Eckelmann    global $AUTH_ACL;
429a9714acSDominik Eckelmann    global $lang;
439a9714acSDominik Eckelmann    $AUTH_ACL = array();
4403c4aec3Schris
4516905344SAndreas Gohr    if(!$conf['useacl']) return false;
4616905344SAndreas Gohr
4716905344SAndreas Gohr    // load the the backend auth functions and instantiate the auth object XXX
488b06d178Schris    if(@file_exists(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php')) {
498b06d178Schris        require_once(DOKU_INC.'inc/auth/basic.class.php');
508b06d178Schris        require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php');
518b06d178Schris
528b06d178Schris        $auth_class = "auth_".$conf['authtype'];
53cd52f92dSchris        if(class_exists($auth_class)) {
548b06d178Schris            $auth = new $auth_class();
55d2dde4ebSMatthias Grimm            if($auth->success == false) {
560f4f4adfSAndreas Gohr                // degrade to unauthenticated user
57d2dde4ebSMatthias Grimm                unset($auth);
580f4f4adfSAndreas Gohr                auth_logoff();
59cd52f92dSchris                msg($lang['authtempfail'], -1);
60d2dde4ebSMatthias Grimm            }
618b06d178Schris        } else {
623816dcbcSAndreas Gohr            nice_die($lang['authmodfailed']);
63cd52f92dSchris        }
64cd52f92dSchris    } else {
653816dcbcSAndreas Gohr        nice_die($lang['authmodfailed']);
668b06d178Schris    }
67f3f0262cSandi
68ab5d26daSAndreas Gohr    if(!$auth) return false;
6916905344SAndreas Gohr
7016905344SAndreas Gohr    // do the login either by cookie or provided credentials XXX
71bcc94b2cSAndreas Gohr    $INPUT->set('http_credentials', false);
72bcc94b2cSAndreas Gohr    if(!$conf['rememberme']) $INPUT->set('r', false);
73bbbd6568SAndreas Gohr
74b2665af7SMichael Hamann    // handle renamed HTTP_AUTHORIZATION variable (can happen when a fix like
75b2665af7SMichael Hamann    // the one presented at
76b2665af7SMichael Hamann    // http://www.besthostratings.com/articles/http-auth-php-cgi.html is used
77b2665af7SMichael Hamann    // for enabling HTTP authentication with CGI/SuExec)
78b2665af7SMichael Hamann    if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
79b2665af7SMichael Hamann        $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
80528ddc7cSAndreas Gohr    // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
8106156f3cSAndreas Gohr    if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
82528ddc7cSAndreas Gohr        list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
83528ddc7cSAndreas Gohr            explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
84528ddc7cSAndreas Gohr    }
85528ddc7cSAndreas Gohr
861e8c9c90SAndreas Gohr    // if no credentials were given try to use HTTP auth (for SSO)
87bcc94b2cSAndreas Gohr    if(!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])) {
88bcc94b2cSAndreas Gohr        $INPUT->set('u', $_SERVER['PHP_AUTH_USER']);
89bcc94b2cSAndreas Gohr        $INPUT->set('p', $_SERVER['PHP_AUTH_PW']);
90bcc94b2cSAndreas Gohr        $INPUT->set('http_credentials', true);
911e8c9c90SAndreas Gohr    }
921e8c9c90SAndreas Gohr
93191bb90aSAndreas Gohr    // apply cleaning
94bcc94b2cSAndreas Gohr    $INPUT->set('u', $auth->cleanUser($INPUT->str('u')));
95191bb90aSAndreas Gohr
96bcc94b2cSAndreas Gohr    if($INPUT->str('authtok')) {
97f13fa892SAndreas Gohr        // when an authentication token is given, trust the session
98bcc94b2cSAndreas Gohr        auth_validateToken($INPUT->str('authtok'));
99f13fa892SAndreas Gohr    } elseif(!is_null($auth) && $auth->canDo('external')) {
100f13fa892SAndreas Gohr        // external trust mechanism in place
101bcc94b2cSAndreas Gohr        $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
102f5cb575dSAndreas Gohr    } else {
1036080c584SRobin Gareus        $evdata = array(
104bcc94b2cSAndreas Gohr            'user'     => $INPUT->str('u'),
105bcc94b2cSAndreas Gohr            'password' => $INPUT->str('p'),
106bcc94b2cSAndreas Gohr            'sticky'   => $INPUT->bool('r'),
107bcc94b2cSAndreas Gohr            'silent'   => $INPUT->bool('http_credentials')
1086080c584SRobin Gareus        );
109b5ee21aaSAdrian Lang        trigger_event('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
110f5cb575dSAndreas Gohr    }
111f5cb575dSAndreas Gohr
11216905344SAndreas Gohr    //load ACL into a global array XXX
11375c93b77SAndreas Gohr    $AUTH_ACL = auth_loadACL();
114ab5d26daSAndreas Gohr
115ab5d26daSAndreas Gohr    return true;
11675c93b77SAndreas Gohr}
11775c93b77SAndreas Gohr
11875c93b77SAndreas Gohr/**
11975c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards
12075c93b77SAndreas Gohr *
12175c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
122ab5d26daSAndreas Gohr * @return array
12375c93b77SAndreas Gohr */
12475c93b77SAndreas Gohrfunction auth_loadACL() {
12575c93b77SAndreas Gohr    global $config_cascade;
126b78bf706Sromain    global $conf;
127b78bf706Sromain    global $USERINFO;
12875c93b77SAndreas Gohr
12975c93b77SAndreas Gohr    if(!is_readable($config_cascade['acl']['default'])) return array();
13075c93b77SAndreas Gohr
13175c93b77SAndreas Gohr    $acl = file($config_cascade['acl']['default']);
13275c93b77SAndreas Gohr
133191bb90aSAndreas Gohr    //support user wildcard
134b78bf706Sromain    if(isset($_SERVER['REMOTE_USER']) && $conf['use_wildcards']){
13575c93b77SAndreas Gohr        $len = count($acl);
13675c93b77SAndreas Gohr        for($i = 0; $i < $len; $i++) {
13775c93b77SAndreas Gohr            if($acl[$i]{0} == '#') continue;
13875c93b77SAndreas Gohr            list($id,$rest) = preg_split('/\s+/',$acl[$i],2);
139*d0f8d50bSAndreas Gohr            if(strstr($acl[$i], '%GROUP%')){
140b78bf706Sromain                foreach($USERINFO['grps'] as $grp){
141b78bf706Sromain                    $nid   = str_replace('%GROUP%',cleanID($grp),$id);
142b78bf706Sromain                    $nrest = str_replace('%GROUP%',auth_nameencode($grp),$rest);
143b78bf706Sromain                    $acl[] = "$nid\t$nrest";
144b78bf706Sromain                }
145b78bf706Sromain            }
14675c93b77SAndreas Gohr            $id   = str_replace('%USER%',cleanID($_SERVER['REMOTE_USER']),$id);
14775c93b77SAndreas Gohr            $rest = str_replace('%USER%',auth_nameencode($_SERVER['REMOTE_USER']),$rest);
14875c93b77SAndreas Gohr            $acl[$i] = "$id\t$rest";
149a8fe108bSGuy Brand        }
15011799630Sandi    }
15175c93b77SAndreas Gohr    return $acl;
152f3f0262cSandi}
153f3f0262cSandi
154ab5d26daSAndreas Gohr/**
155ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK
156ab5d26daSAndreas Gohr *
157ab5d26daSAndreas Gohr * @param $evdata
158ab5d26daSAndreas Gohr * @return bool
159ab5d26daSAndreas Gohr */
160b5ee21aaSAdrian Langfunction auth_login_wrapper($evdata) {
161ab5d26daSAndreas Gohr    return auth_login(
162ab5d26daSAndreas Gohr        $evdata['user'],
163b5ee21aaSAdrian Lang        $evdata['password'],
164b5ee21aaSAdrian Lang        $evdata['sticky'],
165ab5d26daSAndreas Gohr        $evdata['silent']
166ab5d26daSAndreas Gohr    );
167b5ee21aaSAdrian Lang}
168b5ee21aaSAdrian Lang
169f3f0262cSandi/**
170f3f0262cSandi * This tries to login the user based on the sent auth credentials
171f3f0262cSandi *
172f3f0262cSandi * The authentication works like this: if a username was given
17315fae107Sandi * a new login is assumed and user/password are checked. If they
17415fae107Sandi * are correct the password is encrypted with blowfish and stored
17515fae107Sandi * together with the username in a cookie - the same info is stored
17615fae107Sandi * in the session, too. Additonally a browserID is stored in the
17715fae107Sandi * session.
17815fae107Sandi *
17915fae107Sandi * If no username was given the cookie is checked: if the username,
18015fae107Sandi * crypted password and browserID match between session and cookie
18115fae107Sandi * no further testing is done and the user is accepted
18215fae107Sandi *
18315fae107Sandi * If a cookie was found but no session info was availabe the
184136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
18515fae107Sandi * together with username rechecked by calling this function again.
186f3f0262cSandi *
187f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
188f3f0262cSandi * are set.
18915fae107Sandi *
19015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
19115fae107Sandi *
19215fae107Sandi * @param   string  $user    Username
19315fae107Sandi * @param   string  $pass    Cleartext Password
19415fae107Sandi * @param   bool    $sticky  Cookie should not expire
195f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
19615fae107Sandi * @return  bool             true on successful auth
197f3f0262cSandi */
198f112c2faSAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false) {
199f3f0262cSandi    global $USERINFO;
200f3f0262cSandi    global $conf;
201f3f0262cSandi    global $lang;
202ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
203cd52f92dSchris    global $auth;
204ab5d26daSAndreas Gohr
205132bdbfeSandi    $sticky ? $sticky = true : $sticky = false; //sanity check
206f3f0262cSandi
207beca106aSAdrian Lang    if(!$auth) return false;
208beca106aSAdrian Lang
209bbbd6568SAndreas Gohr    if(!empty($user)) {
210132bdbfeSandi        //usual login
211cd52f92dSchris        if($auth->checkPass($user, $pass)) {
212132bdbfeSandi            // make logininfo globally available
213f3f0262cSandi            $_SERVER['REMOTE_USER'] = $user;
21432ed2b36SAndreas Gohr            $secret                 = auth_cookiesalt(!$sticky); //bind non-sticky to session
215e940aea4SAndreas Gohr            auth_setCookie($user, PMA_blowfish_encrypt($pass, $secret), $sticky);
216132bdbfeSandi            return true;
217f3f0262cSandi        } else {
218f3f0262cSandi            //invalid credentials - log off
219f112c2faSAndreas Gohr            if(!$silent) msg($lang['badlogin'], -1);
220f3f0262cSandi            auth_logoff();
221132bdbfeSandi            return false;
222f3f0262cSandi        }
223f3f0262cSandi    } else {
224132bdbfeSandi        // read cookie information
225645c0a36SAndreas Gohr        list($user, $sticky, $pass) = auth_getCookie();
226132bdbfeSandi        if($user && $pass) {
227132bdbfeSandi            // we got a cookie - see if we can trust it
228fa7c70ffSAdrian Lang
229fa7c70ffSAdrian Lang            // get session info
230fa7c70ffSAdrian Lang            $session = $_SESSION[DOKU_COOKIE]['auth'];
231132bdbfeSandi            if(isset($session) &&
2327172dbc0SAndreas Gohr                $auth->useSessionCache($user) &&
2334c989037SChris Smith                ($session['time'] >= time() - $conf['auth_security_timeout']) &&
234132bdbfeSandi                ($session['user'] == $user) &&
235234ce57eSAndreas Gohr                ($session['pass'] == sha1($pass)) && //still crypted
236ab5d26daSAndreas Gohr                ($session['buid'] == auth_browseruid())
237ab5d26daSAndreas Gohr            ) {
238234ce57eSAndreas Gohr
239132bdbfeSandi                // he has session, cookie and browser right - let him in
240132bdbfeSandi                $_SERVER['REMOTE_USER'] = $user;
241132bdbfeSandi                $USERINFO               = $session['info']; //FIXME move all references to session
242132bdbfeSandi                return true;
243132bdbfeSandi            }
244f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
24532ed2b36SAndreas Gohr            $secret = auth_cookiesalt(!$sticky); //bind non-sticky to session
246e940aea4SAndreas Gohr            $pass   = PMA_blowfish_decrypt($pass, $secret);
247f112c2faSAndreas Gohr            return auth_login($user, $pass, $sticky, true);
248132bdbfeSandi        }
249132bdbfeSandi    }
250f3f0262cSandi    //just to be sure
251883179a4SAndreas Gohr    auth_logoff(true);
252132bdbfeSandi    return false;
253f3f0262cSandi}
254132bdbfeSandi
255132bdbfeSandi/**
256f13fa892SAndreas Gohr * Checks if a given authentication token was stored in the session
257f13fa892SAndreas Gohr *
258f13fa892SAndreas Gohr * Will setup authentication data using data from the session if the
259f13fa892SAndreas Gohr * token is correct. Will exit with a 401 Status if not.
260f13fa892SAndreas Gohr *
261f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
262f13fa892SAndreas Gohr * @param  string $token The authentication token
263f13fa892SAndreas Gohr * @return boolean true (or will exit on failure)
264f13fa892SAndreas Gohr */
265f13fa892SAndreas Gohrfunction auth_validateToken($token) {
266f13fa892SAndreas Gohr    if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']) {
267f13fa892SAndreas Gohr        // bad token
268f13fa892SAndreas Gohr        header("HTTP/1.0 401 Unauthorized");
269f13fa892SAndreas Gohr        print 'Invalid auth token - maybe the session timed out';
270f13fa892SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
271f13fa892SAndreas Gohr        exit;
272f13fa892SAndreas Gohr    }
273f13fa892SAndreas Gohr    // still here? trust the session data
274f13fa892SAndreas Gohr    global $USERINFO;
275f13fa892SAndreas Gohr    $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
276f13fa892SAndreas Gohr    $USERINFO               = $_SESSION[DOKU_COOKIE]['auth']['info'];
277f13fa892SAndreas Gohr    return true;
278f13fa892SAndreas Gohr}
279f13fa892SAndreas Gohr
280f13fa892SAndreas Gohr/**
281f13fa892SAndreas Gohr * Create an auth token and store it in the session
282f13fa892SAndreas Gohr *
283f13fa892SAndreas Gohr * NOTE: this is completely unrelated to the getSecurityToken() function
284f13fa892SAndreas Gohr *
285f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
286f13fa892SAndreas Gohr * @return string The auth token
287f13fa892SAndreas Gohr */
288f13fa892SAndreas Gohrfunction auth_createToken() {
289f13fa892SAndreas Gohr    $token = md5(mt_rand());
29009c2d803SAndreas Gohr    @session_start(); // reopen the session if needed
291f13fa892SAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
29209c2d803SAndreas Gohr    session_write_close();
293f13fa892SAndreas Gohr    return $token;
294f13fa892SAndreas Gohr}
295f13fa892SAndreas Gohr
296f13fa892SAndreas Gohr/**
297136ce040Sandi * Builds a pseudo UID from browser and IP data
298132bdbfeSandi *
299132bdbfeSandi * This is neither unique nor unfakable - still it adds some
300136ce040Sandi * security. Using the first part of the IP makes sure
301136ce040Sandi * proxy farms like AOLs are stil okay.
30215fae107Sandi *
30315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
30415fae107Sandi *
30515fae107Sandi * @return  string  a MD5 sum of various browser headers
306132bdbfeSandi */
307132bdbfeSandifunction auth_browseruid() {
3082f9daf16SAndreas Gohr    $ip  = clientIP(true);
309132bdbfeSandi    $uid = '';
310132bdbfeSandi    $uid .= $_SERVER['HTTP_USER_AGENT'];
311132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
312132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
313132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
3142f9daf16SAndreas Gohr    $uid .= substr($ip, 0, strpos($ip, '.'));
315132bdbfeSandi    return md5($uid);
316132bdbfeSandi}
317132bdbfeSandi
318132bdbfeSandi/**
319132bdbfeSandi * Creates a random key to encrypt the password in cookies
32015fae107Sandi *
32115fae107Sandi * This function tries to read the password for encrypting
32298407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
32315fae107Sandi * if no such file is found a random key is created and
32415fae107Sandi * and stored in this file.
32515fae107Sandi *
32615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
32732ed2b36SAndreas Gohr * @param   bool $addsession if true, the sessionid is added to the salt
32815fae107Sandi * @return  string
329132bdbfeSandi */
33032ed2b36SAndreas Gohrfunction auth_cookiesalt($addsession = false) {
331132bdbfeSandi    global $conf;
33298407a7aSandi    $file = $conf['metadir'].'/_htcookiesalt';
333132bdbfeSandi    $salt = io_readFile($file);
334132bdbfeSandi    if(empty($salt)) {
335132bdbfeSandi        $salt = uniqid(rand(), true);
336132bdbfeSandi        io_saveFile($file, $salt);
337132bdbfeSandi    }
33832ed2b36SAndreas Gohr    if($addsession) {
33932ed2b36SAndreas Gohr        $salt .= session_id();
34032ed2b36SAndreas Gohr    }
341132bdbfeSandi    return $salt;
342f3f0262cSandi}
343f3f0262cSandi
344f3f0262cSandi/**
345883179a4SAndreas Gohr * Log out the current user
346883179a4SAndreas Gohr *
347f3f0262cSandi * This clears all authentication data and thus log the user
348883179a4SAndreas Gohr * off. It also clears session data.
34915fae107Sandi *
35015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
351883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
352f3f0262cSandi */
353883179a4SAndreas Gohrfunction auth_logoff($keepbc = false) {
354f3f0262cSandi    global $conf;
355f3f0262cSandi    global $USERINFO;
356ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
3575298a619SAndreas Gohr    global $auth;
35837065e65Sandi
359d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
360e9621d07SAndreas Gohr    @session_start();
361e9621d07SAndreas Gohr
362e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
363e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
364e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
365e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
366e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
367e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
368883179a4SAndreas Gohr    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
369e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
37037065e65Sandi    if(isset($_SERVER['REMOTE_USER']))
371f3f0262cSandi        unset($_SERVER['REMOTE_USER']);
372132bdbfeSandi    $USERINFO = null; //FIXME
373f5c6743cSAndreas Gohr
37473ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
375f5c6743cSAndreas Gohr    if(version_compare(PHP_VERSION, '5.2.0', '>')) {
37673ab87deSGabriel Birke        setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
377f5c6743cSAndreas Gohr    } else {
37873ab87deSGabriel Birke        setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
379f5c6743cSAndreas Gohr    }
3805298a619SAndreas Gohr
381880f62faSAndreas Gohr    if($auth) $auth->logOff();
382f3f0262cSandi}
383f3f0262cSandi
384f3f0262cSandi/**
385f8cc712eSAndreas Gohr * Check if a user is a manager
386f8cc712eSAndreas Gohr *
387f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
388f8cc712eSAndreas Gohr * user.
389f8cc712eSAndreas Gohr *
390f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
391f8cc712eSAndreas Gohr *
392f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
393f8cc712eSAndreas Gohr * @see    auth_isadmin
394ab5d26daSAndreas Gohr * @param  string $user       Username
395ab5d26daSAndreas Gohr * @param  array  $groups     List of groups the user is in
396ab5d26daSAndreas Gohr * @param  bool   $adminonly  when true checks if user is admin
397ab5d26daSAndreas Gohr * @return bool
398f8cc712eSAndreas Gohr */
399f8cc712eSAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false) {
400f8cc712eSAndreas Gohr    global $conf;
401f8cc712eSAndreas Gohr    global $USERINFO;
402ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
403d752aedeSAndreas Gohr    global $auth;
404f8cc712eSAndreas Gohr
405beca106aSAdrian Lang    if(!$auth) return false;
406c66972f2SAdrian Lang    if(is_null($user)) {
407c66972f2SAdrian Lang        if(!isset($_SERVER['REMOTE_USER'])) {
408c66972f2SAdrian Lang            return false;
409c66972f2SAdrian Lang        } else {
410c66972f2SAdrian Lang            $user = $_SERVER['REMOTE_USER'];
411c66972f2SAdrian Lang        }
412c66972f2SAdrian Lang    }
413d6dc956fSAndreas Gohr    if(is_null($groups)) {
414d6dc956fSAndreas Gohr        $groups = (array) $USERINFO['grps'];
415e259aa79SAndreas Gohr    }
416e259aa79SAndreas Gohr
417d6dc956fSAndreas Gohr    // check superuser match
418d6dc956fSAndreas Gohr    if(auth_isMember($conf['superuser'], $user, $groups)) return true;
419d6dc956fSAndreas Gohr    if($adminonly) return false;
420e259aa79SAndreas Gohr    // check managers
421d6dc956fSAndreas Gohr    if(auth_isMember($conf['manager'], $user, $groups)) return true;
42200ce12daSChris Smith
423f8cc712eSAndreas Gohr    return false;
424f8cc712eSAndreas Gohr}
425f8cc712eSAndreas Gohr
426f8cc712eSAndreas Gohr/**
427f8cc712eSAndreas Gohr * Check if a user is admin
428f8cc712eSAndreas Gohr *
429f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
430f8cc712eSAndreas Gohr *
431f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
432f8cc712eSAndreas Gohr *
433f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
434ab5d26daSAndreas Gohr * @see auth_ismanager()
435ab5d26daSAndreas Gohr * @param  string $user       Username
436ab5d26daSAndreas Gohr * @param  array  $groups     List of groups the user is in
437ab5d26daSAndreas Gohr * @return bool
438f8cc712eSAndreas Gohr */
439f8cc712eSAndreas Gohrfunction auth_isadmin($user = null, $groups = null) {
440f8cc712eSAndreas Gohr    return auth_ismanager($user, $groups, true);
441f8cc712eSAndreas Gohr}
442f8cc712eSAndreas Gohr
443d6dc956fSAndreas Gohr/**
444d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
445d6dc956fSAndreas Gohr * users and groups to determine membership status
446d6dc956fSAndreas Gohr *
447d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
448d6dc956fSAndreas Gohr *
449d6dc956fSAndreas Gohr * @param $memberlist string commaseparated list of allowed users and groups
450d6dc956fSAndreas Gohr * @param $user       string user to match against
451d6dc956fSAndreas Gohr * @param $groups     array  groups the user is member of
4525446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
453d6dc956fSAndreas Gohr */
454d6dc956fSAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups) {
455ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
456d6dc956fSAndreas Gohr    global $auth;
457d6dc956fSAndreas Gohr    if(!$auth) return false;
458d6dc956fSAndreas Gohr
459d6dc956fSAndreas Gohr    // clean user and groups
4604f56ecbfSAdrian Lang    if(!$auth->isCaseSensitive()) {
461d6dc956fSAndreas Gohr        $user   = utf8_strtolower($user);
462d6dc956fSAndreas Gohr        $groups = array_map('utf8_strtolower', $groups);
463d6dc956fSAndreas Gohr    }
464d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
465d6dc956fSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), $groups);
466d6dc956fSAndreas Gohr
467d6dc956fSAndreas Gohr    // extract the memberlist
468d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
469d6dc956fSAndreas Gohr    $members = array_map('trim', $members);
470d6dc956fSAndreas Gohr    $members = array_unique($members);
471d6dc956fSAndreas Gohr    $members = array_filter($members);
472d6dc956fSAndreas Gohr
473d6dc956fSAndreas Gohr    // compare cleaned values
474d6dc956fSAndreas Gohr    foreach($members as $member) {
4754f56ecbfSAdrian Lang        if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member);
476d6dc956fSAndreas Gohr        if($member[0] == '@') {
477d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
478d6dc956fSAndreas Gohr            if(in_array($member, $groups)) return true;
479d6dc956fSAndreas Gohr        } else {
480d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
481d6dc956fSAndreas Gohr            if($member == $user) return true;
482d6dc956fSAndreas Gohr        }
483d6dc956fSAndreas Gohr    }
484d6dc956fSAndreas Gohr
485d6dc956fSAndreas Gohr    // still here? not a member!
486d6dc956fSAndreas Gohr    return false;
487d6dc956fSAndreas Gohr}
488d6dc956fSAndreas Gohr
489f8cc712eSAndreas Gohr/**
49015fae107Sandi * Convinience function for auth_aclcheck()
49115fae107Sandi *
49215fae107Sandi * This checks the permissions for the current user
49315fae107Sandi *
49415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
49515fae107Sandi *
4961698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
49715fae107Sandi * @return int          permission level
498f3f0262cSandi */
499f3f0262cSandifunction auth_quickaclcheck($id) {
500f3f0262cSandi    global $conf;
501f3f0262cSandi    global $USERINFO;
502f3f0262cSandi    # if no ACL is used always return upload rights
503f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
504f3f0262cSandi    return auth_aclcheck($id, $_SERVER['REMOTE_USER'], $USERINFO['grps']);
505f3f0262cSandi}
506f3f0262cSandi
507f3f0262cSandi/**
508f3f0262cSandi * Returns the maximum rights a user has for
509f3f0262cSandi * the given ID or its namespace
51015fae107Sandi *
51115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
51215fae107Sandi *
5131698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
51415fae107Sandi * @param  string       $user   Username
5153272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
51615fae107Sandi * @return int             permission level
517f3f0262cSandi */
518f3f0262cSandifunction auth_aclcheck($id, $user, $groups) {
519f3f0262cSandi    global $conf;
520f3f0262cSandi    global $AUTH_ACL;
521ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
522d752aedeSAndreas Gohr    global $auth;
523f3f0262cSandi
52485d03f68SAndreas Gohr    // if no ACL is used always return upload rights
525f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
526beca106aSAdrian Lang    if(!$auth) return AUTH_NONE;
527f3f0262cSandi
528074cf26bSandi    //make sure groups is an array
529074cf26bSandi    if(!is_array($groups)) $groups = array();
530074cf26bSandi
53185d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
532ab5d26daSAndreas Gohr    if(auth_isadmin($user, $groups)) {
533ab5d26daSAndreas Gohr        return AUTH_ADMIN;
534ab5d26daSAndreas Gohr    }
53585d03f68SAndreas Gohr
536e259aa79SAndreas Gohr    $ci = '';
537e259aa79SAndreas Gohr    if(!$auth->isCaseSensitive()) $ci = 'ui';
538d752aedeSAndreas Gohr
539d752aedeSAndreas Gohr    $user   = $auth->cleanUser($user);
540d752aedeSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
54185d03f68SAndreas Gohr    $user   = auth_nameencode($user);
54285d03f68SAndreas Gohr
5436c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
5442cd2db38Sandi    $cnt = count($groups);
5452cd2db38Sandi    for($i = 0; $i < $cnt; $i++) {
5466c2bb100SAndreas Gohr        $groups[$i] = '@'.auth_nameencode($groups[$i]);
54710a76f6fSfrank    }
54810a76f6fSfrank
549f3f0262cSandi    $ns   = getNS($id);
550f3f0262cSandi    $perm = -1;
551f3f0262cSandi
55234aeb4afSAndreas Gohr    if($user || count($groups)) {
553f3f0262cSandi        //add ALL group
554f3f0262cSandi        $groups[] = '@ALL';
555f3f0262cSandi        //add User
55634aeb4afSAndreas Gohr        if($user) $groups[] = $user;
557f3f0262cSandi    } else {
55848d7b7a6SDominik Eckelmann        $groups[] = '@ALL';
559f3f0262cSandi    }
560f3f0262cSandi
561f3f0262cSandi    //check exact match first
56248d7b7a6SDominik Eckelmann    $matches = preg_grep('/^'.preg_quote($id, '/').'\s+(\S+)\s+/'.$ci, $AUTH_ACL);
563f3f0262cSandi    if(count($matches)) {
564f3f0262cSandi        foreach($matches as $match) {
565f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
566f3f0262cSandi            $acl   = preg_split('/\s+/', $match);
56748d7b7a6SDominik Eckelmann            if(!in_array($acl[1], $groups)) {
56848d7b7a6SDominik Eckelmann                continue;
56948d7b7a6SDominik Eckelmann            }
5708ef6b7caSandi            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
571f3f0262cSandi            if($acl[2] > $perm) {
572f3f0262cSandi                $perm = $acl[2];
573f3f0262cSandi            }
574f3f0262cSandi        }
575f3f0262cSandi        if($perm > -1) {
576f3f0262cSandi            //we had a match - return it
577f3f0262cSandi            return $perm;
578f3f0262cSandi        }
579f3f0262cSandi    }
580f3f0262cSandi
581f3f0262cSandi    //still here? do the namespace checks
582f3f0262cSandi    if($ns) {
5833e304b55SMichael Hamann        $path = $ns.':*';
584f3f0262cSandi    } else {
5853e304b55SMichael Hamann        $path = '*'; //root document
586f3f0262cSandi    }
587f3f0262cSandi
588f3f0262cSandi    do {
58948d7b7a6SDominik Eckelmann        $matches = preg_grep('/^'.preg_quote($path, '/').'\s+(\S+)\s+/'.$ci, $AUTH_ACL);
590f3f0262cSandi        if(count($matches)) {
591f3f0262cSandi            foreach($matches as $match) {
592f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
593f3f0262cSandi                $acl   = preg_split('/\s+/', $match);
59448d7b7a6SDominik Eckelmann                if(!in_array($acl[1], $groups)) {
59548d7b7a6SDominik Eckelmann                    continue;
59648d7b7a6SDominik Eckelmann                }
5978ef6b7caSandi                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
598f3f0262cSandi                if($acl[2] > $perm) {
599f3f0262cSandi                    $perm = $acl[2];
600f3f0262cSandi                }
601f3f0262cSandi            }
602f3f0262cSandi            //we had a match - return it
60348d7b7a6SDominik Eckelmann            if($perm != -1) {
604f3f0262cSandi                return $perm;
605f3f0262cSandi            }
60648d7b7a6SDominik Eckelmann        }
607f3f0262cSandi        //get next higher namespace
608f3f0262cSandi        $ns = getNS($ns);
609f3f0262cSandi
6103e304b55SMichael Hamann        if($path != '*') {
6113e304b55SMichael Hamann            $path = $ns.':*';
6123e304b55SMichael Hamann            if($path == ':*') $path = '*';
613f3f0262cSandi        } else {
614f3f0262cSandi            //we did this already
615f3f0262cSandi            //looks like there is something wrong with the ACL
616f3f0262cSandi            //break here
617d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
618d5ce66f6SAndreas Gohr            return AUTH_NONE;
619f3f0262cSandi        }
620f3f0262cSandi    } while(1); //this should never loop endless
621ab5d26daSAndreas Gohr    return AUTH_NONE;
622f3f0262cSandi}
623f3f0262cSandi
624f3f0262cSandi/**
6256c2bb100SAndreas Gohr * Encode ASCII special chars
6266c2bb100SAndreas Gohr *
6276c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
6286c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
6296c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
6306c2bb100SAndreas Gohr * urlencoding!).
6316c2bb100SAndreas Gohr *
6326c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
6336c2bb100SAndreas Gohr *
6346c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
6356c2bb100SAndreas Gohr * @see rawurldecode()
6366c2bb100SAndreas Gohr */
637e838fc2eSAndreas Gohrfunction auth_nameencode($name, $skip_group = false) {
638a424cd8eSchris    global $cache_authname;
639a424cd8eSchris    $cache =& $cache_authname;
64031784267SAndreas Gohr    $name  = (string) $name;
641a424cd8eSchris
64280601d26SAndreas Gohr    // never encode wildcard FS#1955
64380601d26SAndreas Gohr    if($name == '%USER%') return $name;
644b78bf706Sromain    if($name == '%GROUP%') return $name;
64580601d26SAndreas Gohr
646a424cd8eSchris    if(!isset($cache[$name][$skip_group])) {
647e838fc2eSAndreas Gohr        if($skip_group && $name{0} == '@') {
648ab5d26daSAndreas Gohr            $cache[$name][$skip_group] = '@'.preg_replace(
649ab5d26daSAndreas Gohr                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
650ab5d26daSAndreas Gohr                "'%'.dechex(ord(substr('\\1',-1)))", substr($name, 1)
651ab5d26daSAndreas Gohr            );
652e838fc2eSAndreas Gohr        } else {
653ab5d26daSAndreas Gohr            $cache[$name][$skip_group] = preg_replace(
654ab5d26daSAndreas Gohr                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
655ab5d26daSAndreas Gohr                "'%'.dechex(ord(substr('\\1',-1)))", $name
656ab5d26daSAndreas Gohr            );
657e838fc2eSAndreas Gohr        }
6586c2bb100SAndreas Gohr    }
6596c2bb100SAndreas Gohr
660a424cd8eSchris    return $cache[$name][$skip_group];
661a424cd8eSchris}
662a424cd8eSchris
6636c2bb100SAndreas Gohr/**
664f3f0262cSandi * Create a pronouncable password
665f3f0262cSandi *
66615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
66715fae107Sandi * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
66815fae107Sandi *
66915fae107Sandi * @return string  pronouncable password
670f3f0262cSandi */
671f3f0262cSandifunction auth_pwgen() {
672f3f0262cSandi    $pw = '';
673f3f0262cSandi    $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
674f3f0262cSandi    $v  = 'aeiou'; //vowels
675f3f0262cSandi    $a  = $c.$v; //both
676f3f0262cSandi
677f3f0262cSandi    //use two syllables...
678f3f0262cSandi    for($i = 0; $i < 2; $i++) {
679f3f0262cSandi        $pw .= $c[rand(0, strlen($c) - 1)];
680f3f0262cSandi        $pw .= $v[rand(0, strlen($v) - 1)];
681f3f0262cSandi        $pw .= $a[rand(0, strlen($a) - 1)];
682f3f0262cSandi    }
683f3f0262cSandi    //... and add a nice number
684f3f0262cSandi    $pw .= rand(10, 99);
685f3f0262cSandi
686f3f0262cSandi    return $pw;
687f3f0262cSandi}
688f3f0262cSandi
689f3f0262cSandi/**
690f3f0262cSandi * Sends a password to the given user
691f3f0262cSandi *
69215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
693ab5d26daSAndreas Gohr * @param string $user Login name of the user
694ab5d26daSAndreas Gohr * @param string $password The new password in clear text
69515fae107Sandi * @return bool  true on success
696f3f0262cSandi */
697f3f0262cSandifunction auth_sendPassword($user, $password) {
698f3f0262cSandi    global $lang;
699ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
700cd52f92dSchris    global $auth;
701beca106aSAdrian Lang    if(!$auth) return false;
702cd52f92dSchris
703d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
704cd52f92dSchris    $userinfo = $auth->getUserData($user);
705f3f0262cSandi
70687ddda95Sandi    if(!$userinfo['mail']) return false;
707f3f0262cSandi
708f3f0262cSandi    $text = rawLocale('password');
709d7169d19SAndreas Gohr    $trep = array(
710d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
711d7169d19SAndreas Gohr        'LOGIN'    => $user,
712d7169d19SAndreas Gohr        'PASSWORD' => $password
713d7169d19SAndreas Gohr    );
714f3f0262cSandi
715d7169d19SAndreas Gohr    $mail = new Mailer();
716d7169d19SAndreas Gohr    $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
717d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
718d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
719d7169d19SAndreas Gohr    return $mail->send();
720f3f0262cSandi}
721f3f0262cSandi
722f3f0262cSandi/**
72315fae107Sandi * Register a new user
724f3f0262cSandi *
72515fae107Sandi * This registers a new user - Data is read directly from $_POST
72615fae107Sandi *
72715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
72815fae107Sandi * @return bool  true on success, false on any error
729f3f0262cSandi */
730f3f0262cSandifunction register() {
731f3f0262cSandi    global $lang;
732eb5d07e4Sjan    global $conf;
733ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
734cd52f92dSchris    global $auth;
735f3f0262cSandi
736f3f0262cSandi    if(!$_POST['save']) return false;
7373a48618aSAnika Henke    if(!actionOK('register')) return false;
738640145a5Sandi
739f3f0262cSandi    //clean username
740d752aedeSAndreas Gohr    $_POST['login'] = trim($auth->cleanUser($_POST['login']));
741d752aedeSAndreas Gohr
742f3f0262cSandi    //clean fullname and email
74354f0e6eaSAndreas Gohr    $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $_POST['fullname']));
74454f0e6eaSAndreas Gohr    $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $_POST['email']));
745f3f0262cSandi
746f3f0262cSandi    if(empty($_POST['login']) ||
747f3f0262cSandi        empty($_POST['fullname']) ||
748ab5d26daSAndreas Gohr        empty($_POST['email'])
749ab5d26daSAndreas Gohr    ) {
750f3f0262cSandi        msg($lang['regmissing'], -1);
751f3f0262cSandi        return false;
752f3f0262cSandi    }
753f3f0262cSandi
754cab2716aSmatthias.grimm    if($conf['autopasswd']) {
755cab2716aSmatthias.grimm        $pass = auth_pwgen(); // automatically generate password
756cab2716aSmatthias.grimm    } elseif(empty($_POST['pass']) ||
757ab5d26daSAndreas Gohr        empty($_POST['passchk'])
758ab5d26daSAndreas Gohr    ) {
759bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
760cab2716aSmatthias.grimm        return false;
761cab2716aSmatthias.grimm    } elseif($_POST['pass'] != $_POST['passchk']) {
762bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
763cab2716aSmatthias.grimm        return false;
764cab2716aSmatthias.grimm    } else {
765cab2716aSmatthias.grimm        $pass = $_POST['pass']; // accept checked and valid password
766cab2716aSmatthias.grimm    }
767cab2716aSmatthias.grimm
768f3f0262cSandi    //check mail
76944f669e9Sandi    if(!mail_isvalid($_POST['email'])) {
770f3f0262cSandi        msg($lang['regbadmail'], -1);
771f3f0262cSandi        return false;
772f3f0262cSandi    }
773f3f0262cSandi
774f3f0262cSandi    //okay try to create the user
7757d3c8d42SGabriel Birke    if(!$auth->triggerUserMod('create', array($_POST['login'], $pass, $_POST['fullname'], $_POST['email']))) {
776f3f0262cSandi        msg($lang['reguexists'], -1);
777f3f0262cSandi        return false;
778f3f0262cSandi    }
779f3f0262cSandi
78002a498e7Schris    // create substitutions for use in notification email
78102a498e7Schris    $substitutions = array(
78202a498e7Schris        'NEWUSER'  => $_POST['login'],
78302a498e7Schris        'NEWNAME'  => $_POST['fullname'],
78402a498e7Schris        'NEWEMAIL' => $_POST['email'],
78502a498e7Schris    );
78602a498e7Schris
787cab2716aSmatthias.grimm    if(!$conf['autopasswd']) {
788cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
78902a498e7Schris        notify('', 'register', '', $_POST['login'], false, $substitutions);
790cab2716aSmatthias.grimm        return true;
791cab2716aSmatthias.grimm    }
792cab2716aSmatthias.grimm
793cab2716aSmatthias.grimm    // autogenerated password? then send him the password
794f3f0262cSandi    if(auth_sendPassword($_POST['login'], $pass)) {
795f3f0262cSandi        msg($lang['regsuccess'], 1);
79602a498e7Schris        notify('', 'register', '', $_POST['login'], false, $substitutions);
797f3f0262cSandi        return true;
798f3f0262cSandi    } else {
799f3f0262cSandi        msg($lang['regmailfail'], -1);
800f3f0262cSandi        return false;
801f3f0262cSandi    }
802f3f0262cSandi}
803f3f0262cSandi
80410a76f6fSfrank/**
8058b06d178Schris * Update user profile
8068b06d178Schris *
8078b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
8088b06d178Schris */
8098b06d178Schrisfunction updateprofile() {
8108b06d178Schris    global $conf;
8118b06d178Schris    global $lang;
812ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
813cd52f92dSchris    global $auth;
814bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
815bcc94b2cSAndreas Gohr    global $INPUT;
8168b06d178Schris
817bcc94b2cSAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
8181b2a85e8SAndreas Gohr    if(!checkSecurityToken()) return false;
8198b06d178Schris
8203a48618aSAnika Henke    if(!actionOK('profile')) {
8218b06d178Schris        msg($lang['profna'], -1);
8228b06d178Schris        return false;
8238b06d178Schris    }
8248b06d178Schris
825bcc94b2cSAndreas Gohr    $changes         = array();
826bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
827bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
828bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
829bcc94b2cSAndreas Gohr
830bcc94b2cSAndreas Gohr    // check misspelled passwords
831bcc94b2cSAndreas Gohr    if($changes['pass'] != $INPUT->post->str('passchk')) {
832bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
8338b06d178Schris        return false;
8348b06d178Schris    }
8358b06d178Schris
8368b06d178Schris    // clean fullname and email
837bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
838bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
8398b06d178Schris
840bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
841bcc94b2cSAndreas Gohr    if((empty($changes['name']) && $auth->canDo('modName')) ||
842bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
843ab5d26daSAndreas Gohr    ) {
8448b06d178Schris        msg($lang['profnoempty'], -1);
8458b06d178Schris        return false;
8468b06d178Schris    }
847bcc94b2cSAndreas Gohr    if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
8488b06d178Schris        msg($lang['regbadmail'], -1);
8498b06d178Schris        return false;
8508b06d178Schris    }
8518b06d178Schris
852bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
8534c21b7eeSAndreas Gohr
854bcc94b2cSAndreas Gohr    // check for unavailable capabilities
855bcc94b2cSAndreas Gohr    if(!$auth->canDo('modName')) unset($changes['name']);
856bcc94b2cSAndreas Gohr    if(!$auth->canDo('modMail')) unset($changes['mail']);
857bcc94b2cSAndreas Gohr    if(!$auth->canDo('modPass')) unset($changes['pass']);
858bcc94b2cSAndreas Gohr
859bcc94b2cSAndreas Gohr    // anything to do?
8608b06d178Schris    if(!count($changes)) {
8618b06d178Schris        msg($lang['profnochange'], -1);
8628b06d178Schris        return false;
8638b06d178Schris    }
8648b06d178Schris
8658b06d178Schris    if($conf['profileconfirm']) {
866bcc94b2cSAndreas Gohr        if(!$auth->checkPass($_SERVER['REMOTE_USER'], $INPUT->post->str('oldpass'))) {
8678b06d178Schris            msg($lang['badlogin'], -1);
8688b06d178Schris            return false;
8698b06d178Schris        }
8708b06d178Schris    }
8718b06d178Schris
872a0b5b007SChris Smith    if($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
873a0b5b007SChris Smith        // update cookie and session with the changed data
87432ed2b36SAndreas Gohr        if($changes['pass']) {
875ab5d26daSAndreas Gohr            list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
87632ed2b36SAndreas Gohr            $pass = PMA_blowfish_encrypt($changes['pass'], auth_cookiesalt(!$sticky));
877a0b5b007SChris Smith            auth_setCookie($_SERVER['REMOTE_USER'], $pass, (bool) $sticky);
87832ed2b36SAndreas Gohr        }
87925b2a98cSMichael Klier        return true;
880a0b5b007SChris Smith    }
881ab5d26daSAndreas Gohr
882ab5d26daSAndreas Gohr    return false;
8838b06d178Schris}
8848b06d178Schris
8858b06d178Schris/**
8868b06d178Schris * Send a  new password
8878b06d178Schris *
8881d5856cfSAndreas Gohr * This function handles both phases of the password reset:
8891d5856cfSAndreas Gohr *
8901d5856cfSAndreas Gohr *   - handling the first request of password reset
8911d5856cfSAndreas Gohr *   - validating the password reset auth token
8921d5856cfSAndreas Gohr *
8938b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
8948b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
8951d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
8968b06d178Schris *
8978b06d178Schris * @return bool true on success, false on any error
8988b06d178Schris */
8998b06d178Schrisfunction act_resendpwd() {
9008b06d178Schris    global $lang;
9018b06d178Schris    global $conf;
902ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
903cd52f92dSchris    global $auth;
904bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
905bcc94b2cSAndreas Gohr    global $INPUT;
9068b06d178Schris
9073a48618aSAnika Henke    if(!actionOK('resendpwd')) {
9088b06d178Schris        msg($lang['resendna'], -1);
9098b06d178Schris        return false;
9108b06d178Schris    }
9118b06d178Schris
912bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
9138b06d178Schris
9141d5856cfSAndreas Gohr    if($token) {
915cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
9161d5856cfSAndreas Gohr
9171d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
9181d5856cfSAndreas Gohr        if(!@file_exists($tfile)) {
9191d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
920bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
9211d5856cfSAndreas Gohr            return false;
9221d5856cfSAndreas Gohr        }
9238a9735e3SAndreas Gohr        // token is only valid for 3 days
9248a9735e3SAndreas Gohr        if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
9258a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
926bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
9271d5856cfSAndreas Gohr            @unlink($tfile);
9288a9735e3SAndreas Gohr            return false;
9298a9735e3SAndreas Gohr        }
9308a9735e3SAndreas Gohr
9318b06d178Schris        $user     = io_readfile($tfile);
932cd52f92dSchris        $userinfo = $auth->getUserData($user);
9338b06d178Schris        if(!$userinfo['mail']) {
9348b06d178Schris            msg($lang['resendpwdnouser'], -1);
9358b06d178Schris            return false;
9368b06d178Schris        }
9378b06d178Schris
938cc204bbdSAndreas Gohr        if(!$conf['autopasswd']) { // we let the user choose a password
939bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
940bcc94b2cSAndreas Gohr
941cc204bbdSAndreas Gohr            // password given correctly?
942bcc94b2cSAndreas Gohr            if(!$pass) return false;
943bcc94b2cSAndreas Gohr            if($pass != $INPUT->str('passchk')) {
944451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
945cc204bbdSAndreas Gohr                return false;
946cc204bbdSAndreas Gohr            }
947cc204bbdSAndreas Gohr
948bcc94b2cSAndreas Gohr            // change it
949cc204bbdSAndreas Gohr            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
950cc204bbdSAndreas Gohr                msg('error modifying user data', -1);
951cc204bbdSAndreas Gohr                return false;
952cc204bbdSAndreas Gohr            }
953cc204bbdSAndreas Gohr
954cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
955cc204bbdSAndreas Gohr
9568b06d178Schris            $pass = auth_pwgen();
9577d3c8d42SGabriel Birke            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
9588b06d178Schris                msg('error modifying user data', -1);
9598b06d178Schris                return false;
9608b06d178Schris            }
9618b06d178Schris
9628b06d178Schris            if(auth_sendPassword($user, $pass)) {
9638b06d178Schris                msg($lang['resendpwdsuccess'], 1);
9648b06d178Schris            } else {
9658b06d178Schris                msg($lang['regmailfail'], -1);
9668b06d178Schris            }
967cc204bbdSAndreas Gohr        }
968cc204bbdSAndreas Gohr
969cc204bbdSAndreas Gohr        @unlink($tfile);
9708b06d178Schris        return true;
9711d5856cfSAndreas Gohr
9721d5856cfSAndreas Gohr    } else {
9731d5856cfSAndreas Gohr        // we're in request phase
9741d5856cfSAndreas Gohr
975bcc94b2cSAndreas Gohr        if(!$INPUT->post->bool('save')) return false;
9761d5856cfSAndreas Gohr
977bcc94b2cSAndreas Gohr        if(!$INPUT->post->str('login')) {
9781d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
9791d5856cfSAndreas Gohr            return false;
9801d5856cfSAndreas Gohr        } else {
981bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
9821d5856cfSAndreas Gohr        }
9831d5856cfSAndreas Gohr
9841d5856cfSAndreas Gohr        $userinfo = $auth->getUserData($user);
9851d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
9861d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
9871d5856cfSAndreas Gohr            return false;
9881d5856cfSAndreas Gohr        }
9891d5856cfSAndreas Gohr
9901d5856cfSAndreas Gohr        // generate auth token
9911d5856cfSAndreas Gohr        $token = md5(auth_cookiesalt().$user); //secret but user based
9921d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
9931d5856cfSAndreas Gohr        $url   = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
9941d5856cfSAndreas Gohr
9951d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
9961d5856cfSAndreas Gohr
9971d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
998d7169d19SAndreas Gohr        $trep = array(
999d7169d19SAndreas Gohr            'FULLNAME' => $userinfo['name'],
1000d7169d19SAndreas Gohr            'LOGIN'    => $user,
1001d7169d19SAndreas Gohr            'CONFIRM'  => $url
1002d7169d19SAndreas Gohr        );
10031d5856cfSAndreas Gohr
1004d7169d19SAndreas Gohr        $mail = new Mailer();
1005d7169d19SAndreas Gohr        $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1006d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
1007d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
1008d7169d19SAndreas Gohr        if($mail->send()) {
10091d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
10101d5856cfSAndreas Gohr        } else {
10111d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
10121d5856cfSAndreas Gohr        }
10131d5856cfSAndreas Gohr        return true;
10141d5856cfSAndreas Gohr    }
1015ab5d26daSAndreas Gohr    // never reached
10168b06d178Schris}
10178b06d178Schris
10188b06d178Schris/**
1019b0855b11Sandi * Encrypts a password using the given method and salt
1020b0855b11Sandi *
1021b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1022b0855b11Sandi * is chosen.
1023b0855b11Sandi *
1024b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
1025ab5d26daSAndreas Gohr * @param string $clear The clear text password
1026ab5d26daSAndreas Gohr * @param string $method The hashing method
1027ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1028b0855b11Sandi * @return  string  The crypted password
1029b0855b11Sandi */
1030577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null) {
1031b0855b11Sandi    global $conf;
1032b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
103310a76f6fSfrank
10343a0a2d05SAndreas Gohr    $pass = new PassHash();
10353a0a2d05SAndreas Gohr    $call = 'hash_'.$method;
1036b0855b11Sandi
10373a0a2d05SAndreas Gohr    if(!method_exists($pass, $call)) {
1038b0855b11Sandi        msg("Unsupported crypt method $method", -1);
10393a0a2d05SAndreas Gohr        return false;
1040b0855b11Sandi    }
10413a0a2d05SAndreas Gohr
10423a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1043b0855b11Sandi}
1044b0855b11Sandi
1045b0855b11Sandi/**
1046b0855b11Sandi * Verifies a cleartext password against a crypted hash
1047b0855b11Sandi *
1048b0855b11Sandi * @author Andreas Gohr <andi@splitbrain.org>
1049ab5d26daSAndreas Gohr * @param  string $clear The clear text password
1050ab5d26daSAndreas Gohr * @param  string $crypt The hash to compare with
1051ab5d26daSAndreas Gohr * @return bool true if both match
1052b0855b11Sandi */
1053b0855b11Sandifunction auth_verifyPassword($clear, $crypt) {
10543a0a2d05SAndreas Gohr    $pass = new PassHash();
10553a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1056b0855b11Sandi}
1057340756e4Sandi
1058a0b5b007SChris Smith/**
1059a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1060a0b5b007SChris Smith *
1061a0b5b007SChris Smith * @param string  $user       username
1062a0b5b007SChris Smith * @param string  $pass       encrypted password
1063a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1064ab5d26daSAndreas Gohr * @return bool
1065a0b5b007SChris Smith */
1066a0b5b007SChris Smithfunction auth_setCookie($user, $pass, $sticky) {
1067a0b5b007SChris Smith    global $conf;
1068ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
1069a0b5b007SChris Smith    global $auth;
107079d00841SOliver Geisen    global $USERINFO;
1071a0b5b007SChris Smith
1072beca106aSAdrian Lang    if(!$auth) return false;
1073a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1074a0b5b007SChris Smith
1075a0b5b007SChris Smith    // set cookie
1076645c0a36SAndreas Gohr    $cookie    = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
107773ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1078c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1079a0b5b007SChris Smith    if(version_compare(PHP_VERSION, '5.2.0', '>')) {
108073ab87deSGabriel Birke        setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
1081a0b5b007SChris Smith    } else {
108273ab87deSGabriel Birke        setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
1083a0b5b007SChris Smith    }
1084a0b5b007SChris Smith    // set session
1085a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1086234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1087a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1088a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1089a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1090ab5d26daSAndreas Gohr
1091ab5d26daSAndreas Gohr    return true;
1092a0b5b007SChris Smith}
1093a0b5b007SChris Smith
1094645c0a36SAndreas Gohr/**
1095645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1096645c0a36SAndreas Gohr *
1097645c0a36SAndreas Gohr * @returns array
1098645c0a36SAndreas Gohr */
1099645c0a36SAndreas Gohrfunction auth_getCookie() {
1100c66972f2SAdrian Lang    if(!isset($_COOKIE[DOKU_COOKIE])) {
1101c66972f2SAdrian Lang        return array(null, null, null);
1102c66972f2SAdrian Lang    }
1103645c0a36SAndreas Gohr    list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
1104645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1105645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1106645c0a36SAndreas Gohr    $user   = base64_decode($user);
1107645c0a36SAndreas Gohr    return array($user, $sticky, $pass);
1108645c0a36SAndreas Gohr}
1109645c0a36SAndreas Gohr
1110e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1111