xref: /dokuwiki/inc/auth.php (revision 3272d797334d9d13a4e4ca43351b1607bb520445)
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;
12675c93b77SAndreas Gohr
12775c93b77SAndreas Gohr    if(!is_readable($config_cascade['acl']['default'])) return array();
12875c93b77SAndreas Gohr
12975c93b77SAndreas Gohr    $acl = file($config_cascade['acl']['default']);
13075c93b77SAndreas Gohr
131191bb90aSAndreas Gohr    //support user wildcard
132f8cc3354SGuy Brand    if(isset($_SERVER['REMOTE_USER'])) {
13375c93b77SAndreas Gohr        $len = count($acl);
13475c93b77SAndreas Gohr        for($i = 0; $i < $len; $i++) {
13575c93b77SAndreas Gohr            if($acl[$i]{0} == '#') continue;
13675c93b77SAndreas Gohr            list($id, $rest) = preg_split('/\s+/', $acl[$i], 2);
13775c93b77SAndreas Gohr            $id      = str_replace('%USER%', cleanID($_SERVER['REMOTE_USER']), $id);
13875c93b77SAndreas Gohr            $rest    = str_replace('%USER%', auth_nameencode($_SERVER['REMOTE_USER']), $rest);
13975c93b77SAndreas Gohr            $acl[$i] = "$id\t$rest";
140a8fe108bSGuy Brand        }
14111799630Sandi    }
14275c93b77SAndreas Gohr    return $acl;
143f3f0262cSandi}
144f3f0262cSandi
145ab5d26daSAndreas Gohr/**
146ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK
147ab5d26daSAndreas Gohr *
148ab5d26daSAndreas Gohr * @param $evdata
149ab5d26daSAndreas Gohr * @return bool
150ab5d26daSAndreas Gohr */
151b5ee21aaSAdrian Langfunction auth_login_wrapper($evdata) {
152ab5d26daSAndreas Gohr    return auth_login(
153ab5d26daSAndreas Gohr        $evdata['user'],
154b5ee21aaSAdrian Lang        $evdata['password'],
155b5ee21aaSAdrian Lang        $evdata['sticky'],
156ab5d26daSAndreas Gohr        $evdata['silent']
157ab5d26daSAndreas Gohr    );
158b5ee21aaSAdrian Lang}
159b5ee21aaSAdrian Lang
160f3f0262cSandi/**
161f3f0262cSandi * This tries to login the user based on the sent auth credentials
162f3f0262cSandi *
163f3f0262cSandi * The authentication works like this: if a username was given
16415fae107Sandi * a new login is assumed and user/password are checked. If they
16515fae107Sandi * are correct the password is encrypted with blowfish and stored
16615fae107Sandi * together with the username in a cookie - the same info is stored
16715fae107Sandi * in the session, too. Additonally a browserID is stored in the
16815fae107Sandi * session.
16915fae107Sandi *
17015fae107Sandi * If no username was given the cookie is checked: if the username,
17115fae107Sandi * crypted password and browserID match between session and cookie
17215fae107Sandi * no further testing is done and the user is accepted
17315fae107Sandi *
17415fae107Sandi * If a cookie was found but no session info was availabe the
175136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
17615fae107Sandi * together with username rechecked by calling this function again.
177f3f0262cSandi *
178f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
179f3f0262cSandi * are set.
18015fae107Sandi *
18115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
18215fae107Sandi *
18315fae107Sandi * @param   string  $user    Username
18415fae107Sandi * @param   string  $pass    Cleartext Password
18515fae107Sandi * @param   bool    $sticky  Cookie should not expire
186f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
18715fae107Sandi * @return  bool             true on successful auth
188f3f0262cSandi */
189f112c2faSAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false) {
190f3f0262cSandi    global $USERINFO;
191f3f0262cSandi    global $conf;
192f3f0262cSandi    global $lang;
193ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
194cd52f92dSchris    global $auth;
195ab5d26daSAndreas Gohr
196132bdbfeSandi    $sticky ? $sticky = true : $sticky = false; //sanity check
197f3f0262cSandi
198beca106aSAdrian Lang    if(!$auth) return false;
199beca106aSAdrian Lang
200bbbd6568SAndreas Gohr    if(!empty($user)) {
201132bdbfeSandi        //usual login
202cd52f92dSchris        if($auth->checkPass($user, $pass)) {
203132bdbfeSandi            // make logininfo globally available
204f3f0262cSandi            $_SERVER['REMOTE_USER'] = $user;
20532ed2b36SAndreas Gohr            $secret                 = auth_cookiesalt(!$sticky); //bind non-sticky to session
206e940aea4SAndreas Gohr            auth_setCookie($user, PMA_blowfish_encrypt($pass, $secret), $sticky);
207132bdbfeSandi            return true;
208f3f0262cSandi        } else {
209f3f0262cSandi            //invalid credentials - log off
210f112c2faSAndreas Gohr            if(!$silent) msg($lang['badlogin'], -1);
211f3f0262cSandi            auth_logoff();
212132bdbfeSandi            return false;
213f3f0262cSandi        }
214f3f0262cSandi    } else {
215132bdbfeSandi        // read cookie information
216645c0a36SAndreas Gohr        list($user, $sticky, $pass) = auth_getCookie();
217132bdbfeSandi        if($user && $pass) {
218132bdbfeSandi            // we got a cookie - see if we can trust it
219fa7c70ffSAdrian Lang
220fa7c70ffSAdrian Lang            // get session info
221fa7c70ffSAdrian Lang            $session = $_SESSION[DOKU_COOKIE]['auth'];
222132bdbfeSandi            if(isset($session) &&
2237172dbc0SAndreas Gohr                $auth->useSessionCache($user) &&
2244c989037SChris Smith                ($session['time'] >= time() - $conf['auth_security_timeout']) &&
225132bdbfeSandi                ($session['user'] == $user) &&
226234ce57eSAndreas Gohr                ($session['pass'] == sha1($pass)) && //still crypted
227ab5d26daSAndreas Gohr                ($session['buid'] == auth_browseruid())
228ab5d26daSAndreas Gohr            ) {
229234ce57eSAndreas Gohr
230132bdbfeSandi                // he has session, cookie and browser right - let him in
231132bdbfeSandi                $_SERVER['REMOTE_USER'] = $user;
232132bdbfeSandi                $USERINFO               = $session['info']; //FIXME move all references to session
233132bdbfeSandi                return true;
234132bdbfeSandi            }
235f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
23632ed2b36SAndreas Gohr            $secret = auth_cookiesalt(!$sticky); //bind non-sticky to session
237e940aea4SAndreas Gohr            $pass   = PMA_blowfish_decrypt($pass, $secret);
238f112c2faSAndreas Gohr            return auth_login($user, $pass, $sticky, true);
239132bdbfeSandi        }
240132bdbfeSandi    }
241f3f0262cSandi    //just to be sure
242883179a4SAndreas Gohr    auth_logoff(true);
243132bdbfeSandi    return false;
244f3f0262cSandi}
245132bdbfeSandi
246132bdbfeSandi/**
247f13fa892SAndreas Gohr * Checks if a given authentication token was stored in the session
248f13fa892SAndreas Gohr *
249f13fa892SAndreas Gohr * Will setup authentication data using data from the session if the
250f13fa892SAndreas Gohr * token is correct. Will exit with a 401 Status if not.
251f13fa892SAndreas Gohr *
252f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
253f13fa892SAndreas Gohr * @param  string $token The authentication token
254f13fa892SAndreas Gohr * @return boolean true (or will exit on failure)
255f13fa892SAndreas Gohr */
256f13fa892SAndreas Gohrfunction auth_validateToken($token) {
257f13fa892SAndreas Gohr    if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']) {
258f13fa892SAndreas Gohr        // bad token
259f13fa892SAndreas Gohr        header("HTTP/1.0 401 Unauthorized");
260f13fa892SAndreas Gohr        print 'Invalid auth token - maybe the session timed out';
261f13fa892SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
262f13fa892SAndreas Gohr        exit;
263f13fa892SAndreas Gohr    }
264f13fa892SAndreas Gohr    // still here? trust the session data
265f13fa892SAndreas Gohr    global $USERINFO;
266f13fa892SAndreas Gohr    $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
267f13fa892SAndreas Gohr    $USERINFO               = $_SESSION[DOKU_COOKIE]['auth']['info'];
268f13fa892SAndreas Gohr    return true;
269f13fa892SAndreas Gohr}
270f13fa892SAndreas Gohr
271f13fa892SAndreas Gohr/**
272f13fa892SAndreas Gohr * Create an auth token and store it in the session
273f13fa892SAndreas Gohr *
274f13fa892SAndreas Gohr * NOTE: this is completely unrelated to the getSecurityToken() function
275f13fa892SAndreas Gohr *
276f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
277f13fa892SAndreas Gohr * @return string The auth token
278f13fa892SAndreas Gohr */
279f13fa892SAndreas Gohrfunction auth_createToken() {
280f13fa892SAndreas Gohr    $token = md5(mt_rand());
28109c2d803SAndreas Gohr    @session_start(); // reopen the session if needed
282f13fa892SAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
28309c2d803SAndreas Gohr    session_write_close();
284f13fa892SAndreas Gohr    return $token;
285f13fa892SAndreas Gohr}
286f13fa892SAndreas Gohr
287f13fa892SAndreas Gohr/**
288136ce040Sandi * Builds a pseudo UID from browser and IP data
289132bdbfeSandi *
290132bdbfeSandi * This is neither unique nor unfakable - still it adds some
291136ce040Sandi * security. Using the first part of the IP makes sure
292136ce040Sandi * proxy farms like AOLs are stil okay.
29315fae107Sandi *
29415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
29515fae107Sandi *
29615fae107Sandi * @return  string  a MD5 sum of various browser headers
297132bdbfeSandi */
298132bdbfeSandifunction auth_browseruid() {
2992f9daf16SAndreas Gohr    $ip  = clientIP(true);
300132bdbfeSandi    $uid = '';
301132bdbfeSandi    $uid .= $_SERVER['HTTP_USER_AGENT'];
302132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
303132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
304132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
3052f9daf16SAndreas Gohr    $uid .= substr($ip, 0, strpos($ip, '.'));
306132bdbfeSandi    return md5($uid);
307132bdbfeSandi}
308132bdbfeSandi
309132bdbfeSandi/**
310132bdbfeSandi * Creates a random key to encrypt the password in cookies
31115fae107Sandi *
31215fae107Sandi * This function tries to read the password for encrypting
31398407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
31415fae107Sandi * if no such file is found a random key is created and
31515fae107Sandi * and stored in this file.
31615fae107Sandi *
31715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
31832ed2b36SAndreas Gohr * @param   bool $addsession if true, the sessionid is added to the salt
31915fae107Sandi * @return  string
320132bdbfeSandi */
32132ed2b36SAndreas Gohrfunction auth_cookiesalt($addsession = false) {
322132bdbfeSandi    global $conf;
32398407a7aSandi    $file = $conf['metadir'].'/_htcookiesalt';
324132bdbfeSandi    $salt = io_readFile($file);
325132bdbfeSandi    if(empty($salt)) {
326132bdbfeSandi        $salt = uniqid(rand(), true);
327132bdbfeSandi        io_saveFile($file, $salt);
328132bdbfeSandi    }
32932ed2b36SAndreas Gohr    if($addsession) {
33032ed2b36SAndreas Gohr        $salt .= session_id();
33132ed2b36SAndreas Gohr    }
332132bdbfeSandi    return $salt;
333f3f0262cSandi}
334f3f0262cSandi
335f3f0262cSandi/**
336883179a4SAndreas Gohr * Log out the current user
337883179a4SAndreas Gohr *
338f3f0262cSandi * This clears all authentication data and thus log the user
339883179a4SAndreas Gohr * off. It also clears session data.
34015fae107Sandi *
34115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
342883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
343f3f0262cSandi */
344883179a4SAndreas Gohrfunction auth_logoff($keepbc = false) {
345f3f0262cSandi    global $conf;
346f3f0262cSandi    global $USERINFO;
347ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
3485298a619SAndreas Gohr    global $auth;
34937065e65Sandi
350d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
351e9621d07SAndreas Gohr    @session_start();
352e9621d07SAndreas Gohr
353e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
354e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
355e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
356e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
357e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
358e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
359883179a4SAndreas Gohr    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
360e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
36137065e65Sandi    if(isset($_SERVER['REMOTE_USER']))
362f3f0262cSandi        unset($_SERVER['REMOTE_USER']);
363132bdbfeSandi    $USERINFO = null; //FIXME
364f5c6743cSAndreas Gohr
36573ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
366f5c6743cSAndreas Gohr    if(version_compare(PHP_VERSION, '5.2.0', '>')) {
36773ab87deSGabriel Birke        setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
368f5c6743cSAndreas Gohr    } else {
36973ab87deSGabriel Birke        setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
370f5c6743cSAndreas Gohr    }
3715298a619SAndreas Gohr
372880f62faSAndreas Gohr    if($auth) $auth->logOff();
373f3f0262cSandi}
374f3f0262cSandi
375f3f0262cSandi/**
376f8cc712eSAndreas Gohr * Check if a user is a manager
377f8cc712eSAndreas Gohr *
378f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
379f8cc712eSAndreas Gohr * user.
380f8cc712eSAndreas Gohr *
381f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
382f8cc712eSAndreas Gohr *
383f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
384f8cc712eSAndreas Gohr * @see    auth_isadmin
385ab5d26daSAndreas Gohr * @param  string $user       Username
386ab5d26daSAndreas Gohr * @param  array  $groups     List of groups the user is in
387ab5d26daSAndreas Gohr * @param  bool   $adminonly  when true checks if user is admin
388ab5d26daSAndreas Gohr * @return bool
389f8cc712eSAndreas Gohr */
390f8cc712eSAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false) {
391f8cc712eSAndreas Gohr    global $conf;
392f8cc712eSAndreas Gohr    global $USERINFO;
393ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
394d752aedeSAndreas Gohr    global $auth;
395f8cc712eSAndreas Gohr
396beca106aSAdrian Lang    if(!$auth) return false;
397c66972f2SAdrian Lang    if(is_null($user)) {
398c66972f2SAdrian Lang        if(!isset($_SERVER['REMOTE_USER'])) {
399c66972f2SAdrian Lang            return false;
400c66972f2SAdrian Lang        } else {
401c66972f2SAdrian Lang            $user = $_SERVER['REMOTE_USER'];
402c66972f2SAdrian Lang        }
403c66972f2SAdrian Lang    }
404d6dc956fSAndreas Gohr    if(is_null($groups)) {
405d6dc956fSAndreas Gohr        $groups = (array) $USERINFO['grps'];
406e259aa79SAndreas Gohr    }
407e259aa79SAndreas Gohr
408d6dc956fSAndreas Gohr    // check superuser match
409d6dc956fSAndreas Gohr    if(auth_isMember($conf['superuser'], $user, $groups)) return true;
410d6dc956fSAndreas Gohr    if($adminonly) return false;
411e259aa79SAndreas Gohr    // check managers
412d6dc956fSAndreas Gohr    if(auth_isMember($conf['manager'], $user, $groups)) return true;
41300ce12daSChris Smith
414f8cc712eSAndreas Gohr    return false;
415f8cc712eSAndreas Gohr}
416f8cc712eSAndreas Gohr
417f8cc712eSAndreas Gohr/**
418f8cc712eSAndreas Gohr * Check if a user is admin
419f8cc712eSAndreas Gohr *
420f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
421f8cc712eSAndreas Gohr *
422f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
423f8cc712eSAndreas Gohr *
424f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
425ab5d26daSAndreas Gohr * @see auth_ismanager()
426ab5d26daSAndreas Gohr * @param  string $user       Username
427ab5d26daSAndreas Gohr * @param  array  $groups     List of groups the user is in
428ab5d26daSAndreas Gohr * @return bool
429f8cc712eSAndreas Gohr */
430f8cc712eSAndreas Gohrfunction auth_isadmin($user = null, $groups = null) {
431f8cc712eSAndreas Gohr    return auth_ismanager($user, $groups, true);
432f8cc712eSAndreas Gohr}
433f8cc712eSAndreas Gohr
434d6dc956fSAndreas Gohr/**
435d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
436d6dc956fSAndreas Gohr * users and groups to determine membership status
437d6dc956fSAndreas Gohr *
438d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
439d6dc956fSAndreas Gohr *
440d6dc956fSAndreas Gohr * @param $memberlist string commaseparated list of allowed users and groups
441d6dc956fSAndreas Gohr * @param $user       string user to match against
442d6dc956fSAndreas Gohr * @param $groups     array  groups the user is member of
4435446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
444d6dc956fSAndreas Gohr */
445d6dc956fSAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups) {
446ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
447d6dc956fSAndreas Gohr    global $auth;
448d6dc956fSAndreas Gohr    if(!$auth) return false;
449d6dc956fSAndreas Gohr
450d6dc956fSAndreas Gohr    // clean user and groups
4514f56ecbfSAdrian Lang    if(!$auth->isCaseSensitive()) {
452d6dc956fSAndreas Gohr        $user   = utf8_strtolower($user);
453d6dc956fSAndreas Gohr        $groups = array_map('utf8_strtolower', $groups);
454d6dc956fSAndreas Gohr    }
455d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
456d6dc956fSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), $groups);
457d6dc956fSAndreas Gohr
458d6dc956fSAndreas Gohr    // extract the memberlist
459d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
460d6dc956fSAndreas Gohr    $members = array_map('trim', $members);
461d6dc956fSAndreas Gohr    $members = array_unique($members);
462d6dc956fSAndreas Gohr    $members = array_filter($members);
463d6dc956fSAndreas Gohr
464d6dc956fSAndreas Gohr    // compare cleaned values
465d6dc956fSAndreas Gohr    foreach($members as $member) {
4664f56ecbfSAdrian Lang        if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member);
467d6dc956fSAndreas Gohr        if($member[0] == '@') {
468d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
469d6dc956fSAndreas Gohr            if(in_array($member, $groups)) return true;
470d6dc956fSAndreas Gohr        } else {
471d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
472d6dc956fSAndreas Gohr            if($member == $user) return true;
473d6dc956fSAndreas Gohr        }
474d6dc956fSAndreas Gohr    }
475d6dc956fSAndreas Gohr
476d6dc956fSAndreas Gohr    // still here? not a member!
477d6dc956fSAndreas Gohr    return false;
478d6dc956fSAndreas Gohr}
479d6dc956fSAndreas Gohr
480f8cc712eSAndreas Gohr/**
48115fae107Sandi * Convinience function for auth_aclcheck()
48215fae107Sandi *
48315fae107Sandi * This checks the permissions for the current user
48415fae107Sandi *
48515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
48615fae107Sandi *
4871698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
48815fae107Sandi * @return int          permission level
489f3f0262cSandi */
490f3f0262cSandifunction auth_quickaclcheck($id) {
491f3f0262cSandi    global $conf;
492f3f0262cSandi    global $USERINFO;
493f3f0262cSandi    # if no ACL is used always return upload rights
494f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
495f3f0262cSandi    return auth_aclcheck($id, $_SERVER['REMOTE_USER'], $USERINFO['grps']);
496f3f0262cSandi}
497f3f0262cSandi
498f3f0262cSandi/**
499f3f0262cSandi * Returns the maximum rights a user has for
500f3f0262cSandi * the given ID or its namespace
50115fae107Sandi *
50215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
50315fae107Sandi *
5041698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
50515fae107Sandi * @param  string       $user   Username
506*3272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
50715fae107Sandi * @return int             permission level
508f3f0262cSandi */
509f3f0262cSandifunction auth_aclcheck($id, $user, $groups) {
510f3f0262cSandi    global $conf;
511f3f0262cSandi    global $AUTH_ACL;
512ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
513d752aedeSAndreas Gohr    global $auth;
514f3f0262cSandi
51585d03f68SAndreas Gohr    // if no ACL is used always return upload rights
516f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
517beca106aSAdrian Lang    if(!$auth) return AUTH_NONE;
518f3f0262cSandi
519074cf26bSandi    //make sure groups is an array
520074cf26bSandi    if(!is_array($groups)) $groups = array();
521074cf26bSandi
52285d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
523ab5d26daSAndreas Gohr    if(auth_isadmin($user, $groups)) {
524ab5d26daSAndreas Gohr        return AUTH_ADMIN;
525ab5d26daSAndreas Gohr    }
52685d03f68SAndreas Gohr
527e259aa79SAndreas Gohr    $ci = '';
528e259aa79SAndreas Gohr    if(!$auth->isCaseSensitive()) $ci = 'ui';
529d752aedeSAndreas Gohr
530d752aedeSAndreas Gohr    $user   = $auth->cleanUser($user);
531d752aedeSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
53285d03f68SAndreas Gohr    $user   = auth_nameencode($user);
53385d03f68SAndreas Gohr
5346c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
5352cd2db38Sandi    $cnt = count($groups);
5362cd2db38Sandi    for($i = 0; $i < $cnt; $i++) {
5376c2bb100SAndreas Gohr        $groups[$i] = '@'.auth_nameencode($groups[$i]);
53810a76f6fSfrank    }
53910a76f6fSfrank
540f3f0262cSandi    $ns   = getNS($id);
541f3f0262cSandi    $perm = -1;
542f3f0262cSandi
54334aeb4afSAndreas Gohr    if($user || count($groups)) {
544f3f0262cSandi        //add ALL group
545f3f0262cSandi        $groups[] = '@ALL';
546f3f0262cSandi        //add User
54734aeb4afSAndreas Gohr        if($user) $groups[] = $user;
548f3f0262cSandi    } else {
54948d7b7a6SDominik Eckelmann        $groups[] = '@ALL';
550f3f0262cSandi    }
551f3f0262cSandi
552f3f0262cSandi    //check exact match first
55348d7b7a6SDominik Eckelmann    $matches = preg_grep('/^'.preg_quote($id, '/').'\s+(\S+)\s+/'.$ci, $AUTH_ACL);
554f3f0262cSandi    if(count($matches)) {
555f3f0262cSandi        foreach($matches as $match) {
556f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
557f3f0262cSandi            $acl   = preg_split('/\s+/', $match);
55848d7b7a6SDominik Eckelmann            if(!in_array($acl[1], $groups)) {
55948d7b7a6SDominik Eckelmann                continue;
56048d7b7a6SDominik Eckelmann            }
5618ef6b7caSandi            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
562f3f0262cSandi            if($acl[2] > $perm) {
563f3f0262cSandi                $perm = $acl[2];
564f3f0262cSandi            }
565f3f0262cSandi        }
566f3f0262cSandi        if($perm > -1) {
567f3f0262cSandi            //we had a match - return it
568f3f0262cSandi            return $perm;
569f3f0262cSandi        }
570f3f0262cSandi    }
571f3f0262cSandi
572f3f0262cSandi    //still here? do the namespace checks
573f3f0262cSandi    if($ns) {
5743e304b55SMichael Hamann        $path = $ns.':*';
575f3f0262cSandi    } else {
5763e304b55SMichael Hamann        $path = '*'; //root document
577f3f0262cSandi    }
578f3f0262cSandi
579f3f0262cSandi    do {
58048d7b7a6SDominik Eckelmann        $matches = preg_grep('/^'.preg_quote($path, '/').'\s+(\S+)\s+/'.$ci, $AUTH_ACL);
581f3f0262cSandi        if(count($matches)) {
582f3f0262cSandi            foreach($matches as $match) {
583f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
584f3f0262cSandi                $acl   = preg_split('/\s+/', $match);
58548d7b7a6SDominik Eckelmann                if(!in_array($acl[1], $groups)) {
58648d7b7a6SDominik Eckelmann                    continue;
58748d7b7a6SDominik Eckelmann                }
5888ef6b7caSandi                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
589f3f0262cSandi                if($acl[2] > $perm) {
590f3f0262cSandi                    $perm = $acl[2];
591f3f0262cSandi                }
592f3f0262cSandi            }
593f3f0262cSandi            //we had a match - return it
59448d7b7a6SDominik Eckelmann            if($perm != -1) {
595f3f0262cSandi                return $perm;
596f3f0262cSandi            }
59748d7b7a6SDominik Eckelmann        }
598f3f0262cSandi        //get next higher namespace
599f3f0262cSandi        $ns = getNS($ns);
600f3f0262cSandi
6013e304b55SMichael Hamann        if($path != '*') {
6023e304b55SMichael Hamann            $path = $ns.':*';
6033e304b55SMichael Hamann            if($path == ':*') $path = '*';
604f3f0262cSandi        } else {
605f3f0262cSandi            //we did this already
606f3f0262cSandi            //looks like there is something wrong with the ACL
607f3f0262cSandi            //break here
608d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
609d5ce66f6SAndreas Gohr            return AUTH_NONE;
610f3f0262cSandi        }
611f3f0262cSandi    } while(1); //this should never loop endless
612ab5d26daSAndreas Gohr    return AUTH_NONE;
613f3f0262cSandi}
614f3f0262cSandi
615f3f0262cSandi/**
6166c2bb100SAndreas Gohr * Encode ASCII special chars
6176c2bb100SAndreas Gohr *
6186c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
6196c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
6206c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
6216c2bb100SAndreas Gohr * urlencoding!).
6226c2bb100SAndreas Gohr *
6236c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
6246c2bb100SAndreas Gohr *
6256c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
6266c2bb100SAndreas Gohr * @see rawurldecode()
6276c2bb100SAndreas Gohr */
628e838fc2eSAndreas Gohrfunction auth_nameencode($name, $skip_group = false) {
629a424cd8eSchris    global $cache_authname;
630a424cd8eSchris    $cache =& $cache_authname;
63131784267SAndreas Gohr    $name  = (string) $name;
632a424cd8eSchris
63380601d26SAndreas Gohr    // never encode wildcard FS#1955
63480601d26SAndreas Gohr    if($name == '%USER%') return $name;
63580601d26SAndreas Gohr
636a424cd8eSchris    if(!isset($cache[$name][$skip_group])) {
637e838fc2eSAndreas Gohr        if($skip_group && $name{0} == '@') {
638ab5d26daSAndreas Gohr            $cache[$name][$skip_group] = '@'.preg_replace(
639ab5d26daSAndreas Gohr                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
640ab5d26daSAndreas Gohr                "'%'.dechex(ord(substr('\\1',-1)))", substr($name, 1)
641ab5d26daSAndreas Gohr            );
642e838fc2eSAndreas Gohr        } else {
643ab5d26daSAndreas Gohr            $cache[$name][$skip_group] = preg_replace(
644ab5d26daSAndreas Gohr                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
645ab5d26daSAndreas Gohr                "'%'.dechex(ord(substr('\\1',-1)))", $name
646ab5d26daSAndreas Gohr            );
647e838fc2eSAndreas Gohr        }
6486c2bb100SAndreas Gohr    }
6496c2bb100SAndreas Gohr
650a424cd8eSchris    return $cache[$name][$skip_group];
651a424cd8eSchris}
652a424cd8eSchris
6536c2bb100SAndreas Gohr/**
654f3f0262cSandi * Create a pronouncable password
655f3f0262cSandi *
65615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
65715fae107Sandi * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
65815fae107Sandi *
65915fae107Sandi * @return string  pronouncable password
660f3f0262cSandi */
661f3f0262cSandifunction auth_pwgen() {
662f3f0262cSandi    $pw = '';
663f3f0262cSandi    $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
664f3f0262cSandi    $v  = 'aeiou'; //vowels
665f3f0262cSandi    $a  = $c.$v; //both
666f3f0262cSandi
667f3f0262cSandi    //use two syllables...
668f3f0262cSandi    for($i = 0; $i < 2; $i++) {
669f3f0262cSandi        $pw .= $c[rand(0, strlen($c) - 1)];
670f3f0262cSandi        $pw .= $v[rand(0, strlen($v) - 1)];
671f3f0262cSandi        $pw .= $a[rand(0, strlen($a) - 1)];
672f3f0262cSandi    }
673f3f0262cSandi    //... and add a nice number
674f3f0262cSandi    $pw .= rand(10, 99);
675f3f0262cSandi
676f3f0262cSandi    return $pw;
677f3f0262cSandi}
678f3f0262cSandi
679f3f0262cSandi/**
680f3f0262cSandi * Sends a password to the given user
681f3f0262cSandi *
68215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
683ab5d26daSAndreas Gohr * @param string $user Login name of the user
684ab5d26daSAndreas Gohr * @param string $password The new password in clear text
68515fae107Sandi * @return bool  true on success
686f3f0262cSandi */
687f3f0262cSandifunction auth_sendPassword($user, $password) {
688f3f0262cSandi    global $lang;
689ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
690cd52f92dSchris    global $auth;
691beca106aSAdrian Lang    if(!$auth) return false;
692cd52f92dSchris
693d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
694cd52f92dSchris    $userinfo = $auth->getUserData($user);
695f3f0262cSandi
69687ddda95Sandi    if(!$userinfo['mail']) return false;
697f3f0262cSandi
698f3f0262cSandi    $text = rawLocale('password');
699d7169d19SAndreas Gohr    $trep = array(
700d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
701d7169d19SAndreas Gohr        'LOGIN'    => $user,
702d7169d19SAndreas Gohr        'PASSWORD' => $password
703d7169d19SAndreas Gohr    );
704f3f0262cSandi
705d7169d19SAndreas Gohr    $mail = new Mailer();
706d7169d19SAndreas Gohr    $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
707d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
708d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
709d7169d19SAndreas Gohr    return $mail->send();
710f3f0262cSandi}
711f3f0262cSandi
712f3f0262cSandi/**
71315fae107Sandi * Register a new user
714f3f0262cSandi *
71515fae107Sandi * This registers a new user - Data is read directly from $_POST
71615fae107Sandi *
71715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
71815fae107Sandi * @return bool  true on success, false on any error
719f3f0262cSandi */
720f3f0262cSandifunction register() {
721f3f0262cSandi    global $lang;
722eb5d07e4Sjan    global $conf;
723ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
724cd52f92dSchris    global $auth;
725f3f0262cSandi
726f3f0262cSandi    if(!$_POST['save']) return false;
7273a48618aSAnika Henke    if(!actionOK('register')) return false;
728640145a5Sandi
729f3f0262cSandi    //clean username
730d752aedeSAndreas Gohr    $_POST['login'] = trim($auth->cleanUser($_POST['login']));
731d752aedeSAndreas Gohr
732f3f0262cSandi    //clean fullname and email
73354f0e6eaSAndreas Gohr    $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $_POST['fullname']));
73454f0e6eaSAndreas Gohr    $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $_POST['email']));
735f3f0262cSandi
736f3f0262cSandi    if(empty($_POST['login']) ||
737f3f0262cSandi        empty($_POST['fullname']) ||
738ab5d26daSAndreas Gohr        empty($_POST['email'])
739ab5d26daSAndreas Gohr    ) {
740f3f0262cSandi        msg($lang['regmissing'], -1);
741f3f0262cSandi        return false;
742f3f0262cSandi    }
743f3f0262cSandi
744cab2716aSmatthias.grimm    if($conf['autopasswd']) {
745cab2716aSmatthias.grimm        $pass = auth_pwgen(); // automatically generate password
746cab2716aSmatthias.grimm    } elseif(empty($_POST['pass']) ||
747ab5d26daSAndreas Gohr        empty($_POST['passchk'])
748ab5d26daSAndreas Gohr    ) {
749bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
750cab2716aSmatthias.grimm        return false;
751cab2716aSmatthias.grimm    } elseif($_POST['pass'] != $_POST['passchk']) {
752bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
753cab2716aSmatthias.grimm        return false;
754cab2716aSmatthias.grimm    } else {
755cab2716aSmatthias.grimm        $pass = $_POST['pass']; // accept checked and valid password
756cab2716aSmatthias.grimm    }
757cab2716aSmatthias.grimm
758f3f0262cSandi    //check mail
75944f669e9Sandi    if(!mail_isvalid($_POST['email'])) {
760f3f0262cSandi        msg($lang['regbadmail'], -1);
761f3f0262cSandi        return false;
762f3f0262cSandi    }
763f3f0262cSandi
764f3f0262cSandi    //okay try to create the user
7657d3c8d42SGabriel Birke    if(!$auth->triggerUserMod('create', array($_POST['login'], $pass, $_POST['fullname'], $_POST['email']))) {
766f3f0262cSandi        msg($lang['reguexists'], -1);
767f3f0262cSandi        return false;
768f3f0262cSandi    }
769f3f0262cSandi
77002a498e7Schris    // create substitutions for use in notification email
77102a498e7Schris    $substitutions = array(
77202a498e7Schris        'NEWUSER'  => $_POST['login'],
77302a498e7Schris        'NEWNAME'  => $_POST['fullname'],
77402a498e7Schris        'NEWEMAIL' => $_POST['email'],
77502a498e7Schris    );
77602a498e7Schris
777cab2716aSmatthias.grimm    if(!$conf['autopasswd']) {
778cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
77902a498e7Schris        notify('', 'register', '', $_POST['login'], false, $substitutions);
780cab2716aSmatthias.grimm        return true;
781cab2716aSmatthias.grimm    }
782cab2716aSmatthias.grimm
783cab2716aSmatthias.grimm    // autogenerated password? then send him the password
784f3f0262cSandi    if(auth_sendPassword($_POST['login'], $pass)) {
785f3f0262cSandi        msg($lang['regsuccess'], 1);
78602a498e7Schris        notify('', 'register', '', $_POST['login'], false, $substitutions);
787f3f0262cSandi        return true;
788f3f0262cSandi    } else {
789f3f0262cSandi        msg($lang['regmailfail'], -1);
790f3f0262cSandi        return false;
791f3f0262cSandi    }
792f3f0262cSandi}
793f3f0262cSandi
79410a76f6fSfrank/**
7958b06d178Schris * Update user profile
7968b06d178Schris *
7978b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
7988b06d178Schris */
7998b06d178Schrisfunction updateprofile() {
8008b06d178Schris    global $conf;
8018b06d178Schris    global $lang;
802ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
803cd52f92dSchris    global $auth;
804bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
805bcc94b2cSAndreas Gohr    global $INPUT;
8068b06d178Schris
807bcc94b2cSAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
8081b2a85e8SAndreas Gohr    if(!checkSecurityToken()) return false;
8098b06d178Schris
8103a48618aSAnika Henke    if(!actionOK('profile')) {
8118b06d178Schris        msg($lang['profna'], -1);
8128b06d178Schris        return false;
8138b06d178Schris    }
8148b06d178Schris
815bcc94b2cSAndreas Gohr    $changes         = array();
816bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
817bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
818bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
819bcc94b2cSAndreas Gohr
820bcc94b2cSAndreas Gohr    // check misspelled passwords
821bcc94b2cSAndreas Gohr    if($changes['pass'] != $INPUT->post->str('passchk')) {
822bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
8238b06d178Schris        return false;
8248b06d178Schris    }
8258b06d178Schris
8268b06d178Schris    // clean fullname and email
827bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
828bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
8298b06d178Schris
830bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
831bcc94b2cSAndreas Gohr    if((empty($changes['name']) && $auth->canDo('modName')) ||
832bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
833ab5d26daSAndreas Gohr    ) {
8348b06d178Schris        msg($lang['profnoempty'], -1);
8358b06d178Schris        return false;
8368b06d178Schris    }
837bcc94b2cSAndreas Gohr    if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
8388b06d178Schris        msg($lang['regbadmail'], -1);
8398b06d178Schris        return false;
8408b06d178Schris    }
8418b06d178Schris
842bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
8434c21b7eeSAndreas Gohr
844bcc94b2cSAndreas Gohr    // check for unavailable capabilities
845bcc94b2cSAndreas Gohr    if(!$auth->canDo('modName')) unset($changes['name']);
846bcc94b2cSAndreas Gohr    if(!$auth->canDo('modMail')) unset($changes['mail']);
847bcc94b2cSAndreas Gohr    if(!$auth->canDo('modPass')) unset($changes['pass']);
848bcc94b2cSAndreas Gohr
849bcc94b2cSAndreas Gohr    // anything to do?
8508b06d178Schris    if(!count($changes)) {
8518b06d178Schris        msg($lang['profnochange'], -1);
8528b06d178Schris        return false;
8538b06d178Schris    }
8548b06d178Schris
8558b06d178Schris    if($conf['profileconfirm']) {
856bcc94b2cSAndreas Gohr        if(!$auth->checkPass($_SERVER['REMOTE_USER'], $INPUT->post->str('oldpass'))) {
8578b06d178Schris            msg($lang['badlogin'], -1);
8588b06d178Schris            return false;
8598b06d178Schris        }
8608b06d178Schris    }
8618b06d178Schris
862a0b5b007SChris Smith    if($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
863a0b5b007SChris Smith        // update cookie and session with the changed data
86432ed2b36SAndreas Gohr        if($changes['pass']) {
865ab5d26daSAndreas Gohr            list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
86632ed2b36SAndreas Gohr            $pass = PMA_blowfish_encrypt($changes['pass'], auth_cookiesalt(!$sticky));
867a0b5b007SChris Smith            auth_setCookie($_SERVER['REMOTE_USER'], $pass, (bool) $sticky);
86832ed2b36SAndreas Gohr        }
86925b2a98cSMichael Klier        return true;
870a0b5b007SChris Smith    }
871ab5d26daSAndreas Gohr
872ab5d26daSAndreas Gohr    return false;
8738b06d178Schris}
8748b06d178Schris
8758b06d178Schris/**
8768b06d178Schris * Send a  new password
8778b06d178Schris *
8781d5856cfSAndreas Gohr * This function handles both phases of the password reset:
8791d5856cfSAndreas Gohr *
8801d5856cfSAndreas Gohr *   - handling the first request of password reset
8811d5856cfSAndreas Gohr *   - validating the password reset auth token
8821d5856cfSAndreas Gohr *
8838b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
8848b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
8851d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
8868b06d178Schris *
8878b06d178Schris * @return bool true on success, false on any error
8888b06d178Schris */
8898b06d178Schrisfunction act_resendpwd() {
8908b06d178Schris    global $lang;
8918b06d178Schris    global $conf;
892ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
893cd52f92dSchris    global $auth;
894bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
895bcc94b2cSAndreas Gohr    global $INPUT;
8968b06d178Schris
8973a48618aSAnika Henke    if(!actionOK('resendpwd')) {
8988b06d178Schris        msg($lang['resendna'], -1);
8998b06d178Schris        return false;
9008b06d178Schris    }
9018b06d178Schris
902bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
9038b06d178Schris
9041d5856cfSAndreas Gohr    if($token) {
905cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
9061d5856cfSAndreas Gohr
9071d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
9081d5856cfSAndreas Gohr        if(!@file_exists($tfile)) {
9091d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
910bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
9111d5856cfSAndreas Gohr            return false;
9121d5856cfSAndreas Gohr        }
9138a9735e3SAndreas Gohr        // token is only valid for 3 days
9148a9735e3SAndreas Gohr        if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
9158a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
916bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
9171d5856cfSAndreas Gohr            @unlink($tfile);
9188a9735e3SAndreas Gohr            return false;
9198a9735e3SAndreas Gohr        }
9208a9735e3SAndreas Gohr
9218b06d178Schris        $user     = io_readfile($tfile);
922cd52f92dSchris        $userinfo = $auth->getUserData($user);
9238b06d178Schris        if(!$userinfo['mail']) {
9248b06d178Schris            msg($lang['resendpwdnouser'], -1);
9258b06d178Schris            return false;
9268b06d178Schris        }
9278b06d178Schris
928cc204bbdSAndreas Gohr        if(!$conf['autopasswd']) { // we let the user choose a password
929bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
930bcc94b2cSAndreas Gohr
931cc204bbdSAndreas Gohr            // password given correctly?
932bcc94b2cSAndreas Gohr            if(!$pass) return false;
933bcc94b2cSAndreas Gohr            if($pass != $INPUT->str('passchk')) {
934451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
935cc204bbdSAndreas Gohr                return false;
936cc204bbdSAndreas Gohr            }
937cc204bbdSAndreas Gohr
938bcc94b2cSAndreas Gohr            // change it
939cc204bbdSAndreas Gohr            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
940cc204bbdSAndreas Gohr                msg('error modifying user data', -1);
941cc204bbdSAndreas Gohr                return false;
942cc204bbdSAndreas Gohr            }
943cc204bbdSAndreas Gohr
944cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
945cc204bbdSAndreas Gohr
9468b06d178Schris            $pass = auth_pwgen();
9477d3c8d42SGabriel Birke            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
9488b06d178Schris                msg('error modifying user data', -1);
9498b06d178Schris                return false;
9508b06d178Schris            }
9518b06d178Schris
9528b06d178Schris            if(auth_sendPassword($user, $pass)) {
9538b06d178Schris                msg($lang['resendpwdsuccess'], 1);
9548b06d178Schris            } else {
9558b06d178Schris                msg($lang['regmailfail'], -1);
9568b06d178Schris            }
957cc204bbdSAndreas Gohr        }
958cc204bbdSAndreas Gohr
959cc204bbdSAndreas Gohr        @unlink($tfile);
9608b06d178Schris        return true;
9611d5856cfSAndreas Gohr
9621d5856cfSAndreas Gohr    } else {
9631d5856cfSAndreas Gohr        // we're in request phase
9641d5856cfSAndreas Gohr
965bcc94b2cSAndreas Gohr        if(!$INPUT->post->bool('save')) return false;
9661d5856cfSAndreas Gohr
967bcc94b2cSAndreas Gohr        if(!$INPUT->post->str('login')) {
9681d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
9691d5856cfSAndreas Gohr            return false;
9701d5856cfSAndreas Gohr        } else {
971bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
9721d5856cfSAndreas Gohr        }
9731d5856cfSAndreas Gohr
9741d5856cfSAndreas Gohr        $userinfo = $auth->getUserData($user);
9751d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
9761d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
9771d5856cfSAndreas Gohr            return false;
9781d5856cfSAndreas Gohr        }
9791d5856cfSAndreas Gohr
9801d5856cfSAndreas Gohr        // generate auth token
9811d5856cfSAndreas Gohr        $token = md5(auth_cookiesalt().$user); //secret but user based
9821d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
9831d5856cfSAndreas Gohr        $url   = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
9841d5856cfSAndreas Gohr
9851d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
9861d5856cfSAndreas Gohr
9871d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
988d7169d19SAndreas Gohr        $trep = array(
989d7169d19SAndreas Gohr            'FULLNAME' => $userinfo['name'],
990d7169d19SAndreas Gohr            'LOGIN'    => $user,
991d7169d19SAndreas Gohr            'CONFIRM'  => $url
992d7169d19SAndreas Gohr        );
9931d5856cfSAndreas Gohr
994d7169d19SAndreas Gohr        $mail = new Mailer();
995d7169d19SAndreas Gohr        $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
996d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
997d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
998d7169d19SAndreas Gohr        if($mail->send()) {
9991d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
10001d5856cfSAndreas Gohr        } else {
10011d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
10021d5856cfSAndreas Gohr        }
10031d5856cfSAndreas Gohr        return true;
10041d5856cfSAndreas Gohr    }
1005ab5d26daSAndreas Gohr    // never reached
10068b06d178Schris}
10078b06d178Schris
10088b06d178Schris/**
1009b0855b11Sandi * Encrypts a password using the given method and salt
1010b0855b11Sandi *
1011b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1012b0855b11Sandi * is chosen.
1013b0855b11Sandi *
1014b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
1015ab5d26daSAndreas Gohr * @param string $clear The clear text password
1016ab5d26daSAndreas Gohr * @param string $method The hashing method
1017ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1018b0855b11Sandi * @return  string  The crypted password
1019b0855b11Sandi */
1020577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null) {
1021b0855b11Sandi    global $conf;
1022b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
102310a76f6fSfrank
10243a0a2d05SAndreas Gohr    $pass = new PassHash();
10253a0a2d05SAndreas Gohr    $call = 'hash_'.$method;
1026b0855b11Sandi
10273a0a2d05SAndreas Gohr    if(!method_exists($pass, $call)) {
1028b0855b11Sandi        msg("Unsupported crypt method $method", -1);
10293a0a2d05SAndreas Gohr        return false;
1030b0855b11Sandi    }
10313a0a2d05SAndreas Gohr
10323a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1033b0855b11Sandi}
1034b0855b11Sandi
1035b0855b11Sandi/**
1036b0855b11Sandi * Verifies a cleartext password against a crypted hash
1037b0855b11Sandi *
1038b0855b11Sandi * @author Andreas Gohr <andi@splitbrain.org>
1039ab5d26daSAndreas Gohr * @param  string $clear The clear text password
1040ab5d26daSAndreas Gohr * @param  string $crypt The hash to compare with
1041ab5d26daSAndreas Gohr * @return bool true if both match
1042b0855b11Sandi */
1043b0855b11Sandifunction auth_verifyPassword($clear, $crypt) {
10443a0a2d05SAndreas Gohr    $pass = new PassHash();
10453a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1046b0855b11Sandi}
1047340756e4Sandi
1048a0b5b007SChris Smith/**
1049a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1050a0b5b007SChris Smith *
1051a0b5b007SChris Smith * @param string  $user       username
1052a0b5b007SChris Smith * @param string  $pass       encrypted password
1053a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1054ab5d26daSAndreas Gohr * @return bool
1055a0b5b007SChris Smith */
1056a0b5b007SChris Smithfunction auth_setCookie($user, $pass, $sticky) {
1057a0b5b007SChris Smith    global $conf;
1058ab5d26daSAndreas Gohr    /* @var auth_basic $auth */
1059a0b5b007SChris Smith    global $auth;
106079d00841SOliver Geisen    global $USERINFO;
1061a0b5b007SChris Smith
1062beca106aSAdrian Lang    if(!$auth) return false;
1063a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1064a0b5b007SChris Smith
1065a0b5b007SChris Smith    // set cookie
1066645c0a36SAndreas Gohr    $cookie    = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
106773ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1068c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1069a0b5b007SChris Smith    if(version_compare(PHP_VERSION, '5.2.0', '>')) {
107073ab87deSGabriel Birke        setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
1071a0b5b007SChris Smith    } else {
107273ab87deSGabriel Birke        setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
1073a0b5b007SChris Smith    }
1074a0b5b007SChris Smith    // set session
1075a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1076234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1077a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1078a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1079a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1080ab5d26daSAndreas Gohr
1081ab5d26daSAndreas Gohr    return true;
1082a0b5b007SChris Smith}
1083a0b5b007SChris Smith
1084645c0a36SAndreas Gohr/**
1085645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1086645c0a36SAndreas Gohr *
1087645c0a36SAndreas Gohr * @returns array
1088645c0a36SAndreas Gohr */
1089645c0a36SAndreas Gohrfunction auth_getCookie() {
1090c66972f2SAdrian Lang    if(!isset($_COOKIE[DOKU_COOKIE])) {
1091c66972f2SAdrian Lang        return array(null, null, null);
1092c66972f2SAdrian Lang    }
1093645c0a36SAndreas Gohr    list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
1094645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1095645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1096645c0a36SAndreas Gohr    $user   = base64_decode($user);
1097645c0a36SAndreas Gohr    return array($user, $sticky, $pass);
1098645c0a36SAndreas Gohr}
1099645c0a36SAndreas Gohr
1100e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1101