xref: /dokuwiki/inc/auth.php (revision 98e31f853f43d94c5bd1d3ab79388c44ce29ce0a)
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;
3793a7873eSAndreas Gohr    /* @var DokuWiki_Auth_Plugin $auth */
3803c4aec3Schris    global $auth;
39bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
40bcc94b2cSAndreas Gohr    global $INPUT;
419a9714acSDominik Eckelmann    global $AUTH_ACL;
429a9714acSDominik Eckelmann    global $lang;
43c8f80b4eSAndreas Gohr    global $config_cascade;
449c29eea5SJan Schumann    global $plugin_controller;
459a9714acSDominik Eckelmann    $AUTH_ACL = array();
4603c4aec3Schris
4716905344SAndreas Gohr    if(!$conf['useacl']) return false;
4816905344SAndreas Gohr
499c29eea5SJan Schumann    // try to load auth backend from plugins
509c29eea5SJan Schumann    foreach ($plugin_controller->getList('auth') as $plugin) {
519c29eea5SJan Schumann      if ($conf['authtype'] === $plugin) {
52f4476bd9SJan Schumann        $auth = $plugin_controller->load('auth', $plugin);
539c29eea5SJan Schumann        break;
54e71b0ef7SGuy Brand      } elseif ('auth' . $conf['authtype'] === $plugin) {
55e71b0ef7SGuy Brand        // matches old auth backends (pre-Weatherwax)
56e71b0ef7SGuy Brand        $auth = $plugin_controller->load('auth', $plugin);
57*98e31f85SKlap-in        msg('Your authtype setting is deprecated. You must set $conf[\'authtype\'] = ' . "auth" . $conf['authtype']
58*98e31f85SKlap-in             . ' in your configuration (see <a href="https://www.dokuwiki.org/auth">Authentication Backends</a>)',-1,'','',MSG_ADMINS_ONLY);
599c29eea5SJan Schumann      }
609c29eea5SJan Schumann    }
618b06d178Schris
626416b708SMichael Hamann	if(!isset($auth) || !$auth){
633094e817SAndreas Gohr        msg($lang['authtempfail'], -1);
643094e817SAndreas Gohr        return false;
653094e817SAndreas Gohr    }
668b06d178Schris
676416b708SMichael Hamann    if ($auth->success == false) {
680f4f4adfSAndreas Gohr		// degrade to unauthenticated user
69d2dde4ebSMatthias Grimm	    unset($auth);
700f4f4adfSAndreas Gohr	    auth_logoff();
71cd52f92dSchris	    msg($lang['authtempfail'], -1);
726416b708SMichael Hamann        return false;
73d2dde4ebSMatthias Grimm	}
7416905344SAndreas Gohr
7516905344SAndreas Gohr    // do the login either by cookie or provided credentials XXX
76bcc94b2cSAndreas Gohr    $INPUT->set('http_credentials', false);
77bcc94b2cSAndreas Gohr    if(!$conf['rememberme']) $INPUT->set('r', false);
78bbbd6568SAndreas Gohr
79b2665af7SMichael Hamann    // handle renamed HTTP_AUTHORIZATION variable (can happen when a fix like
80b2665af7SMichael Hamann    // the one presented at
81b2665af7SMichael Hamann    // http://www.besthostratings.com/articles/http-auth-php-cgi.html is used
82b2665af7SMichael Hamann    // for enabling HTTP authentication with CGI/SuExec)
83b2665af7SMichael Hamann    if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
84b2665af7SMichael Hamann        $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
85528ddc7cSAndreas Gohr    // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
8606156f3cSAndreas Gohr    if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
87528ddc7cSAndreas Gohr        list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
88528ddc7cSAndreas Gohr            explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
89528ddc7cSAndreas Gohr    }
90528ddc7cSAndreas Gohr
911e8c9c90SAndreas Gohr    // if no credentials were given try to use HTTP auth (for SSO)
92bcc94b2cSAndreas Gohr    if(!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])) {
93bcc94b2cSAndreas Gohr        $INPUT->set('u', $_SERVER['PHP_AUTH_USER']);
94bcc94b2cSAndreas Gohr        $INPUT->set('p', $_SERVER['PHP_AUTH_PW']);
95bcc94b2cSAndreas Gohr        $INPUT->set('http_credentials', true);
961e8c9c90SAndreas Gohr    }
971e8c9c90SAndreas Gohr
98191bb90aSAndreas Gohr    // apply cleaning
9993a7873eSAndreas Gohr    if (true === $auth->success) {
10000d58927SMichael Hamann        $INPUT->set('u', $auth->cleanUser($INPUT->str('u')));
101f4476bd9SJan Schumann    }
102191bb90aSAndreas Gohr
103bcc94b2cSAndreas Gohr    if($INPUT->str('authtok')) {
104f13fa892SAndreas Gohr        // when an authentication token is given, trust the session
105bcc94b2cSAndreas Gohr        auth_validateToken($INPUT->str('authtok'));
106f13fa892SAndreas Gohr    } elseif(!is_null($auth) && $auth->canDo('external')) {
107f13fa892SAndreas Gohr        // external trust mechanism in place
108bcc94b2cSAndreas Gohr        $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
109f5cb575dSAndreas Gohr    } else {
1106080c584SRobin Gareus        $evdata = array(
111bcc94b2cSAndreas Gohr            'user'     => $INPUT->str('u'),
112bcc94b2cSAndreas Gohr            'password' => $INPUT->str('p'),
113bcc94b2cSAndreas Gohr            'sticky'   => $INPUT->bool('r'),
114bcc94b2cSAndreas Gohr            'silent'   => $INPUT->bool('http_credentials')
1156080c584SRobin Gareus        );
116b5ee21aaSAdrian Lang        trigger_event('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
117f5cb575dSAndreas Gohr    }
118f5cb575dSAndreas Gohr
11916905344SAndreas Gohr    //load ACL into a global array XXX
12075c93b77SAndreas Gohr    $AUTH_ACL = auth_loadACL();
121ab5d26daSAndreas Gohr
122ab5d26daSAndreas Gohr    return true;
12375c93b77SAndreas Gohr}
12475c93b77SAndreas Gohr
12575c93b77SAndreas Gohr/**
12675c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards
12775c93b77SAndreas Gohr *
12875c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
129ab5d26daSAndreas Gohr * @return array
13075c93b77SAndreas Gohr */
13175c93b77SAndreas Gohrfunction auth_loadACL() {
13275c93b77SAndreas Gohr    global $config_cascade;
133b78bf706Sromain    global $USERINFO;
13475c93b77SAndreas Gohr
13575c93b77SAndreas Gohr    if(!is_readable($config_cascade['acl']['default'])) return array();
13675c93b77SAndreas Gohr
13775c93b77SAndreas Gohr    $acl = file($config_cascade['acl']['default']);
13875c93b77SAndreas Gohr
139191bb90aSAndreas Gohr    //support user wildcard
14032e82180SAndreas Gohr    $out = array();
1419ce556d2SAndreas Gohr    foreach($acl as $line) {
1429ce556d2SAndreas Gohr        $line = trim($line);
1439ce556d2SAndreas Gohr        if($line{0} == '#') continue;
1449ce556d2SAndreas Gohr        list($id,$rest) = preg_split('/\s+/',$line,2);
14532e82180SAndreas Gohr
1469ce556d2SAndreas Gohr        if(strstr($line, '%GROUP%')){
1479ce556d2SAndreas Gohr            foreach((array) $USERINFO['grps'] as $grp){
148b78bf706Sromain                $nid   = str_replace('%GROUP%',cleanID($grp),$id);
14932e82180SAndreas Gohr                $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest);
15032e82180SAndreas Gohr                $out[] = "$nid\t$nrest";
151b78bf706Sromain            }
15232e82180SAndreas Gohr        } else {
15375c93b77SAndreas Gohr            $id   = str_replace('%USER%',cleanID($_SERVER['REMOTE_USER']),$id);
15475c93b77SAndreas Gohr            $rest = str_replace('%USER%',auth_nameencode($_SERVER['REMOTE_USER']),$rest);
15532e82180SAndreas Gohr            $out[] = "$id\t$rest";
156a8fe108bSGuy Brand        }
15711799630Sandi    }
1589ce556d2SAndreas Gohr
15932e82180SAndreas Gohr    return $out;
160f3f0262cSandi}
161f3f0262cSandi
162ab5d26daSAndreas Gohr/**
163ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK
164ab5d26daSAndreas Gohr *
165ab5d26daSAndreas Gohr * @param $evdata
166ab5d26daSAndreas Gohr * @return bool
167ab5d26daSAndreas Gohr */
168b5ee21aaSAdrian Langfunction auth_login_wrapper($evdata) {
169ab5d26daSAndreas Gohr    return auth_login(
170ab5d26daSAndreas Gohr        $evdata['user'],
171b5ee21aaSAdrian Lang        $evdata['password'],
172b5ee21aaSAdrian Lang        $evdata['sticky'],
173ab5d26daSAndreas Gohr        $evdata['silent']
174ab5d26daSAndreas Gohr    );
175b5ee21aaSAdrian Lang}
176b5ee21aaSAdrian Lang
177f3f0262cSandi/**
178f3f0262cSandi * This tries to login the user based on the sent auth credentials
179f3f0262cSandi *
180f3f0262cSandi * The authentication works like this: if a username was given
18115fae107Sandi * a new login is assumed and user/password are checked. If they
18215fae107Sandi * are correct the password is encrypted with blowfish and stored
18315fae107Sandi * together with the username in a cookie - the same info is stored
18415fae107Sandi * in the session, too. Additonally a browserID is stored in the
18515fae107Sandi * session.
18615fae107Sandi *
18715fae107Sandi * If no username was given the cookie is checked: if the username,
18815fae107Sandi * crypted password and browserID match between session and cookie
18915fae107Sandi * no further testing is done and the user is accepted
19015fae107Sandi *
19115fae107Sandi * If a cookie was found but no session info was availabe the
192136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
19315fae107Sandi * together with username rechecked by calling this function again.
194f3f0262cSandi *
195f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
196f3f0262cSandi * are set.
19715fae107Sandi *
19815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
19915fae107Sandi *
20015fae107Sandi * @param   string  $user    Username
20115fae107Sandi * @param   string  $pass    Cleartext Password
20215fae107Sandi * @param   bool    $sticky  Cookie should not expire
203f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
20415fae107Sandi * @return  bool             true on successful auth
205f3f0262cSandi */
206f112c2faSAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false) {
207f3f0262cSandi    global $USERINFO;
208f3f0262cSandi    global $conf;
209f3f0262cSandi    global $lang;
210ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
211cd52f92dSchris    global $auth;
212ab5d26daSAndreas Gohr
213132bdbfeSandi    $sticky ? $sticky = true : $sticky = false; //sanity check
214f3f0262cSandi
215beca106aSAdrian Lang    if(!$auth) return false;
216beca106aSAdrian Lang
217bbbd6568SAndreas Gohr    if(!empty($user)) {
218132bdbfeSandi        //usual login
219cd52f92dSchris        if($auth->checkPass($user, $pass)) {
220132bdbfeSandi            // make logininfo globally available
221f3f0262cSandi            $_SERVER['REMOTE_USER'] = $user;
22232ed2b36SAndreas Gohr            $secret                 = auth_cookiesalt(!$sticky); //bind non-sticky to session
223e940aea4SAndreas Gohr            auth_setCookie($user, PMA_blowfish_encrypt($pass, $secret), $sticky);
224132bdbfeSandi            return true;
225f3f0262cSandi        } else {
226f3f0262cSandi            //invalid credentials - log off
227f112c2faSAndreas Gohr            if(!$silent) msg($lang['badlogin'], -1);
228f3f0262cSandi            auth_logoff();
229132bdbfeSandi            return false;
230f3f0262cSandi        }
231f3f0262cSandi    } else {
232132bdbfeSandi        // read cookie information
233645c0a36SAndreas Gohr        list($user, $sticky, $pass) = auth_getCookie();
234132bdbfeSandi        if($user && $pass) {
235132bdbfeSandi            // we got a cookie - see if we can trust it
236fa7c70ffSAdrian Lang
237fa7c70ffSAdrian Lang            // get session info
238fa7c70ffSAdrian Lang            $session = $_SESSION[DOKU_COOKIE]['auth'];
239132bdbfeSandi            if(isset($session) &&
2407172dbc0SAndreas Gohr                $auth->useSessionCache($user) &&
2414c989037SChris Smith                ($session['time'] >= time() - $conf['auth_security_timeout']) &&
242132bdbfeSandi                ($session['user'] == $user) &&
243234ce57eSAndreas Gohr                ($session['pass'] == sha1($pass)) && //still crypted
244ab5d26daSAndreas Gohr                ($session['buid'] == auth_browseruid())
245ab5d26daSAndreas Gohr            ) {
246234ce57eSAndreas Gohr
247132bdbfeSandi                // he has session, cookie and browser right - let him in
248132bdbfeSandi                $_SERVER['REMOTE_USER'] = $user;
249132bdbfeSandi                $USERINFO               = $session['info']; //FIXME move all references to session
250132bdbfeSandi                return true;
251132bdbfeSandi            }
252f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
25332ed2b36SAndreas Gohr            $secret = auth_cookiesalt(!$sticky); //bind non-sticky to session
254e940aea4SAndreas Gohr            $pass   = PMA_blowfish_decrypt($pass, $secret);
255f112c2faSAndreas Gohr            return auth_login($user, $pass, $sticky, true);
256132bdbfeSandi        }
257132bdbfeSandi    }
258f3f0262cSandi    //just to be sure
259883179a4SAndreas Gohr    auth_logoff(true);
260132bdbfeSandi    return false;
261f3f0262cSandi}
262132bdbfeSandi
263132bdbfeSandi/**
264f13fa892SAndreas Gohr * Checks if a given authentication token was stored in the session
265f13fa892SAndreas Gohr *
266f13fa892SAndreas Gohr * Will setup authentication data using data from the session if the
267f13fa892SAndreas Gohr * token is correct. Will exit with a 401 Status if not.
268f13fa892SAndreas Gohr *
269f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
270f13fa892SAndreas Gohr * @param  string $token The authentication token
271f13fa892SAndreas Gohr * @return boolean true (or will exit on failure)
272f13fa892SAndreas Gohr */
273f13fa892SAndreas Gohrfunction auth_validateToken($token) {
274f13fa892SAndreas Gohr    if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']) {
275f13fa892SAndreas Gohr        // bad token
2769d2e1be6SAndreas Gohr        http_status(401);
277f13fa892SAndreas Gohr        print 'Invalid auth token - maybe the session timed out';
278f13fa892SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
279f13fa892SAndreas Gohr        exit;
280f13fa892SAndreas Gohr    }
281f13fa892SAndreas Gohr    // still here? trust the session data
282f13fa892SAndreas Gohr    global $USERINFO;
283f13fa892SAndreas Gohr    $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
284f13fa892SAndreas Gohr    $USERINFO               = $_SESSION[DOKU_COOKIE]['auth']['info'];
285f13fa892SAndreas Gohr    return true;
286f13fa892SAndreas Gohr}
287f13fa892SAndreas Gohr
288f13fa892SAndreas Gohr/**
289f13fa892SAndreas Gohr * Create an auth token and store it in the session
290f13fa892SAndreas Gohr *
291f13fa892SAndreas Gohr * NOTE: this is completely unrelated to the getSecurityToken() function
292f13fa892SAndreas Gohr *
293f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
294f13fa892SAndreas Gohr * @return string The auth token
295f13fa892SAndreas Gohr */
296f13fa892SAndreas Gohrfunction auth_createToken() {
297f13fa892SAndreas Gohr    $token = md5(mt_rand());
29809c2d803SAndreas Gohr    @session_start(); // reopen the session if needed
299f13fa892SAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
30009c2d803SAndreas Gohr    session_write_close();
301f13fa892SAndreas Gohr    return $token;
302f13fa892SAndreas Gohr}
303f13fa892SAndreas Gohr
304f13fa892SAndreas Gohr/**
305136ce040Sandi * Builds a pseudo UID from browser and IP data
306132bdbfeSandi *
307132bdbfeSandi * This is neither unique nor unfakable - still it adds some
308136ce040Sandi * security. Using the first part of the IP makes sure
30980b4f376SAndreas Gohr * proxy farms like AOLs are still okay.
31015fae107Sandi *
31115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
31215fae107Sandi *
31315fae107Sandi * @return  string  a MD5 sum of various browser headers
314132bdbfeSandi */
315132bdbfeSandifunction auth_browseruid() {
3162f9daf16SAndreas Gohr    $ip  = clientIP(true);
317132bdbfeSandi    $uid = '';
318132bdbfeSandi    $uid .= $_SERVER['HTTP_USER_AGENT'];
319132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
320132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
3212f9daf16SAndreas Gohr    $uid .= substr($ip, 0, strpos($ip, '.'));
32280b4f376SAndreas Gohr    $uid = strtolower($uid);
323132bdbfeSandi    return md5($uid);
324132bdbfeSandi}
325132bdbfeSandi
326132bdbfeSandi/**
327132bdbfeSandi * Creates a random key to encrypt the password in cookies
32815fae107Sandi *
32915fae107Sandi * This function tries to read the password for encrypting
33098407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
33115fae107Sandi * if no such file is found a random key is created and
33215fae107Sandi * and stored in this file.
33315fae107Sandi *
33415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
33532ed2b36SAndreas Gohr * @param   bool $addsession if true, the sessionid is added to the salt
33615fae107Sandi * @return  string
337132bdbfeSandi */
33832ed2b36SAndreas Gohrfunction auth_cookiesalt($addsession = false) {
339132bdbfeSandi    global $conf;
34098407a7aSandi    $file = $conf['metadir'].'/_htcookiesalt';
341132bdbfeSandi    $salt = io_readFile($file);
342132bdbfeSandi    if(empty($salt)) {
343132bdbfeSandi        $salt = uniqid(rand(), true);
344132bdbfeSandi        io_saveFile($file, $salt);
345132bdbfeSandi    }
34632ed2b36SAndreas Gohr    if($addsession) {
34732ed2b36SAndreas Gohr        $salt .= session_id();
34832ed2b36SAndreas Gohr    }
349132bdbfeSandi    return $salt;
350f3f0262cSandi}
351f3f0262cSandi
352f3f0262cSandi/**
353883179a4SAndreas Gohr * Log out the current user
354883179a4SAndreas Gohr *
355f3f0262cSandi * This clears all authentication data and thus log the user
356883179a4SAndreas Gohr * off. It also clears session data.
35715fae107Sandi *
35815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
359883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
360f3f0262cSandi */
361883179a4SAndreas Gohrfunction auth_logoff($keepbc = false) {
362f3f0262cSandi    global $conf;
363f3f0262cSandi    global $USERINFO;
364ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
3655298a619SAndreas Gohr    global $auth;
36637065e65Sandi
367d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
368e9621d07SAndreas Gohr    @session_start();
369e9621d07SAndreas Gohr
370e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
371e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
372e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
373e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
374e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
375e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
376883179a4SAndreas Gohr    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
377e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
37837065e65Sandi    if(isset($_SERVER['REMOTE_USER']))
379f3f0262cSandi        unset($_SERVER['REMOTE_USER']);
380132bdbfeSandi    $USERINFO = null; //FIXME
381f5c6743cSAndreas Gohr
38273ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
383f5c6743cSAndreas Gohr    if(version_compare(PHP_VERSION, '5.2.0', '>')) {
38473ab87deSGabriel Birke        setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
385f5c6743cSAndreas Gohr    } else {
38673ab87deSGabriel Birke        setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
387f5c6743cSAndreas Gohr    }
3885298a619SAndreas Gohr
389880f62faSAndreas Gohr    if($auth) $auth->logOff();
390f3f0262cSandi}
391f3f0262cSandi
392f3f0262cSandi/**
393f8cc712eSAndreas Gohr * Check if a user is a manager
394f8cc712eSAndreas Gohr *
395f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
396f8cc712eSAndreas Gohr * user.
397f8cc712eSAndreas Gohr *
398f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
399f8cc712eSAndreas Gohr *
400f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
401f8cc712eSAndreas Gohr * @see    auth_isadmin
402ab5d26daSAndreas Gohr * @param  string $user       Username
403ab5d26daSAndreas Gohr * @param  array  $groups     List of groups the user is in
404ab5d26daSAndreas Gohr * @param  bool   $adminonly  when true checks if user is admin
405ab5d26daSAndreas Gohr * @return bool
406f8cc712eSAndreas Gohr */
407f8cc712eSAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false) {
408f8cc712eSAndreas Gohr    global $conf;
409f8cc712eSAndreas Gohr    global $USERINFO;
410ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
411d752aedeSAndreas Gohr    global $auth;
412f8cc712eSAndreas Gohr
413beca106aSAdrian Lang    if(!$auth) return false;
414c66972f2SAdrian Lang    if(is_null($user)) {
415c66972f2SAdrian Lang        if(!isset($_SERVER['REMOTE_USER'])) {
416c66972f2SAdrian Lang            return false;
417c66972f2SAdrian Lang        } else {
418c66972f2SAdrian Lang            $user = $_SERVER['REMOTE_USER'];
419c66972f2SAdrian Lang        }
420c66972f2SAdrian Lang    }
421d6dc956fSAndreas Gohr    if(is_null($groups)) {
422d6dc956fSAndreas Gohr        $groups = (array) $USERINFO['grps'];
423e259aa79SAndreas Gohr    }
424e259aa79SAndreas Gohr
425d6dc956fSAndreas Gohr    // check superuser match
426d6dc956fSAndreas Gohr    if(auth_isMember($conf['superuser'], $user, $groups)) return true;
427d6dc956fSAndreas Gohr    if($adminonly) return false;
428e259aa79SAndreas Gohr    // check managers
429d6dc956fSAndreas Gohr    if(auth_isMember($conf['manager'], $user, $groups)) return true;
43000ce12daSChris Smith
431f8cc712eSAndreas Gohr    return false;
432f8cc712eSAndreas Gohr}
433f8cc712eSAndreas Gohr
434f8cc712eSAndreas Gohr/**
435f8cc712eSAndreas Gohr * Check if a user is admin
436f8cc712eSAndreas Gohr *
437f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
438f8cc712eSAndreas Gohr *
439f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
440f8cc712eSAndreas Gohr *
441f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
442ab5d26daSAndreas Gohr * @see auth_ismanager()
443ab5d26daSAndreas Gohr * @param  string $user       Username
444ab5d26daSAndreas Gohr * @param  array  $groups     List of groups the user is in
445ab5d26daSAndreas Gohr * @return bool
446f8cc712eSAndreas Gohr */
447f8cc712eSAndreas Gohrfunction auth_isadmin($user = null, $groups = null) {
448f8cc712eSAndreas Gohr    return auth_ismanager($user, $groups, true);
449f8cc712eSAndreas Gohr}
450f8cc712eSAndreas Gohr
451d6dc956fSAndreas Gohr/**
452d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
453d6dc956fSAndreas Gohr * users and groups to determine membership status
454d6dc956fSAndreas Gohr *
455d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
456d6dc956fSAndreas Gohr *
457d6dc956fSAndreas Gohr * @param $memberlist string commaseparated list of allowed users and groups
458d6dc956fSAndreas Gohr * @param $user       string user to match against
459d6dc956fSAndreas Gohr * @param $groups     array  groups the user is member of
4605446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
461d6dc956fSAndreas Gohr */
462d6dc956fSAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups) {
463ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
464d6dc956fSAndreas Gohr    global $auth;
465d6dc956fSAndreas Gohr    if(!$auth) return false;
466d6dc956fSAndreas Gohr
467d6dc956fSAndreas Gohr    // clean user and groups
4684f56ecbfSAdrian Lang    if(!$auth->isCaseSensitive()) {
469d6dc956fSAndreas Gohr        $user   = utf8_strtolower($user);
470d6dc956fSAndreas Gohr        $groups = array_map('utf8_strtolower', $groups);
471d6dc956fSAndreas Gohr    }
472d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
473d6dc956fSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), $groups);
474d6dc956fSAndreas Gohr
475d6dc956fSAndreas Gohr    // extract the memberlist
476d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
477d6dc956fSAndreas Gohr    $members = array_map('trim', $members);
478d6dc956fSAndreas Gohr    $members = array_unique($members);
479d6dc956fSAndreas Gohr    $members = array_filter($members);
480d6dc956fSAndreas Gohr
481d6dc956fSAndreas Gohr    // compare cleaned values
482d6dc956fSAndreas Gohr    foreach($members as $member) {
4834f56ecbfSAdrian Lang        if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member);
484d6dc956fSAndreas Gohr        if($member[0] == '@') {
485d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
486d6dc956fSAndreas Gohr            if(in_array($member, $groups)) return true;
487d6dc956fSAndreas Gohr        } else {
488d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
489d6dc956fSAndreas Gohr            if($member == $user) return true;
490d6dc956fSAndreas Gohr        }
491d6dc956fSAndreas Gohr    }
492d6dc956fSAndreas Gohr
493d6dc956fSAndreas Gohr    // still here? not a member!
494d6dc956fSAndreas Gohr    return false;
495d6dc956fSAndreas Gohr}
496d6dc956fSAndreas Gohr
497f8cc712eSAndreas Gohr/**
49815fae107Sandi * Convinience function for auth_aclcheck()
49915fae107Sandi *
50015fae107Sandi * This checks the permissions for the current user
50115fae107Sandi *
50215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
50315fae107Sandi *
5041698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
50515fae107Sandi * @return int          permission level
506f3f0262cSandi */
507f3f0262cSandifunction auth_quickaclcheck($id) {
508f3f0262cSandi    global $conf;
509f3f0262cSandi    global $USERINFO;
510f3f0262cSandi    # if no ACL is used always return upload rights
511f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
512f3f0262cSandi    return auth_aclcheck($id, $_SERVER['REMOTE_USER'], $USERINFO['grps']);
513f3f0262cSandi}
514f3f0262cSandi
515f3f0262cSandi/**
516f3f0262cSandi * Returns the maximum rights a user has for
517f3f0262cSandi * the given ID or its namespace
51815fae107Sandi *
51915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
52015fae107Sandi *
5211698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
52215fae107Sandi * @param  string       $user   Username
5233272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
52415fae107Sandi * @return int             permission level
525f3f0262cSandi */
526f3f0262cSandifunction auth_aclcheck($id, $user, $groups) {
527f3f0262cSandi    global $conf;
528f3f0262cSandi    global $AUTH_ACL;
529ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
530d752aedeSAndreas Gohr    global $auth;
531f3f0262cSandi
53285d03f68SAndreas Gohr    // if no ACL is used always return upload rights
533f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
534beca106aSAdrian Lang    if(!$auth) return AUTH_NONE;
535f3f0262cSandi
536074cf26bSandi    //make sure groups is an array
537074cf26bSandi    if(!is_array($groups)) $groups = array();
538074cf26bSandi
53985d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
540ab5d26daSAndreas Gohr    if(auth_isadmin($user, $groups)) {
541ab5d26daSAndreas Gohr        return AUTH_ADMIN;
542ab5d26daSAndreas Gohr    }
54385d03f68SAndreas Gohr
544eb3ce0d5SKazutaka Miyasaka    if(!$auth->isCaseSensitive()) {
545eb3ce0d5SKazutaka Miyasaka        $user   = utf8_strtolower($user);
546eb3ce0d5SKazutaka Miyasaka        $groups = array_map('utf8_strtolower', $groups);
547eb3ce0d5SKazutaka Miyasaka    }
548d752aedeSAndreas Gohr    $user   = $auth->cleanUser($user);
549d752aedeSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
55085d03f68SAndreas Gohr    $user   = auth_nameencode($user);
55185d03f68SAndreas Gohr
5526c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
5532cd2db38Sandi    $cnt = count($groups);
5542cd2db38Sandi    for($i = 0; $i < $cnt; $i++) {
5556c2bb100SAndreas Gohr        $groups[$i] = '@'.auth_nameencode($groups[$i]);
55610a76f6fSfrank    }
55710a76f6fSfrank
558f3f0262cSandi    $ns   = getNS($id);
559f3f0262cSandi    $perm = -1;
560f3f0262cSandi
56134aeb4afSAndreas Gohr    if($user || count($groups)) {
562f3f0262cSandi        //add ALL group
563f3f0262cSandi        $groups[] = '@ALL';
564f3f0262cSandi        //add User
56534aeb4afSAndreas Gohr        if($user) $groups[] = $user;
566f3f0262cSandi    } else {
56748d7b7a6SDominik Eckelmann        $groups[] = '@ALL';
568f3f0262cSandi    }
569f3f0262cSandi
570f3f0262cSandi    //check exact match first
571eb3ce0d5SKazutaka Miyasaka    $matches = preg_grep('/^'.preg_quote($id, '/').'\s+(\S+)\s+/u', $AUTH_ACL);
572f3f0262cSandi    if(count($matches)) {
573f3f0262cSandi        foreach($matches as $match) {
574f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
575f3f0262cSandi            $acl   = preg_split('/\s+/', $match);
576eb3ce0d5SKazutaka Miyasaka            if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
577eb3ce0d5SKazutaka Miyasaka                $acl[1] = utf8_strtolower($acl[1]);
578eb3ce0d5SKazutaka Miyasaka            }
57948d7b7a6SDominik Eckelmann            if(!in_array($acl[1], $groups)) {
58048d7b7a6SDominik Eckelmann                continue;
58148d7b7a6SDominik Eckelmann            }
5828ef6b7caSandi            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
583f3f0262cSandi            if($acl[2] > $perm) {
584f3f0262cSandi                $perm = $acl[2];
585f3f0262cSandi            }
586f3f0262cSandi        }
587f3f0262cSandi        if($perm > -1) {
588f3f0262cSandi            //we had a match - return it
589def492a2SGuillaume Turri            return (int) $perm;
590f3f0262cSandi        }
591f3f0262cSandi    }
592f3f0262cSandi
593f3f0262cSandi    //still here? do the namespace checks
594f3f0262cSandi    if($ns) {
5953e304b55SMichael Hamann        $path = $ns.':*';
596f3f0262cSandi    } else {
5973e304b55SMichael Hamann        $path = '*'; //root document
598f3f0262cSandi    }
599f3f0262cSandi
600f3f0262cSandi    do {
601eb3ce0d5SKazutaka Miyasaka        $matches = preg_grep('/^'.preg_quote($path, '/').'\s+(\S+)\s+/u', $AUTH_ACL);
602f3f0262cSandi        if(count($matches)) {
603f3f0262cSandi            foreach($matches as $match) {
604f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
605f3f0262cSandi                $acl   = preg_split('/\s+/', $match);
606eb3ce0d5SKazutaka Miyasaka                if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
607eb3ce0d5SKazutaka Miyasaka                    $acl[1] = utf8_strtolower($acl[1]);
608eb3ce0d5SKazutaka Miyasaka                }
60948d7b7a6SDominik Eckelmann                if(!in_array($acl[1], $groups)) {
61048d7b7a6SDominik Eckelmann                    continue;
61148d7b7a6SDominik Eckelmann                }
6128ef6b7caSandi                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
613f3f0262cSandi                if($acl[2] > $perm) {
614f3f0262cSandi                    $perm = $acl[2];
615f3f0262cSandi                }
616f3f0262cSandi            }
617f3f0262cSandi            //we had a match - return it
61848d7b7a6SDominik Eckelmann            if($perm != -1) {
619def492a2SGuillaume Turri                return (int) $perm;
620f3f0262cSandi            }
62148d7b7a6SDominik Eckelmann        }
622f3f0262cSandi        //get next higher namespace
623f3f0262cSandi        $ns = getNS($ns);
624f3f0262cSandi
6253e304b55SMichael Hamann        if($path != '*') {
6263e304b55SMichael Hamann            $path = $ns.':*';
6273e304b55SMichael Hamann            if($path == ':*') $path = '*';
628f3f0262cSandi        } else {
629f3f0262cSandi            //we did this already
630f3f0262cSandi            //looks like there is something wrong with the ACL
631f3f0262cSandi            //break here
632d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
633d5ce66f6SAndreas Gohr            return AUTH_NONE;
634f3f0262cSandi        }
635f3f0262cSandi    } while(1); //this should never loop endless
636ab5d26daSAndreas Gohr    return AUTH_NONE;
637f3f0262cSandi}
638f3f0262cSandi
639f3f0262cSandi/**
6406c2bb100SAndreas Gohr * Encode ASCII special chars
6416c2bb100SAndreas Gohr *
6426c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
6436c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
6446c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
6456c2bb100SAndreas Gohr * urlencoding!).
6466c2bb100SAndreas Gohr *
6476c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
6486c2bb100SAndreas Gohr *
6496c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
6506c2bb100SAndreas Gohr * @see rawurldecode()
6516c2bb100SAndreas Gohr */
652e838fc2eSAndreas Gohrfunction auth_nameencode($name, $skip_group = false) {
653a424cd8eSchris    global $cache_authname;
654a424cd8eSchris    $cache =& $cache_authname;
65531784267SAndreas Gohr    $name  = (string) $name;
656a424cd8eSchris
65780601d26SAndreas Gohr    // never encode wildcard FS#1955
65880601d26SAndreas Gohr    if($name == '%USER%') return $name;
659b78bf706Sromain    if($name == '%GROUP%') return $name;
66080601d26SAndreas Gohr
661a424cd8eSchris    if(!isset($cache[$name][$skip_group])) {
662e838fc2eSAndreas Gohr        if($skip_group && $name{0} == '@') {
663ab5d26daSAndreas Gohr            $cache[$name][$skip_group] = '@'.preg_replace(
664ab5d26daSAndreas Gohr                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
665ab5d26daSAndreas Gohr                "'%'.dechex(ord(substr('\\1',-1)))", substr($name, 1)
666ab5d26daSAndreas Gohr            );
667e838fc2eSAndreas Gohr        } else {
668ab5d26daSAndreas Gohr            $cache[$name][$skip_group] = preg_replace(
669ab5d26daSAndreas Gohr                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
670ab5d26daSAndreas Gohr                "'%'.dechex(ord(substr('\\1',-1)))", $name
671ab5d26daSAndreas Gohr            );
672e838fc2eSAndreas Gohr        }
6736c2bb100SAndreas Gohr    }
6746c2bb100SAndreas Gohr
675a424cd8eSchris    return $cache[$name][$skip_group];
676a424cd8eSchris}
677a424cd8eSchris
6786c2bb100SAndreas Gohr/**
679f3f0262cSandi * Create a pronouncable password
680f3f0262cSandi *
68115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
68215fae107Sandi * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
68315fae107Sandi *
68415fae107Sandi * @return string  pronouncable password
685f3f0262cSandi */
686f3f0262cSandifunction auth_pwgen() {
687f3f0262cSandi    $pw = '';
688f3f0262cSandi    $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
689f3f0262cSandi    $v  = 'aeiou'; //vowels
690f3f0262cSandi    $a  = $c.$v; //both
691f3f0262cSandi
692f3f0262cSandi    //use two syllables...
693f3f0262cSandi    for($i = 0; $i < 2; $i++) {
694f3f0262cSandi        $pw .= $c[rand(0, strlen($c) - 1)];
695f3f0262cSandi        $pw .= $v[rand(0, strlen($v) - 1)];
696f3f0262cSandi        $pw .= $a[rand(0, strlen($a) - 1)];
697f3f0262cSandi    }
698f3f0262cSandi    //... and add a nice number
699f3f0262cSandi    $pw .= rand(10, 99);
700f3f0262cSandi
701f3f0262cSandi    return $pw;
702f3f0262cSandi}
703f3f0262cSandi
704f3f0262cSandi/**
705f3f0262cSandi * Sends a password to the given user
706f3f0262cSandi *
70715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
708ab5d26daSAndreas Gohr * @param string $user Login name of the user
709ab5d26daSAndreas Gohr * @param string $password The new password in clear text
71015fae107Sandi * @return bool  true on success
711f3f0262cSandi */
712f3f0262cSandifunction auth_sendPassword($user, $password) {
713f3f0262cSandi    global $lang;
714ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
715cd52f92dSchris    global $auth;
716beca106aSAdrian Lang    if(!$auth) return false;
717cd52f92dSchris
718d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
719cd52f92dSchris    $userinfo = $auth->getUserData($user);
720f3f0262cSandi
72187ddda95Sandi    if(!$userinfo['mail']) return false;
722f3f0262cSandi
723f3f0262cSandi    $text = rawLocale('password');
724d7169d19SAndreas Gohr    $trep = array(
725d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
726d7169d19SAndreas Gohr        'LOGIN'    => $user,
727d7169d19SAndreas Gohr        'PASSWORD' => $password
728d7169d19SAndreas Gohr    );
729f3f0262cSandi
730d7169d19SAndreas Gohr    $mail = new Mailer();
731d7169d19SAndreas Gohr    $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
732d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
733d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
734d7169d19SAndreas Gohr    return $mail->send();
735f3f0262cSandi}
736f3f0262cSandi
737f3f0262cSandi/**
73815fae107Sandi * Register a new user
739f3f0262cSandi *
74015fae107Sandi * This registers a new user - Data is read directly from $_POST
74115fae107Sandi *
74215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
74315fae107Sandi * @return bool  true on success, false on any error
744f3f0262cSandi */
745f3f0262cSandifunction register() {
746f3f0262cSandi    global $lang;
747eb5d07e4Sjan    global $conf;
748ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
749cd52f92dSchris    global $auth;
75064273335SAndreas Gohr    global $INPUT;
751f3f0262cSandi
75264273335SAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
7533a48618aSAnika Henke    if(!actionOK('register')) return false;
754640145a5Sandi
75564273335SAndreas Gohr    // gather input
75664273335SAndreas Gohr    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
75764273335SAndreas Gohr    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
75864273335SAndreas Gohr    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
75964273335SAndreas Gohr    $pass     = $INPUT->post->str('pass');
76064273335SAndreas Gohr    $passchk  = $INPUT->post->str('passchk');
761d752aedeSAndreas Gohr
76264273335SAndreas Gohr    if(empty($login) || empty($fullname) || empty($email)) {
763f3f0262cSandi        msg($lang['regmissing'], -1);
764f3f0262cSandi        return false;
765f3f0262cSandi    }
766f3f0262cSandi
767cab2716aSmatthias.grimm    if($conf['autopasswd']) {
768cab2716aSmatthias.grimm        $pass = auth_pwgen(); // automatically generate password
76964273335SAndreas Gohr    } elseif(empty($pass) || empty($passchk)) {
770bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
771cab2716aSmatthias.grimm        return false;
77264273335SAndreas Gohr    } elseif($pass != $passchk) {
773bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
774cab2716aSmatthias.grimm        return false;
775cab2716aSmatthias.grimm    }
776cab2716aSmatthias.grimm
777f3f0262cSandi    //check mail
77864273335SAndreas Gohr    if(!mail_isvalid($email)) {
779f3f0262cSandi        msg($lang['regbadmail'], -1);
780f3f0262cSandi        return false;
781f3f0262cSandi    }
782f3f0262cSandi
783f3f0262cSandi    //okay try to create the user
78464273335SAndreas Gohr    if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) {
785f3f0262cSandi        msg($lang['reguexists'], -1);
786f3f0262cSandi        return false;
787f3f0262cSandi    }
788f3f0262cSandi
789790b7720SAndreas Gohr    // send notification about the new user
790790b7720SAndreas Gohr    $subscription = new Subscription();
791790b7720SAndreas Gohr    $subscription->send_register($login, $fullname, $email);
79202a498e7Schris
793790b7720SAndreas Gohr    // are we done?
794cab2716aSmatthias.grimm    if(!$conf['autopasswd']) {
795cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
796cab2716aSmatthias.grimm        return true;
797cab2716aSmatthias.grimm    }
798cab2716aSmatthias.grimm
799790b7720SAndreas Gohr    // autogenerated password? then send password to user
80064273335SAndreas Gohr    if(auth_sendPassword($login, $pass)) {
801f3f0262cSandi        msg($lang['regsuccess'], 1);
802f3f0262cSandi        return true;
803f3f0262cSandi    } else {
804f3f0262cSandi        msg($lang['regmailfail'], -1);
805f3f0262cSandi        return false;
806f3f0262cSandi    }
807f3f0262cSandi}
808f3f0262cSandi
80910a76f6fSfrank/**
8108b06d178Schris * Update user profile
8118b06d178Schris *
8128b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
8138b06d178Schris */
8148b06d178Schrisfunction updateprofile() {
8158b06d178Schris    global $conf;
8168b06d178Schris    global $lang;
817ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
818cd52f92dSchris    global $auth;
819bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
820bcc94b2cSAndreas Gohr    global $INPUT;
8218b06d178Schris
822bcc94b2cSAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
8231b2a85e8SAndreas Gohr    if(!checkSecurityToken()) return false;
8248b06d178Schris
8253a48618aSAnika Henke    if(!actionOK('profile')) {
8268b06d178Schris        msg($lang['profna'], -1);
8278b06d178Schris        return false;
8288b06d178Schris    }
8298b06d178Schris
830bcc94b2cSAndreas Gohr    $changes         = array();
831bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
832bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
833bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
834bcc94b2cSAndreas Gohr
835bcc94b2cSAndreas Gohr    // check misspelled passwords
836bcc94b2cSAndreas Gohr    if($changes['pass'] != $INPUT->post->str('passchk')) {
837bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
8388b06d178Schris        return false;
8398b06d178Schris    }
8408b06d178Schris
8418b06d178Schris    // clean fullname and email
842bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
843bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
8448b06d178Schris
845bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
846bcc94b2cSAndreas Gohr    if((empty($changes['name']) && $auth->canDo('modName')) ||
847bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
848ab5d26daSAndreas Gohr    ) {
8498b06d178Schris        msg($lang['profnoempty'], -1);
8508b06d178Schris        return false;
8518b06d178Schris    }
852bcc94b2cSAndreas Gohr    if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
8538b06d178Schris        msg($lang['regbadmail'], -1);
8548b06d178Schris        return false;
8558b06d178Schris    }
8568b06d178Schris
857bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
8584c21b7eeSAndreas Gohr
859bcc94b2cSAndreas Gohr    // check for unavailable capabilities
860bcc94b2cSAndreas Gohr    if(!$auth->canDo('modName')) unset($changes['name']);
861bcc94b2cSAndreas Gohr    if(!$auth->canDo('modMail')) unset($changes['mail']);
862bcc94b2cSAndreas Gohr    if(!$auth->canDo('modPass')) unset($changes['pass']);
863bcc94b2cSAndreas Gohr
864bcc94b2cSAndreas Gohr    // anything to do?
8658b06d178Schris    if(!count($changes)) {
8668b06d178Schris        msg($lang['profnochange'], -1);
8678b06d178Schris        return false;
8688b06d178Schris    }
8698b06d178Schris
8708b06d178Schris    if($conf['profileconfirm']) {
871bcc94b2cSAndreas Gohr        if(!$auth->checkPass($_SERVER['REMOTE_USER'], $INPUT->post->str('oldpass'))) {
8728b06d178Schris            msg($lang['badlogin'], -1);
8738b06d178Schris            return false;
8748b06d178Schris        }
8758b06d178Schris    }
8768b06d178Schris
877a0b5b007SChris Smith    if($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
878a0b5b007SChris Smith        // update cookie and session with the changed data
87932ed2b36SAndreas Gohr        if($changes['pass']) {
880ab5d26daSAndreas Gohr            list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
88132ed2b36SAndreas Gohr            $pass = PMA_blowfish_encrypt($changes['pass'], auth_cookiesalt(!$sticky));
882a0b5b007SChris Smith            auth_setCookie($_SERVER['REMOTE_USER'], $pass, (bool) $sticky);
88332ed2b36SAndreas Gohr        }
88425b2a98cSMichael Klier        return true;
885a0b5b007SChris Smith    }
886ab5d26daSAndreas Gohr
887ab5d26daSAndreas Gohr    return false;
8888b06d178Schris}
8898b06d178Schris
8908b06d178Schris/**
8918b06d178Schris * Send a  new password
8928b06d178Schris *
8931d5856cfSAndreas Gohr * This function handles both phases of the password reset:
8941d5856cfSAndreas Gohr *
8951d5856cfSAndreas Gohr *   - handling the first request of password reset
8961d5856cfSAndreas Gohr *   - validating the password reset auth token
8971d5856cfSAndreas Gohr *
8988b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
8998b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
9001d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
9018b06d178Schris *
9028b06d178Schris * @return bool true on success, false on any error
9038b06d178Schris */
9048b06d178Schrisfunction act_resendpwd() {
9058b06d178Schris    global $lang;
9068b06d178Schris    global $conf;
907ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
908cd52f92dSchris    global $auth;
909bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
910bcc94b2cSAndreas Gohr    global $INPUT;
9118b06d178Schris
9123a48618aSAnika Henke    if(!actionOK('resendpwd')) {
9138b06d178Schris        msg($lang['resendna'], -1);
9148b06d178Schris        return false;
9158b06d178Schris    }
9168b06d178Schris
917bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
9188b06d178Schris
9191d5856cfSAndreas Gohr    if($token) {
920cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
9211d5856cfSAndreas Gohr
9221d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
9231d5856cfSAndreas Gohr        if(!@file_exists($tfile)) {
9241d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
925bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
9261d5856cfSAndreas Gohr            return false;
9271d5856cfSAndreas Gohr        }
9288a9735e3SAndreas Gohr        // token is only valid for 3 days
9298a9735e3SAndreas Gohr        if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
9308a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
931bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
9321d5856cfSAndreas Gohr            @unlink($tfile);
9338a9735e3SAndreas Gohr            return false;
9348a9735e3SAndreas Gohr        }
9358a9735e3SAndreas Gohr
9368b06d178Schris        $user     = io_readfile($tfile);
937cd52f92dSchris        $userinfo = $auth->getUserData($user);
9388b06d178Schris        if(!$userinfo['mail']) {
9398b06d178Schris            msg($lang['resendpwdnouser'], -1);
9408b06d178Schris            return false;
9418b06d178Schris        }
9428b06d178Schris
943cc204bbdSAndreas Gohr        if(!$conf['autopasswd']) { // we let the user choose a password
944bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
945bcc94b2cSAndreas Gohr
946cc204bbdSAndreas Gohr            // password given correctly?
947bcc94b2cSAndreas Gohr            if(!$pass) return false;
948bcc94b2cSAndreas Gohr            if($pass != $INPUT->str('passchk')) {
949451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
950cc204bbdSAndreas Gohr                return false;
951cc204bbdSAndreas Gohr            }
952cc204bbdSAndreas Gohr
953bcc94b2cSAndreas Gohr            // change it
954cc204bbdSAndreas Gohr            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
955cc204bbdSAndreas Gohr                msg('error modifying user data', -1);
956cc204bbdSAndreas Gohr                return false;
957cc204bbdSAndreas Gohr            }
958cc204bbdSAndreas Gohr
959cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
960cc204bbdSAndreas Gohr
9618b06d178Schris            $pass = auth_pwgen();
9627d3c8d42SGabriel Birke            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
9638b06d178Schris                msg('error modifying user data', -1);
9648b06d178Schris                return false;
9658b06d178Schris            }
9668b06d178Schris
9678b06d178Schris            if(auth_sendPassword($user, $pass)) {
9688b06d178Schris                msg($lang['resendpwdsuccess'], 1);
9698b06d178Schris            } else {
9708b06d178Schris                msg($lang['regmailfail'], -1);
9718b06d178Schris            }
972cc204bbdSAndreas Gohr        }
973cc204bbdSAndreas Gohr
974cc204bbdSAndreas Gohr        @unlink($tfile);
9758b06d178Schris        return true;
9761d5856cfSAndreas Gohr
9771d5856cfSAndreas Gohr    } else {
9781d5856cfSAndreas Gohr        // we're in request phase
9791d5856cfSAndreas Gohr
980bcc94b2cSAndreas Gohr        if(!$INPUT->post->bool('save')) return false;
9811d5856cfSAndreas Gohr
982bcc94b2cSAndreas Gohr        if(!$INPUT->post->str('login')) {
9831d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
9841d5856cfSAndreas Gohr            return false;
9851d5856cfSAndreas Gohr        } else {
986bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
9871d5856cfSAndreas Gohr        }
9881d5856cfSAndreas Gohr
9891d5856cfSAndreas Gohr        $userinfo = $auth->getUserData($user);
9901d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
9911d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
9921d5856cfSAndreas Gohr            return false;
9931d5856cfSAndreas Gohr        }
9941d5856cfSAndreas Gohr
9951d5856cfSAndreas Gohr        // generate auth token
9961d5856cfSAndreas Gohr        $token = md5(auth_cookiesalt().$user); //secret but user based
9971d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
9981d5856cfSAndreas Gohr        $url   = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
9991d5856cfSAndreas Gohr
10001d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
10011d5856cfSAndreas Gohr
10021d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
1003d7169d19SAndreas Gohr        $trep = array(
1004d7169d19SAndreas Gohr            'FULLNAME' => $userinfo['name'],
1005d7169d19SAndreas Gohr            'LOGIN'    => $user,
1006d7169d19SAndreas Gohr            'CONFIRM'  => $url
1007d7169d19SAndreas Gohr        );
10081d5856cfSAndreas Gohr
1009d7169d19SAndreas Gohr        $mail = new Mailer();
1010d7169d19SAndreas Gohr        $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1011d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
1012d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
1013d7169d19SAndreas Gohr        if($mail->send()) {
10141d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
10151d5856cfSAndreas Gohr        } else {
10161d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
10171d5856cfSAndreas Gohr        }
10181d5856cfSAndreas Gohr        return true;
10191d5856cfSAndreas Gohr    }
1020ab5d26daSAndreas Gohr    // never reached
10218b06d178Schris}
10228b06d178Schris
10238b06d178Schris/**
1024b0855b11Sandi * Encrypts a password using the given method and salt
1025b0855b11Sandi *
1026b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1027b0855b11Sandi * is chosen.
1028b0855b11Sandi *
1029b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
1030ab5d26daSAndreas Gohr * @param string $clear The clear text password
1031ab5d26daSAndreas Gohr * @param string $method The hashing method
1032ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1033b0855b11Sandi * @return  string  The crypted password
1034b0855b11Sandi */
1035577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null) {
1036b0855b11Sandi    global $conf;
1037b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
103810a76f6fSfrank
10393a0a2d05SAndreas Gohr    $pass = new PassHash();
10403a0a2d05SAndreas Gohr    $call = 'hash_'.$method;
1041b0855b11Sandi
10423a0a2d05SAndreas Gohr    if(!method_exists($pass, $call)) {
1043b0855b11Sandi        msg("Unsupported crypt method $method", -1);
10443a0a2d05SAndreas Gohr        return false;
1045b0855b11Sandi    }
10463a0a2d05SAndreas Gohr
10473a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1048b0855b11Sandi}
1049b0855b11Sandi
1050b0855b11Sandi/**
1051b0855b11Sandi * Verifies a cleartext password against a crypted hash
1052b0855b11Sandi *
1053b0855b11Sandi * @author Andreas Gohr <andi@splitbrain.org>
1054ab5d26daSAndreas Gohr * @param  string $clear The clear text password
1055ab5d26daSAndreas Gohr * @param  string $crypt The hash to compare with
1056ab5d26daSAndreas Gohr * @return bool true if both match
1057b0855b11Sandi */
1058b0855b11Sandifunction auth_verifyPassword($clear, $crypt) {
10593a0a2d05SAndreas Gohr    $pass = new PassHash();
10603a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1061b0855b11Sandi}
1062340756e4Sandi
1063a0b5b007SChris Smith/**
1064a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1065a0b5b007SChris Smith *
1066a0b5b007SChris Smith * @param string  $user       username
1067a0b5b007SChris Smith * @param string  $pass       encrypted password
1068a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1069ab5d26daSAndreas Gohr * @return bool
1070a0b5b007SChris Smith */
1071a0b5b007SChris Smithfunction auth_setCookie($user, $pass, $sticky) {
1072a0b5b007SChris Smith    global $conf;
1073ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
1074a0b5b007SChris Smith    global $auth;
107579d00841SOliver Geisen    global $USERINFO;
1076a0b5b007SChris Smith
1077beca106aSAdrian Lang    if(!$auth) return false;
1078a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1079a0b5b007SChris Smith
1080a0b5b007SChris Smith    // set cookie
1081645c0a36SAndreas Gohr    $cookie    = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
108273ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1083c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1084a0b5b007SChris Smith    if(version_compare(PHP_VERSION, '5.2.0', '>')) {
108573ab87deSGabriel Birke        setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
1086a0b5b007SChris Smith    } else {
108773ab87deSGabriel Birke        setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
1088a0b5b007SChris Smith    }
1089a0b5b007SChris Smith    // set session
1090a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1091234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1092a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1093a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1094a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1095ab5d26daSAndreas Gohr
1096ab5d26daSAndreas Gohr    return true;
1097a0b5b007SChris Smith}
1098a0b5b007SChris Smith
1099645c0a36SAndreas Gohr/**
1100645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1101645c0a36SAndreas Gohr *
1102645c0a36SAndreas Gohr * @returns array
1103645c0a36SAndreas Gohr */
1104645c0a36SAndreas Gohrfunction auth_getCookie() {
1105c66972f2SAdrian Lang    if(!isset($_COOKIE[DOKU_COOKIE])) {
1106c66972f2SAdrian Lang        return array(null, null, null);
1107c66972f2SAdrian Lang    }
1108645c0a36SAndreas Gohr    list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
1109645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1110645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1111645c0a36SAndreas Gohr    $user   = base64_decode($user);
1112645c0a36SAndreas Gohr    return array($user, $sticky, $pass);
1113645c0a36SAndreas Gohr}
1114645c0a36SAndreas Gohr
1115e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1116