xref: /dokuwiki/inc/auth.php (revision 04d68ae4edcddca8a3c30ed4ce6c72d28440a084)
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;
4327058a05SMichael Hamann    /* @var Doku_Plugin_Controller $plugin_controller */
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);
57a91f1103SAnika Henke            msg('Your authtype setting is deprecated. You must set $conf[\'authtype\'] = "auth' . $conf['authtype'] . '"'
5898e31f85SKlap-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
13932e82180SAndreas Gohr    $out = array();
1409ce556d2SAndreas Gohr    foreach($acl as $line) {
1419ce556d2SAndreas Gohr        $line = trim($line);
142443e135dSChristopher Smith        if(empty($line) || ($line{0} == '#')) continue; // skip blank lines & comments
14321c3090aSChristopher Smith        list($id,$rest) = preg_split('/[ \t]+/',$line,2);
14432e82180SAndreas Gohr
145443e135dSChristopher Smith        // substitute user wildcard first (its 1:1)
146ad3d68d7SChristopher Smith        if(strstr($line, '%USER%')){
147ad3d68d7SChristopher Smith            // if user is not logged in, this ACL line is meaningless - skip it
148ad3d68d7SChristopher Smith            if (!isset($_SERVER['REMOTE_USER'])) continue;
149ad3d68d7SChristopher Smith
150ad3d68d7SChristopher Smith            $id   = str_replace('%USER%',cleanID($_SERVER['REMOTE_USER']),$id);
151ad3d68d7SChristopher Smith            $rest = str_replace('%USER%',auth_nameencode($_SERVER['REMOTE_USER']),$rest);
152ad3d68d7SChristopher Smith        }
153ad3d68d7SChristopher Smith
154ad3d68d7SChristopher Smith        // substitute group wildcard (its 1:m)
1559ce556d2SAndreas Gohr        if(strstr($line, '%GROUP%')){
156ad3d68d7SChristopher Smith            // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
1579ce556d2SAndreas Gohr            foreach((array) $USERINFO['grps'] as $grp){
158b78bf706Sromain                $nid   = str_replace('%GROUP%',cleanID($grp),$id);
15932e82180SAndreas Gohr                $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest);
16032e82180SAndreas Gohr                $out[] = "$nid\t$nrest";
161b78bf706Sromain            }
16232e82180SAndreas Gohr        } else {
16332e82180SAndreas Gohr            $out[] = "$id\t$rest";
164a8fe108bSGuy Brand        }
16511799630Sandi    }
1669ce556d2SAndreas Gohr
16732e82180SAndreas Gohr    return $out;
168f3f0262cSandi}
169f3f0262cSandi
170ab5d26daSAndreas Gohr/**
171ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK
172ab5d26daSAndreas Gohr *
173ab5d26daSAndreas Gohr * @param $evdata
174ab5d26daSAndreas Gohr * @return bool
175ab5d26daSAndreas Gohr */
176b5ee21aaSAdrian Langfunction auth_login_wrapper($evdata) {
177ab5d26daSAndreas Gohr    return auth_login(
178ab5d26daSAndreas Gohr        $evdata['user'],
179b5ee21aaSAdrian Lang        $evdata['password'],
180b5ee21aaSAdrian Lang        $evdata['sticky'],
181ab5d26daSAndreas Gohr        $evdata['silent']
182ab5d26daSAndreas Gohr    );
183b5ee21aaSAdrian Lang}
184b5ee21aaSAdrian Lang
185f3f0262cSandi/**
186f3f0262cSandi * This tries to login the user based on the sent auth credentials
187f3f0262cSandi *
188f3f0262cSandi * The authentication works like this: if a username was given
18915fae107Sandi * a new login is assumed and user/password are checked. If they
19015fae107Sandi * are correct the password is encrypted with blowfish and stored
19115fae107Sandi * together with the username in a cookie - the same info is stored
19215fae107Sandi * in the session, too. Additonally a browserID is stored in the
19315fae107Sandi * session.
19415fae107Sandi *
19515fae107Sandi * If no username was given the cookie is checked: if the username,
19615fae107Sandi * crypted password and browserID match between session and cookie
19715fae107Sandi * no further testing is done and the user is accepted
19815fae107Sandi *
19915fae107Sandi * If a cookie was found but no session info was availabe the
200136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
20115fae107Sandi * together with username rechecked by calling this function again.
202f3f0262cSandi *
203f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
204f3f0262cSandi * are set.
20515fae107Sandi *
20615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
20715fae107Sandi *
20815fae107Sandi * @param   string  $user    Username
20915fae107Sandi * @param   string  $pass    Cleartext Password
21015fae107Sandi * @param   bool    $sticky  Cookie should not expire
211f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
21215fae107Sandi * @return  bool             true on successful auth
213f3f0262cSandi */
214f112c2faSAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false) {
215f3f0262cSandi    global $USERINFO;
216f3f0262cSandi    global $conf;
217f3f0262cSandi    global $lang;
21827058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
219cd52f92dSchris    global $auth;
220ab5d26daSAndreas Gohr
221132bdbfeSandi    $sticky ? $sticky = true : $sticky = false; //sanity check
222f3f0262cSandi
223beca106aSAdrian Lang    if(!$auth) return false;
224beca106aSAdrian Lang
225bbbd6568SAndreas Gohr    if(!empty($user)) {
226132bdbfeSandi        //usual login
227cd52f92dSchris        if($auth->checkPass($user, $pass)) {
228132bdbfeSandi            // make logininfo globally available
229f3f0262cSandi            $_SERVER['REMOTE_USER'] = $user;
23030d544a4SMichael Hamann            $secret                 = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
23104369c3eSMichael Hamann            auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
232132bdbfeSandi            return true;
233f3f0262cSandi        } else {
234f3f0262cSandi            //invalid credentials - log off
235f112c2faSAndreas Gohr            if(!$silent) msg($lang['badlogin'], -1);
236f3f0262cSandi            auth_logoff();
237132bdbfeSandi            return false;
238f3f0262cSandi        }
239f3f0262cSandi    } else {
240132bdbfeSandi        // read cookie information
241645c0a36SAndreas Gohr        list($user, $sticky, $pass) = auth_getCookie();
242132bdbfeSandi        if($user && $pass) {
243132bdbfeSandi            // we got a cookie - see if we can trust it
244fa7c70ffSAdrian Lang
245fa7c70ffSAdrian Lang            // get session info
246fa7c70ffSAdrian Lang            $session = $_SESSION[DOKU_COOKIE]['auth'];
247132bdbfeSandi            if(isset($session) &&
2487172dbc0SAndreas Gohr                $auth->useSessionCache($user) &&
2494c989037SChris Smith                ($session['time'] >= time() - $conf['auth_security_timeout']) &&
250132bdbfeSandi                ($session['user'] == $user) &&
251234ce57eSAndreas Gohr                ($session['pass'] == sha1($pass)) && //still crypted
252ab5d26daSAndreas Gohr                ($session['buid'] == auth_browseruid())
253ab5d26daSAndreas Gohr            ) {
254234ce57eSAndreas Gohr
255132bdbfeSandi                // he has session, cookie and browser right - let him in
256132bdbfeSandi                $_SERVER['REMOTE_USER'] = $user;
257132bdbfeSandi                $USERINFO               = $session['info']; //FIXME move all references to session
258132bdbfeSandi                return true;
259132bdbfeSandi            }
260f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
26130d544a4SMichael Hamann            $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
26204369c3eSMichael Hamann            $pass   = auth_decrypt($pass, $secret);
263f112c2faSAndreas Gohr            return auth_login($user, $pass, $sticky, true);
264132bdbfeSandi        }
265132bdbfeSandi    }
266f3f0262cSandi    //just to be sure
267883179a4SAndreas Gohr    auth_logoff(true);
268132bdbfeSandi    return false;
269f3f0262cSandi}
270132bdbfeSandi
271132bdbfeSandi/**
272f13fa892SAndreas Gohr * Checks if a given authentication token was stored in the session
273f13fa892SAndreas Gohr *
274f13fa892SAndreas Gohr * Will setup authentication data using data from the session if the
275f13fa892SAndreas Gohr * token is correct. Will exit with a 401 Status if not.
276f13fa892SAndreas Gohr *
277f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
278f13fa892SAndreas Gohr * @param  string $token The authentication token
279f13fa892SAndreas Gohr * @return boolean true (or will exit on failure)
280f13fa892SAndreas Gohr */
281f13fa892SAndreas Gohrfunction auth_validateToken($token) {
282f13fa892SAndreas Gohr    if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']) {
283f13fa892SAndreas Gohr        // bad token
2849d2e1be6SAndreas Gohr        http_status(401);
285f13fa892SAndreas Gohr        print 'Invalid auth token - maybe the session timed out';
286f13fa892SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
287f13fa892SAndreas Gohr        exit;
288f13fa892SAndreas Gohr    }
289f13fa892SAndreas Gohr    // still here? trust the session data
290f13fa892SAndreas Gohr    global $USERINFO;
291f13fa892SAndreas Gohr    $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
292f13fa892SAndreas Gohr    $USERINFO               = $_SESSION[DOKU_COOKIE]['auth']['info'];
293f13fa892SAndreas Gohr    return true;
294f13fa892SAndreas Gohr}
295f13fa892SAndreas Gohr
296f13fa892SAndreas Gohr/**
297f13fa892SAndreas Gohr * Create an auth token and store it in the session
298f13fa892SAndreas Gohr *
299f13fa892SAndreas Gohr * NOTE: this is completely unrelated to the getSecurityToken() function
300f13fa892SAndreas Gohr *
301f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
302f13fa892SAndreas Gohr * @return string The auth token
303f13fa892SAndreas Gohr */
304f13fa892SAndreas Gohrfunction auth_createToken() {
305483b6238SMichael Hamann    $token = md5(auth_randombytes(16));
30609c2d803SAndreas Gohr    @session_start(); // reopen the session if needed
307f13fa892SAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
30809c2d803SAndreas Gohr    session_write_close();
309f13fa892SAndreas Gohr    return $token;
310f13fa892SAndreas Gohr}
311f13fa892SAndreas Gohr
312f13fa892SAndreas Gohr/**
313136ce040Sandi * Builds a pseudo UID from browser and IP data
314132bdbfeSandi *
315132bdbfeSandi * This is neither unique nor unfakable - still it adds some
316136ce040Sandi * security. Using the first part of the IP makes sure
31780b4f376SAndreas Gohr * proxy farms like AOLs are still okay.
31815fae107Sandi *
31915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
32015fae107Sandi *
32115fae107Sandi * @return  string  a MD5 sum of various browser headers
322132bdbfeSandi */
323132bdbfeSandifunction auth_browseruid() {
3242f9daf16SAndreas Gohr    $ip  = clientIP(true);
325132bdbfeSandi    $uid = '';
326132bdbfeSandi    $uid .= $_SERVER['HTTP_USER_AGENT'];
327132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
328132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
3292f9daf16SAndreas Gohr    $uid .= substr($ip, 0, strpos($ip, '.'));
33080b4f376SAndreas Gohr    $uid = strtolower($uid);
331132bdbfeSandi    return md5($uid);
332132bdbfeSandi}
333132bdbfeSandi
334132bdbfeSandi/**
335132bdbfeSandi * Creates a random key to encrypt the password in cookies
33615fae107Sandi *
33715fae107Sandi * This function tries to read the password for encrypting
33898407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
33915fae107Sandi * if no such file is found a random key is created and
34015fae107Sandi * and stored in this file.
34115fae107Sandi *
34215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
34332ed2b36SAndreas Gohr * @param   bool $addsession if true, the sessionid is added to the salt
34430d544a4SMichael Hamann * @param   bool $secure     if security is more important than keeping the old value
34515fae107Sandi * @return  string
346132bdbfeSandi */
34730d544a4SMichael Hamannfunction auth_cookiesalt($addsession = false, $secure = false) {
348132bdbfeSandi    global $conf;
34998407a7aSandi    $file = $conf['metadir'].'/_htcookiesalt';
35030d544a4SMichael Hamann    if ($secure || !file_exists($file)) {
35130d544a4SMichael Hamann        $file = $conf['metadir'].'/_htcookiesalt2';
35230d544a4SMichael Hamann    }
353132bdbfeSandi    $salt = io_readFile($file);
354132bdbfeSandi    if(empty($salt)) {
35530d544a4SMichael Hamann        $salt = bin2hex(auth_randombytes(64));
356132bdbfeSandi        io_saveFile($file, $salt);
357132bdbfeSandi    }
35832ed2b36SAndreas Gohr    if($addsession) {
35932ed2b36SAndreas Gohr        $salt .= session_id();
36032ed2b36SAndreas Gohr    }
361132bdbfeSandi    return $salt;
362f3f0262cSandi}
363f3f0262cSandi
364f3f0262cSandi/**
365483b6238SMichael Hamann * Return truly (pseudo) random bytes if available, otherwise fall back to mt_rand
366483b6238SMichael Hamann *
367483b6238SMichael Hamann * @author Mark Seecof
368483b6238SMichael Hamann * @author Michael Hamann <michael@content-space.de>
369483b6238SMichael Hamann * @link   http://www.php.net/manual/de/function.mt-rand.php#83655
370483b6238SMichael Hamann * @param int $length number of bytes to get
371483b6238SMichael Hamann * @return string binary random strings
372483b6238SMichael Hamann */
373483b6238SMichael Hamannfunction auth_randombytes($length) {
374483b6238SMichael Hamann    $strong = false;
375483b6238SMichael Hamann    $rbytes = false;
376483b6238SMichael Hamann
377483b6238SMichael Hamann    if (function_exists('openssl_random_pseudo_bytes')
378483b6238SMichael Hamann        && (version_compare(PHP_VERSION, '5.3.4') >= 0
379483b6238SMichael Hamann            || strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')
380483b6238SMichael Hamann    ) {
381483b6238SMichael Hamann        $rbytes = openssl_random_pseudo_bytes($length, $strong);
382483b6238SMichael Hamann    }
383483b6238SMichael Hamann
384483b6238SMichael Hamann    if (!$strong && function_exists('mcrypt_create_iv')
385483b6238SMichael Hamann        && (version_compare(PHP_VERSION, '5.3.7') >= 0
386483b6238SMichael Hamann            || strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')
387483b6238SMichael Hamann    ) {
388483b6238SMichael Hamann        $rbytes = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
389483b6238SMichael Hamann        if ($rbytes !== false && strlen($rbytes) === $length) {
390483b6238SMichael Hamann            $strong = true;
391483b6238SMichael Hamann        }
392483b6238SMichael Hamann    }
393483b6238SMichael Hamann
394483b6238SMichael Hamann    // If no strong randoms available, try OS the specific ways
395483b6238SMichael Hamann    if(!$strong) {
396483b6238SMichael Hamann        // Unix/Linux platform
397483b6238SMichael Hamann        $fp = @fopen('/dev/urandom', 'rb');
398483b6238SMichael Hamann        if($fp !== false) {
399483b6238SMichael Hamann            $rbytes = fread($fp, $length);
400483b6238SMichael Hamann            fclose($fp);
401483b6238SMichael Hamann        }
402483b6238SMichael Hamann
403483b6238SMichael Hamann        // MS-Windows platform
404483b6238SMichael Hamann        if(class_exists('COM')) {
405483b6238SMichael Hamann            // http://msdn.microsoft.com/en-us/library/aa388176(VS.85).aspx
406483b6238SMichael Hamann            try {
407483b6238SMichael Hamann                $CAPI_Util = new COM('CAPICOM.Utilities.1');
408483b6238SMichael Hamann                $rbytes    = $CAPI_Util->GetRandom($length, 0);
409483b6238SMichael Hamann
410483b6238SMichael Hamann                // if we ask for binary data PHP munges it, so we
411483b6238SMichael Hamann                // request base64 return value.
412483b6238SMichael Hamann                if($rbytes) $rbytes = base64_decode($rbytes);
413483b6238SMichael Hamann            } catch(Exception $ex) {
414483b6238SMichael Hamann                // fail
415483b6238SMichael Hamann            }
416483b6238SMichael Hamann        }
417483b6238SMichael Hamann    }
418483b6238SMichael Hamann    if(strlen($rbytes) < $length) $rbytes = false;
419483b6238SMichael Hamann
420483b6238SMichael Hamann    // still no random bytes available - fall back to mt_rand()
421483b6238SMichael Hamann    if($rbytes === false) {
422483b6238SMichael Hamann        $rbytes = '';
423483b6238SMichael Hamann        for ($i = 0; $i < $length; ++$i) {
424483b6238SMichael Hamann            $rbytes .= chr(mt_rand(0, 255));
425483b6238SMichael Hamann        }
426483b6238SMichael Hamann    }
427483b6238SMichael Hamann
428483b6238SMichael Hamann    return $rbytes;
429483b6238SMichael Hamann}
430483b6238SMichael Hamann
431483b6238SMichael Hamann/**
432483b6238SMichael Hamann * Random number generator using the best available source
433483b6238SMichael Hamann *
434483b6238SMichael Hamann * @author Michael Samuel
435483b6238SMichael Hamann * @author Michael Hamann <michael@content-space.de>
436483b6238SMichael Hamann * @param int $min
437483b6238SMichael Hamann * @param int $max
438483b6238SMichael Hamann * @return int
439483b6238SMichael Hamann */
440483b6238SMichael Hamannfunction auth_random($min, $max) {
441483b6238SMichael Hamann    $abs_max = $max - $min;
442483b6238SMichael Hamann
443483b6238SMichael Hamann    $nbits = 0;
444483b6238SMichael Hamann    for ($n = $abs_max; $n > 0; $n >>= 1) {
445483b6238SMichael Hamann        ++$nbits;
446483b6238SMichael Hamann    }
447483b6238SMichael Hamann
448483b6238SMichael Hamann    $mask = (1 << $nbits) - 1;
449483b6238SMichael Hamann    do {
450483b6238SMichael Hamann        $bytes    = auth_randombytes(PHP_INT_SIZE);
451483b6238SMichael Hamann        $integers = unpack('Inum', $bytes);
452483b6238SMichael Hamann        $integer  = $integers["num"] & $mask;
453483b6238SMichael Hamann    } while ($integer > $abs_max);
454483b6238SMichael Hamann
455483b6238SMichael Hamann    return $min + $integer;
456483b6238SMichael Hamann}
457483b6238SMichael Hamann
458483b6238SMichael Hamann/**
45904369c3eSMichael Hamann * Encrypt data using the given secret using AES
46004369c3eSMichael Hamann *
46104369c3eSMichael Hamann * The mode is CBC with a random initialization vector, the key is derived
46204369c3eSMichael Hamann * using pbkdf2.
46304369c3eSMichael Hamann *
46404369c3eSMichael Hamann * @param string $data   The data that shall be encrypted
46504369c3eSMichael Hamann * @param string $secret The secret/password that shall be used
46604369c3eSMichael Hamann * @return string The ciphertext
46704369c3eSMichael Hamann */
46804369c3eSMichael Hamannfunction auth_encrypt($data, $secret) {
46904369c3eSMichael Hamann    $iv     = auth_randombytes(16);
47004369c3eSMichael Hamann    $cipher = new Crypt_AES();
47104369c3eSMichael Hamann    $cipher->setPassword($secret);
47204369c3eSMichael Hamann
4737b650cefSMichael Hamann    /*
4747b650cefSMichael Hamann    this uses the encrypted IV as IV as suggested in
4757b650cefSMichael Hamann    http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
4767b650cefSMichael Hamann    for unique but necessarily random IVs. The resulting ciphertext is
4777b650cefSMichael Hamann    compatible to ciphertext that was created using a "normal" IV.
4787b650cefSMichael Hamann    */
47904369c3eSMichael Hamann    return $cipher->encrypt($iv.$data);
48004369c3eSMichael Hamann}
48104369c3eSMichael Hamann
48204369c3eSMichael Hamann/**
48304369c3eSMichael Hamann * Decrypt the given AES ciphertext
48404369c3eSMichael Hamann *
48504369c3eSMichael Hamann * The mode is CBC, the key is derived using pbkdf2
48604369c3eSMichael Hamann *
48704369c3eSMichael Hamann * @param string $ciphertext The encrypted data
48804369c3eSMichael Hamann * @param string $secret     The secret/password that shall be used
48904369c3eSMichael Hamann * @return string The decrypted data
49004369c3eSMichael Hamann */
49104369c3eSMichael Hamannfunction auth_decrypt($ciphertext, $secret) {
4927b650cefSMichael Hamann    $iv     = substr($ciphertext, 0, 16);
49304369c3eSMichael Hamann    $cipher = new Crypt_AES();
49404369c3eSMichael Hamann    $cipher->setPassword($secret);
4957b650cefSMichael Hamann    $cipher->setIV($iv);
49604369c3eSMichael Hamann
4977b650cefSMichael Hamann    return $cipher->decrypt(substr($ciphertext, 16));
49804369c3eSMichael Hamann}
49904369c3eSMichael Hamann
50004369c3eSMichael Hamann/**
501883179a4SAndreas Gohr * Log out the current user
502883179a4SAndreas Gohr *
503f3f0262cSandi * This clears all authentication data and thus log the user
504883179a4SAndreas Gohr * off. It also clears session data.
50515fae107Sandi *
50615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
507883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
508f3f0262cSandi */
509883179a4SAndreas Gohrfunction auth_logoff($keepbc = false) {
510f3f0262cSandi    global $conf;
511f3f0262cSandi    global $USERINFO;
51227058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
5135298a619SAndreas Gohr    global $auth;
51437065e65Sandi
515d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
516e9621d07SAndreas Gohr    @session_start();
517e9621d07SAndreas Gohr
518e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
519e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
520e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
521e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
522e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
523e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
524883179a4SAndreas Gohr    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
525e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
52637065e65Sandi    if(isset($_SERVER['REMOTE_USER']))
527f3f0262cSandi        unset($_SERVER['REMOTE_USER']);
528132bdbfeSandi    $USERINFO = null; //FIXME
529f5c6743cSAndreas Gohr
53073ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
531f5c6743cSAndreas Gohr    if(version_compare(PHP_VERSION, '5.2.0', '>')) {
53273ab87deSGabriel Birke        setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
533f5c6743cSAndreas Gohr    } else {
53473ab87deSGabriel Birke        setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
535f5c6743cSAndreas Gohr    }
5365298a619SAndreas Gohr
537880f62faSAndreas Gohr    if($auth) $auth->logOff();
538f3f0262cSandi}
539f3f0262cSandi
540f3f0262cSandi/**
541f8cc712eSAndreas Gohr * Check if a user is a manager
542f8cc712eSAndreas Gohr *
543f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
544f8cc712eSAndreas Gohr * user.
545f8cc712eSAndreas Gohr *
546f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
547f8cc712eSAndreas Gohr *
548f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
549f8cc712eSAndreas Gohr * @see    auth_isadmin
550ab5d26daSAndreas Gohr * @param  string $user       Username
551ab5d26daSAndreas Gohr * @param  array  $groups     List of groups the user is in
552ab5d26daSAndreas Gohr * @param  bool   $adminonly  when true checks if user is admin
553ab5d26daSAndreas Gohr * @return bool
554f8cc712eSAndreas Gohr */
555f8cc712eSAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false) {
556f8cc712eSAndreas Gohr    global $conf;
557f8cc712eSAndreas Gohr    global $USERINFO;
55827058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
559d752aedeSAndreas Gohr    global $auth;
560f8cc712eSAndreas Gohr
561beca106aSAdrian Lang    if(!$auth) return false;
562c66972f2SAdrian Lang    if(is_null($user)) {
563c66972f2SAdrian Lang        if(!isset($_SERVER['REMOTE_USER'])) {
564c66972f2SAdrian Lang            return false;
565c66972f2SAdrian Lang        } else {
566c66972f2SAdrian Lang            $user = $_SERVER['REMOTE_USER'];
567c66972f2SAdrian Lang        }
568c66972f2SAdrian Lang    }
569d6dc956fSAndreas Gohr    if(is_null($groups)) {
570d6dc956fSAndreas Gohr        $groups = (array) $USERINFO['grps'];
571e259aa79SAndreas Gohr    }
572e259aa79SAndreas Gohr
573d6dc956fSAndreas Gohr    // check superuser match
574d6dc956fSAndreas Gohr    if(auth_isMember($conf['superuser'], $user, $groups)) return true;
575d6dc956fSAndreas Gohr    if($adminonly) return false;
576e259aa79SAndreas Gohr    // check managers
577d6dc956fSAndreas Gohr    if(auth_isMember($conf['manager'], $user, $groups)) return true;
57800ce12daSChris Smith
579f8cc712eSAndreas Gohr    return false;
580f8cc712eSAndreas Gohr}
581f8cc712eSAndreas Gohr
582f8cc712eSAndreas Gohr/**
583f8cc712eSAndreas Gohr * Check if a user is admin
584f8cc712eSAndreas Gohr *
585f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
586f8cc712eSAndreas Gohr *
587f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
588f8cc712eSAndreas Gohr *
589f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
590ab5d26daSAndreas Gohr * @see auth_ismanager()
591ab5d26daSAndreas Gohr * @param  string $user       Username
592ab5d26daSAndreas Gohr * @param  array  $groups     List of groups the user is in
593ab5d26daSAndreas Gohr * @return bool
594f8cc712eSAndreas Gohr */
595f8cc712eSAndreas Gohrfunction auth_isadmin($user = null, $groups = null) {
596f8cc712eSAndreas Gohr    return auth_ismanager($user, $groups, true);
597f8cc712eSAndreas Gohr}
598f8cc712eSAndreas Gohr
599d6dc956fSAndreas Gohr/**
600d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
601d6dc956fSAndreas Gohr * users and groups to determine membership status
602d6dc956fSAndreas Gohr *
603d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
604d6dc956fSAndreas Gohr *
605d6dc956fSAndreas Gohr * @param $memberlist string commaseparated list of allowed users and groups
606d6dc956fSAndreas Gohr * @param $user       string user to match against
607d6dc956fSAndreas Gohr * @param $groups     array  groups the user is member of
6085446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
609d6dc956fSAndreas Gohr */
610d6dc956fSAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups) {
61127058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
612d6dc956fSAndreas Gohr    global $auth;
613d6dc956fSAndreas Gohr    if(!$auth) return false;
614d6dc956fSAndreas Gohr
615d6dc956fSAndreas Gohr    // clean user and groups
6164f56ecbfSAdrian Lang    if(!$auth->isCaseSensitive()) {
617d6dc956fSAndreas Gohr        $user   = utf8_strtolower($user);
618d6dc956fSAndreas Gohr        $groups = array_map('utf8_strtolower', $groups);
619d6dc956fSAndreas Gohr    }
620d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
621d6dc956fSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), $groups);
622d6dc956fSAndreas Gohr
623d6dc956fSAndreas Gohr    // extract the memberlist
624d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
625d6dc956fSAndreas Gohr    $members = array_map('trim', $members);
626d6dc956fSAndreas Gohr    $members = array_unique($members);
627d6dc956fSAndreas Gohr    $members = array_filter($members);
628d6dc956fSAndreas Gohr
629d6dc956fSAndreas Gohr    // compare cleaned values
630d6dc956fSAndreas Gohr    foreach($members as $member) {
6314f56ecbfSAdrian Lang        if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member);
632d6dc956fSAndreas Gohr        if($member[0] == '@') {
633d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
634d6dc956fSAndreas Gohr            if(in_array($member, $groups)) return true;
635d6dc956fSAndreas Gohr        } else {
636d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
637d6dc956fSAndreas Gohr            if($member == $user) return true;
638d6dc956fSAndreas Gohr        }
639d6dc956fSAndreas Gohr    }
640d6dc956fSAndreas Gohr
641d6dc956fSAndreas Gohr    // still here? not a member!
642d6dc956fSAndreas Gohr    return false;
643d6dc956fSAndreas Gohr}
644d6dc956fSAndreas Gohr
645f8cc712eSAndreas Gohr/**
64615fae107Sandi * Convinience function for auth_aclcheck()
64715fae107Sandi *
64815fae107Sandi * This checks the permissions for the current user
64915fae107Sandi *
65015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
65115fae107Sandi *
6521698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
65315fae107Sandi * @return int          permission level
654f3f0262cSandi */
655f3f0262cSandifunction auth_quickaclcheck($id) {
656f3f0262cSandi    global $conf;
657f3f0262cSandi    global $USERINFO;
658f3f0262cSandi    # if no ACL is used always return upload rights
659f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
660f3f0262cSandi    return auth_aclcheck($id, $_SERVER['REMOTE_USER'], $USERINFO['grps']);
661f3f0262cSandi}
662f3f0262cSandi
663f3f0262cSandi/**
664c17acc9fSAndreas Gohr * Returns the maximum rights a user has for the given ID or its namespace
66515fae107Sandi *
66615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
667c17acc9fSAndreas Gohr * @triggers AUTH_ACL_CHECK
6681698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
66915fae107Sandi * @param  string       $user   Username
6703272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
67115fae107Sandi * @return int             permission level
672f3f0262cSandi */
673f3f0262cSandifunction auth_aclcheck($id, $user, $groups) {
674c17acc9fSAndreas Gohr    $data = array(
675c17acc9fSAndreas Gohr        'id'     => $id,
676c17acc9fSAndreas Gohr        'user'   => $user,
677c17acc9fSAndreas Gohr        'groups' => $groups
678c17acc9fSAndreas Gohr    );
679c17acc9fSAndreas Gohr
680c17acc9fSAndreas Gohr    return trigger_event('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
681c17acc9fSAndreas Gohr}
682c17acc9fSAndreas Gohr
683c17acc9fSAndreas Gohr/**
684c17acc9fSAndreas Gohr * default ACL check method
685c17acc9fSAndreas Gohr *
686c17acc9fSAndreas Gohr * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
687c17acc9fSAndreas Gohr *
688c17acc9fSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
689c17acc9fSAndreas Gohr * @param  array $data event data
690c17acc9fSAndreas Gohr * @return int   permission level
691c17acc9fSAndreas Gohr */
692c17acc9fSAndreas Gohrfunction auth_aclcheck_cb($data) {
693c17acc9fSAndreas Gohr    $id     =& $data['id'];
694c17acc9fSAndreas Gohr    $user   =& $data['user'];
695c17acc9fSAndreas Gohr    $groups =& $data['groups'];
696c17acc9fSAndreas Gohr
697f3f0262cSandi    global $conf;
698f3f0262cSandi    global $AUTH_ACL;
69927058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
700d752aedeSAndreas Gohr    global $auth;
701f3f0262cSandi
70285d03f68SAndreas Gohr    // if no ACL is used always return upload rights
703f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
704beca106aSAdrian Lang    if(!$auth) return AUTH_NONE;
705f3f0262cSandi
706074cf26bSandi    //make sure groups is an array
707074cf26bSandi    if(!is_array($groups)) $groups = array();
708074cf26bSandi
70985d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
710ab5d26daSAndreas Gohr    if(auth_isadmin($user, $groups)) {
711ab5d26daSAndreas Gohr        return AUTH_ADMIN;
712ab5d26daSAndreas Gohr    }
71385d03f68SAndreas Gohr
714eb3ce0d5SKazutaka Miyasaka    if(!$auth->isCaseSensitive()) {
715eb3ce0d5SKazutaka Miyasaka        $user   = utf8_strtolower($user);
716eb3ce0d5SKazutaka Miyasaka        $groups = array_map('utf8_strtolower', $groups);
717eb3ce0d5SKazutaka Miyasaka    }
718d752aedeSAndreas Gohr    $user   = $auth->cleanUser($user);
719d752aedeSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
72085d03f68SAndreas Gohr    $user   = auth_nameencode($user);
72185d03f68SAndreas Gohr
7226c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
7232cd2db38Sandi    $cnt = count($groups);
7242cd2db38Sandi    for($i = 0; $i < $cnt; $i++) {
7256c2bb100SAndreas Gohr        $groups[$i] = '@'.auth_nameencode($groups[$i]);
72610a76f6fSfrank    }
72710a76f6fSfrank
728f3f0262cSandi    $ns   = getNS($id);
729f3f0262cSandi    $perm = -1;
730f3f0262cSandi
73134aeb4afSAndreas Gohr    if($user || count($groups)) {
732f3f0262cSandi        //add ALL group
733f3f0262cSandi        $groups[] = '@ALL';
734f3f0262cSandi        //add User
73534aeb4afSAndreas Gohr        if($user) $groups[] = $user;
736f3f0262cSandi    } else {
73748d7b7a6SDominik Eckelmann        $groups[] = '@ALL';
738f3f0262cSandi    }
739f3f0262cSandi
740f3f0262cSandi    //check exact match first
74121c3090aSChristopher Smith    $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
742f3f0262cSandi    if(count($matches)) {
743f3f0262cSandi        foreach($matches as $match) {
744f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
74521c3090aSChristopher Smith            $acl   = preg_split('/[ \t]+/', $match);
746eb3ce0d5SKazutaka Miyasaka            if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
747eb3ce0d5SKazutaka Miyasaka                $acl[1] = utf8_strtolower($acl[1]);
748eb3ce0d5SKazutaka Miyasaka            }
74948d7b7a6SDominik Eckelmann            if(!in_array($acl[1], $groups)) {
75048d7b7a6SDominik Eckelmann                continue;
75148d7b7a6SDominik Eckelmann            }
7528ef6b7caSandi            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
753f3f0262cSandi            if($acl[2] > $perm) {
754f3f0262cSandi                $perm = $acl[2];
755f3f0262cSandi            }
756f3f0262cSandi        }
757f3f0262cSandi        if($perm > -1) {
758f3f0262cSandi            //we had a match - return it
759def492a2SGuillaume Turri            return (int) $perm;
760f3f0262cSandi        }
761f3f0262cSandi    }
762f3f0262cSandi
763f3f0262cSandi    //still here? do the namespace checks
764f3f0262cSandi    if($ns) {
7653e304b55SMichael Hamann        $path = $ns.':*';
766f3f0262cSandi    } else {
7673e304b55SMichael Hamann        $path = '*'; //root document
768f3f0262cSandi    }
769f3f0262cSandi
770f3f0262cSandi    do {
77121c3090aSChristopher Smith        $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
772f3f0262cSandi        if(count($matches)) {
773f3f0262cSandi            foreach($matches as $match) {
774f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
77521c3090aSChristopher Smith                $acl   = preg_split('/[ \t]+/', $match);
776eb3ce0d5SKazutaka Miyasaka                if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
777eb3ce0d5SKazutaka Miyasaka                    $acl[1] = utf8_strtolower($acl[1]);
778eb3ce0d5SKazutaka Miyasaka                }
77948d7b7a6SDominik Eckelmann                if(!in_array($acl[1], $groups)) {
78048d7b7a6SDominik Eckelmann                    continue;
78148d7b7a6SDominik Eckelmann                }
7828ef6b7caSandi                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
783f3f0262cSandi                if($acl[2] > $perm) {
784f3f0262cSandi                    $perm = $acl[2];
785f3f0262cSandi                }
786f3f0262cSandi            }
787f3f0262cSandi            //we had a match - return it
78848d7b7a6SDominik Eckelmann            if($perm != -1) {
789def492a2SGuillaume Turri                return (int) $perm;
790f3f0262cSandi            }
79148d7b7a6SDominik Eckelmann        }
792f3f0262cSandi        //get next higher namespace
793f3f0262cSandi        $ns = getNS($ns);
794f3f0262cSandi
7953e304b55SMichael Hamann        if($path != '*') {
7963e304b55SMichael Hamann            $path = $ns.':*';
7973e304b55SMichael Hamann            if($path == ':*') $path = '*';
798f3f0262cSandi        } else {
799f3f0262cSandi            //we did this already
800f3f0262cSandi            //looks like there is something wrong with the ACL
801f3f0262cSandi            //break here
802d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
803d5ce66f6SAndreas Gohr            return AUTH_NONE;
804f3f0262cSandi        }
805f3f0262cSandi    } while(1); //this should never loop endless
806ab5d26daSAndreas Gohr    return AUTH_NONE;
807f3f0262cSandi}
808f3f0262cSandi
809f3f0262cSandi/**
8106c2bb100SAndreas Gohr * Encode ASCII special chars
8116c2bb100SAndreas Gohr *
8126c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
8136c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
8146c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
8156c2bb100SAndreas Gohr * urlencoding!).
8166c2bb100SAndreas Gohr *
8176c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
8186c2bb100SAndreas Gohr *
8196c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
8206c2bb100SAndreas Gohr * @see rawurldecode()
8216c2bb100SAndreas Gohr */
822e838fc2eSAndreas Gohrfunction auth_nameencode($name, $skip_group = false) {
823a424cd8eSchris    global $cache_authname;
824a424cd8eSchris    $cache =& $cache_authname;
82531784267SAndreas Gohr    $name  = (string) $name;
826a424cd8eSchris
82780601d26SAndreas Gohr    // never encode wildcard FS#1955
82880601d26SAndreas Gohr    if($name == '%USER%') return $name;
829b78bf706Sromain    if($name == '%GROUP%') return $name;
83080601d26SAndreas Gohr
831a424cd8eSchris    if(!isset($cache[$name][$skip_group])) {
832e838fc2eSAndreas Gohr        if($skip_group && $name{0} == '@') {
83330f6faf0SChristopher Smith            $cache[$name][$skip_group] = '@'.preg_replace_callback(
83430f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
83530f6faf0SChristopher Smith                'auth_nameencode_callback', substr($name, 1)
836ab5d26daSAndreas Gohr            );
837e838fc2eSAndreas Gohr        } else {
83830f6faf0SChristopher Smith            $cache[$name][$skip_group] = preg_replace_callback(
83930f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
84030f6faf0SChristopher Smith                'auth_nameencode_callback', $name
841ab5d26daSAndreas Gohr            );
842e838fc2eSAndreas Gohr        }
8436c2bb100SAndreas Gohr    }
8446c2bb100SAndreas Gohr
845a424cd8eSchris    return $cache[$name][$skip_group];
846a424cd8eSchris}
847a424cd8eSchris
848*04d68ae4SGerrit Uitslag/**
849*04d68ae4SGerrit Uitslag * callback encodes the matches
850*04d68ae4SGerrit Uitslag *
851*04d68ae4SGerrit Uitslag * @param array $matches first complete match, next matching subpatterms
852*04d68ae4SGerrit Uitslag * @return string
853*04d68ae4SGerrit Uitslag */
85430f6faf0SChristopher Smithfunction auth_nameencode_callback($matches) {
85530f6faf0SChristopher Smith    return '%'.dechex(ord(substr($matches[1],-1)));
85630f6faf0SChristopher Smith}
85730f6faf0SChristopher Smith
8586c2bb100SAndreas Gohr/**
859f3f0262cSandi * Create a pronouncable password
860f3f0262cSandi *
8618a285f7fSAndreas Gohr * The $foruser variable might be used by plugins to run additional password
8628a285f7fSAndreas Gohr * policy checks, but is not used by the default implementation
8638a285f7fSAndreas Gohr *
86415fae107Sandi * @author   Andreas Gohr <andi@splitbrain.org>
86515fae107Sandi * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
8668a285f7fSAndreas Gohr * @triggers AUTH_PASSWORD_GENERATE
86715fae107Sandi *
8688a285f7fSAndreas Gohr * @param  string $foruser username for which the password is generated
86915fae107Sandi * @return string  pronouncable password
870f3f0262cSandi */
8718a285f7fSAndreas Gohrfunction auth_pwgen($foruser = '') {
8728a285f7fSAndreas Gohr    $data = array(
873d628dcf3SAndreas Gohr        'password' => '',
874d628dcf3SAndreas Gohr        'foruser'  => $foruser
8758a285f7fSAndreas Gohr    );
8768a285f7fSAndreas Gohr
8778a285f7fSAndreas Gohr    $evt = new Doku_Event('AUTH_PASSWORD_GENERATE', $data);
8788a285f7fSAndreas Gohr    if($evt->advise_before(true)) {
879f3f0262cSandi        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
880f3f0262cSandi        $v = 'aeiou'; //vowels
881f3f0262cSandi        $a = $c.$v; //both
882987c8d26SAndreas Gohr        $s = '!$%&?+*~#-_:.;,'; // specials
883f3f0262cSandi
884987c8d26SAndreas Gohr        //use thre syllables...
885987c8d26SAndreas Gohr        for($i = 0; $i < 3; $i++) {
886483b6238SMichael Hamann            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
887483b6238SMichael Hamann            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
888483b6238SMichael Hamann            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
889f3f0262cSandi        }
890987c8d26SAndreas Gohr        //... and add a nice number and special
891483b6238SMichael Hamann        $data['password'] .= auth_random(10, 99).$s[auth_random(0, strlen($s) - 1)];
8928a285f7fSAndreas Gohr    }
8938a285f7fSAndreas Gohr    $evt->advise_after();
894f3f0262cSandi
8958a285f7fSAndreas Gohr    return $data['password'];
896f3f0262cSandi}
897f3f0262cSandi
898f3f0262cSandi/**
899f3f0262cSandi * Sends a password to the given user
900f3f0262cSandi *
90115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
902ab5d26daSAndreas Gohr * @param string $user Login name of the user
903ab5d26daSAndreas Gohr * @param string $password The new password in clear text
90415fae107Sandi * @return bool  true on success
905f3f0262cSandi */
906f3f0262cSandifunction auth_sendPassword($user, $password) {
907f3f0262cSandi    global $lang;
90827058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
909cd52f92dSchris    global $auth;
910beca106aSAdrian Lang    if(!$auth) return false;
911cd52f92dSchris
912d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
913cd52f92dSchris    $userinfo = $auth->getUserData($user);
914f3f0262cSandi
91587ddda95Sandi    if(!$userinfo['mail']) return false;
916f3f0262cSandi
917f3f0262cSandi    $text = rawLocale('password');
918d7169d19SAndreas Gohr    $trep = array(
919d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
920d7169d19SAndreas Gohr        'LOGIN'    => $user,
921d7169d19SAndreas Gohr        'PASSWORD' => $password
922d7169d19SAndreas Gohr    );
923f3f0262cSandi
924d7169d19SAndreas Gohr    $mail = new Mailer();
925d7169d19SAndreas Gohr    $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
926d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
927d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
928d7169d19SAndreas Gohr    return $mail->send();
929f3f0262cSandi}
930f3f0262cSandi
931f3f0262cSandi/**
93215fae107Sandi * Register a new user
933f3f0262cSandi *
93415fae107Sandi * This registers a new user - Data is read directly from $_POST
93515fae107Sandi *
93615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
93715fae107Sandi * @return bool  true on success, false on any error
938f3f0262cSandi */
939f3f0262cSandifunction register() {
940f3f0262cSandi    global $lang;
941eb5d07e4Sjan    global $conf;
94227058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
943cd52f92dSchris    global $auth;
94464273335SAndreas Gohr    global $INPUT;
945f3f0262cSandi
94664273335SAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
9473a48618aSAnika Henke    if(!actionOK('register')) return false;
948640145a5Sandi
94964273335SAndreas Gohr    // gather input
95064273335SAndreas Gohr    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
95164273335SAndreas Gohr    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
95264273335SAndreas Gohr    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
95364273335SAndreas Gohr    $pass     = $INPUT->post->str('pass');
95464273335SAndreas Gohr    $passchk  = $INPUT->post->str('passchk');
955d752aedeSAndreas Gohr
95664273335SAndreas Gohr    if(empty($login) || empty($fullname) || empty($email)) {
957f3f0262cSandi        msg($lang['regmissing'], -1);
958f3f0262cSandi        return false;
959f3f0262cSandi    }
960f3f0262cSandi
961cab2716aSmatthias.grimm    if($conf['autopasswd']) {
9628a285f7fSAndreas Gohr        $pass = auth_pwgen($login); // automatically generate password
96364273335SAndreas Gohr    } elseif(empty($pass) || empty($passchk)) {
964bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
965cab2716aSmatthias.grimm        return false;
96664273335SAndreas Gohr    } elseif($pass != $passchk) {
967bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
968cab2716aSmatthias.grimm        return false;
969cab2716aSmatthias.grimm    }
970cab2716aSmatthias.grimm
971f3f0262cSandi    //check mail
97264273335SAndreas Gohr    if(!mail_isvalid($email)) {
973f3f0262cSandi        msg($lang['regbadmail'], -1);
974f3f0262cSandi        return false;
975f3f0262cSandi    }
976f3f0262cSandi
977f3f0262cSandi    //okay try to create the user
97864273335SAndreas Gohr    if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) {
979f3f0262cSandi        msg($lang['reguexists'], -1);
980f3f0262cSandi        return false;
981f3f0262cSandi    }
982f3f0262cSandi
983790b7720SAndreas Gohr    // send notification about the new user
984790b7720SAndreas Gohr    $subscription = new Subscription();
985790b7720SAndreas Gohr    $subscription->send_register($login, $fullname, $email);
98602a498e7Schris
987790b7720SAndreas Gohr    // are we done?
988cab2716aSmatthias.grimm    if(!$conf['autopasswd']) {
989cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
990cab2716aSmatthias.grimm        return true;
991cab2716aSmatthias.grimm    }
992cab2716aSmatthias.grimm
993790b7720SAndreas Gohr    // autogenerated password? then send password to user
99464273335SAndreas Gohr    if(auth_sendPassword($login, $pass)) {
995f3f0262cSandi        msg($lang['regsuccess'], 1);
996f3f0262cSandi        return true;
997f3f0262cSandi    } else {
998f3f0262cSandi        msg($lang['regmailfail'], -1);
999f3f0262cSandi        return false;
1000f3f0262cSandi    }
1001f3f0262cSandi}
1002f3f0262cSandi
100310a76f6fSfrank/**
10048b06d178Schris * Update user profile
10058b06d178Schris *
10068b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
10078b06d178Schris */
10088b06d178Schrisfunction updateprofile() {
10098b06d178Schris    global $conf;
10108b06d178Schris    global $lang;
101127058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
1012cd52f92dSchris    global $auth;
1013bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1014bcc94b2cSAndreas Gohr    global $INPUT;
10158b06d178Schris
1016bcc94b2cSAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
10171b2a85e8SAndreas Gohr    if(!checkSecurityToken()) return false;
10188b06d178Schris
10193a48618aSAnika Henke    if(!actionOK('profile')) {
10208b06d178Schris        msg($lang['profna'], -1);
10218b06d178Schris        return false;
10228b06d178Schris    }
10238b06d178Schris
1024bcc94b2cSAndreas Gohr    $changes         = array();
1025bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
1026bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
1027bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
1028bcc94b2cSAndreas Gohr
1029bcc94b2cSAndreas Gohr    // check misspelled passwords
1030bcc94b2cSAndreas Gohr    if($changes['pass'] != $INPUT->post->str('passchk')) {
1031bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
10328b06d178Schris        return false;
10338b06d178Schris    }
10348b06d178Schris
10358b06d178Schris    // clean fullname and email
1036bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
1037bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
10388b06d178Schris
1039bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
1040bcc94b2cSAndreas Gohr    if((empty($changes['name']) && $auth->canDo('modName')) ||
1041bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
1042ab5d26daSAndreas Gohr    ) {
10438b06d178Schris        msg($lang['profnoempty'], -1);
10448b06d178Schris        return false;
10458b06d178Schris    }
1046bcc94b2cSAndreas Gohr    if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
10478b06d178Schris        msg($lang['regbadmail'], -1);
10488b06d178Schris        return false;
10498b06d178Schris    }
10508b06d178Schris
1051bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
10524c21b7eeSAndreas Gohr
1053bcc94b2cSAndreas Gohr    // check for unavailable capabilities
1054bcc94b2cSAndreas Gohr    if(!$auth->canDo('modName')) unset($changes['name']);
1055bcc94b2cSAndreas Gohr    if(!$auth->canDo('modMail')) unset($changes['mail']);
1056bcc94b2cSAndreas Gohr    if(!$auth->canDo('modPass')) unset($changes['pass']);
1057bcc94b2cSAndreas Gohr
1058bcc94b2cSAndreas Gohr    // anything to do?
10598b06d178Schris    if(!count($changes)) {
10608b06d178Schris        msg($lang['profnochange'], -1);
10618b06d178Schris        return false;
10628b06d178Schris    }
10638b06d178Schris
10648b06d178Schris    if($conf['profileconfirm']) {
1065bcc94b2cSAndreas Gohr        if(!$auth->checkPass($_SERVER['REMOTE_USER'], $INPUT->post->str('oldpass'))) {
106671422fc8SChristopher Smith            msg($lang['badpassconfirm'], -1);
10678b06d178Schris            return false;
10688b06d178Schris        }
10698b06d178Schris    }
10708b06d178Schris
1071a0b5b007SChris Smith    if($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
1072a0b5b007SChris Smith        // update cookie and session with the changed data
107332ed2b36SAndreas Gohr        if($changes['pass']) {
1074ab5d26daSAndreas Gohr            list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
107504369c3eSMichael Hamann            $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1076a0b5b007SChris Smith            auth_setCookie($_SERVER['REMOTE_USER'], $pass, (bool) $sticky);
107732ed2b36SAndreas Gohr        }
107825b2a98cSMichael Klier        return true;
1079a0b5b007SChris Smith    }
1080ab5d26daSAndreas Gohr
1081ab5d26daSAndreas Gohr    return false;
10828b06d178Schris}
10838b06d178Schris
1084*04d68ae4SGerrit Uitslag/**
1085*04d68ae4SGerrit Uitslag * Delete the current logged-in user
1086*04d68ae4SGerrit Uitslag *
1087*04d68ae4SGerrit Uitslag * @return bool true on success, false on any error
1088*04d68ae4SGerrit Uitslag */
10892a7abf2dSChristopher Smithfunction auth_deleteprofile(){
10902a7abf2dSChristopher Smith    global $conf;
10912a7abf2dSChristopher Smith    global $lang;
109273012efdSChristopher Smith    /* @var DokuWiki_Auth_Plugin $auth */
10932a7abf2dSChristopher Smith    global $auth;
10942a7abf2dSChristopher Smith    /* @var Input $INPUT */
10952a7abf2dSChristopher Smith    global $INPUT;
10962a7abf2dSChristopher Smith
10972a7abf2dSChristopher Smith    if(!$INPUT->post->bool('delete')) return false;
10982a7abf2dSChristopher Smith    if(!checkSecurityToken()) return false;
10992a7abf2dSChristopher Smith
11002a7abf2dSChristopher Smith    // action prevented or auth module disallows
11012a7abf2dSChristopher Smith    if(!actionOK('profile_delete') || !$auth->canDo('delUser')) {
11022a7abf2dSChristopher Smith        msg($lang['profnodelete'], -1);
11032a7abf2dSChristopher Smith        return false;
11042a7abf2dSChristopher Smith    }
11052a7abf2dSChristopher Smith
11062a7abf2dSChristopher Smith    if(!$INPUT->post->bool('confirm_delete')){
11072a7abf2dSChristopher Smith        msg($lang['profconfdeletemissing'], -1);
11082a7abf2dSChristopher Smith        return false;
11092a7abf2dSChristopher Smith    }
11102a7abf2dSChristopher Smith
11112a7abf2dSChristopher Smith    if($conf['profileconfirm']) {
11122a7abf2dSChristopher Smith        if(!$auth->checkPass($_SERVER['REMOTE_USER'], $INPUT->post->str('oldpass'))) {
11132a7abf2dSChristopher Smith            msg($lang['badpassconfirm'], -1);
11142a7abf2dSChristopher Smith            return false;
11152a7abf2dSChristopher Smith        }
11162a7abf2dSChristopher Smith    }
11172a7abf2dSChristopher Smith
11182a7abf2dSChristopher Smith    $deleted[] = $_SERVER['REMOTE_USER'];
111973012efdSChristopher Smith    if($auth->triggerUserMod('delete', array($deleted))) {
11202a7abf2dSChristopher Smith        // force and immediate logout including removing the sticky cookie
11212a7abf2dSChristopher Smith        auth_logoff();
11222a7abf2dSChristopher Smith        return true;
11232a7abf2dSChristopher Smith    }
11242a7abf2dSChristopher Smith
11252a7abf2dSChristopher Smith    return false;
11262a7abf2dSChristopher Smith}
11272a7abf2dSChristopher Smith
11288b06d178Schris/**
11298b06d178Schris * Send a  new password
11308b06d178Schris *
11311d5856cfSAndreas Gohr * This function handles both phases of the password reset:
11321d5856cfSAndreas Gohr *
11331d5856cfSAndreas Gohr *   - handling the first request of password reset
11341d5856cfSAndreas Gohr *   - validating the password reset auth token
11351d5856cfSAndreas Gohr *
11368b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
11378b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
11381d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
11398b06d178Schris *
11408b06d178Schris * @return bool true on success, false on any error
11418b06d178Schris */
11428b06d178Schrisfunction act_resendpwd() {
11438b06d178Schris    global $lang;
11448b06d178Schris    global $conf;
114527058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
1146cd52f92dSchris    global $auth;
1147bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1148bcc94b2cSAndreas Gohr    global $INPUT;
11498b06d178Schris
11503a48618aSAnika Henke    if(!actionOK('resendpwd')) {
11518b06d178Schris        msg($lang['resendna'], -1);
11528b06d178Schris        return false;
11538b06d178Schris    }
11548b06d178Schris
1155bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
11568b06d178Schris
11571d5856cfSAndreas Gohr    if($token) {
1158cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
11591d5856cfSAndreas Gohr
11601d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
11611d5856cfSAndreas Gohr        if(!@file_exists($tfile)) {
11621d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1163bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
11641d5856cfSAndreas Gohr            return false;
11651d5856cfSAndreas Gohr        }
11668a9735e3SAndreas Gohr        // token is only valid for 3 days
11678a9735e3SAndreas Gohr        if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
11688a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1169bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
11701d5856cfSAndreas Gohr            @unlink($tfile);
11718a9735e3SAndreas Gohr            return false;
11728a9735e3SAndreas Gohr        }
11738a9735e3SAndreas Gohr
11748b06d178Schris        $user     = io_readfile($tfile);
1175cd52f92dSchris        $userinfo = $auth->getUserData($user);
11768b06d178Schris        if(!$userinfo['mail']) {
11778b06d178Schris            msg($lang['resendpwdnouser'], -1);
11788b06d178Schris            return false;
11798b06d178Schris        }
11808b06d178Schris
1181cc204bbdSAndreas Gohr        if(!$conf['autopasswd']) { // we let the user choose a password
1182bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
1183bcc94b2cSAndreas Gohr
1184cc204bbdSAndreas Gohr            // password given correctly?
1185bcc94b2cSAndreas Gohr            if(!$pass) return false;
1186bcc94b2cSAndreas Gohr            if($pass != $INPUT->str('passchk')) {
1187451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
1188cc204bbdSAndreas Gohr                return false;
1189cc204bbdSAndreas Gohr            }
1190cc204bbdSAndreas Gohr
1191bcc94b2cSAndreas Gohr            // change it
1192cc204bbdSAndreas Gohr            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1193cc204bbdSAndreas Gohr                msg('error modifying user data', -1);
1194cc204bbdSAndreas Gohr                return false;
1195cc204bbdSAndreas Gohr            }
1196cc204bbdSAndreas Gohr
1197cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
1198cc204bbdSAndreas Gohr
11998a285f7fSAndreas Gohr            $pass = auth_pwgen($user);
12007d3c8d42SGabriel Birke            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
12018b06d178Schris                msg('error modifying user data', -1);
12028b06d178Schris                return false;
12038b06d178Schris            }
12048b06d178Schris
12058b06d178Schris            if(auth_sendPassword($user, $pass)) {
12068b06d178Schris                msg($lang['resendpwdsuccess'], 1);
12078b06d178Schris            } else {
12088b06d178Schris                msg($lang['regmailfail'], -1);
12098b06d178Schris            }
1210cc204bbdSAndreas Gohr        }
1211cc204bbdSAndreas Gohr
1212cc204bbdSAndreas Gohr        @unlink($tfile);
12138b06d178Schris        return true;
12141d5856cfSAndreas Gohr
12151d5856cfSAndreas Gohr    } else {
12161d5856cfSAndreas Gohr        // we're in request phase
12171d5856cfSAndreas Gohr
1218bcc94b2cSAndreas Gohr        if(!$INPUT->post->bool('save')) return false;
12191d5856cfSAndreas Gohr
1220bcc94b2cSAndreas Gohr        if(!$INPUT->post->str('login')) {
12211d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
12221d5856cfSAndreas Gohr            return false;
12231d5856cfSAndreas Gohr        } else {
1224bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
12251d5856cfSAndreas Gohr        }
12261d5856cfSAndreas Gohr
12271d5856cfSAndreas Gohr        $userinfo = $auth->getUserData($user);
12281d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
12291d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
12301d5856cfSAndreas Gohr            return false;
12311d5856cfSAndreas Gohr        }
12321d5856cfSAndreas Gohr
12331d5856cfSAndreas Gohr        // generate auth token
1234483b6238SMichael Hamann        $token = md5(auth_randombytes(16)); // random secret
12351d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
12361d5856cfSAndreas Gohr        $url   = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
12371d5856cfSAndreas Gohr
12381d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
12391d5856cfSAndreas Gohr
12401d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
1241d7169d19SAndreas Gohr        $trep = array(
1242d7169d19SAndreas Gohr            'FULLNAME' => $userinfo['name'],
1243d7169d19SAndreas Gohr            'LOGIN'    => $user,
1244d7169d19SAndreas Gohr            'CONFIRM'  => $url
1245d7169d19SAndreas Gohr        );
12461d5856cfSAndreas Gohr
1247d7169d19SAndreas Gohr        $mail = new Mailer();
1248d7169d19SAndreas Gohr        $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1249d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
1250d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
1251d7169d19SAndreas Gohr        if($mail->send()) {
12521d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
12531d5856cfSAndreas Gohr        } else {
12541d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
12551d5856cfSAndreas Gohr        }
12561d5856cfSAndreas Gohr        return true;
12571d5856cfSAndreas Gohr    }
1258ab5d26daSAndreas Gohr    // never reached
12598b06d178Schris}
12608b06d178Schris
12618b06d178Schris/**
1262b0855b11Sandi * Encrypts a password using the given method and salt
1263b0855b11Sandi *
1264b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1265b0855b11Sandi * is chosen.
1266b0855b11Sandi *
1267b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
1268ab5d26daSAndreas Gohr * @param string $clear The clear text password
1269ab5d26daSAndreas Gohr * @param string $method The hashing method
1270ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1271b0855b11Sandi * @return  string  The crypted password
1272b0855b11Sandi */
1273577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null) {
1274b0855b11Sandi    global $conf;
1275b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
127610a76f6fSfrank
12773a0a2d05SAndreas Gohr    $pass = new PassHash();
12783a0a2d05SAndreas Gohr    $call = 'hash_'.$method;
1279b0855b11Sandi
12803a0a2d05SAndreas Gohr    if(!method_exists($pass, $call)) {
1281b0855b11Sandi        msg("Unsupported crypt method $method", -1);
12823a0a2d05SAndreas Gohr        return false;
1283b0855b11Sandi    }
12843a0a2d05SAndreas Gohr
12853a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1286b0855b11Sandi}
1287b0855b11Sandi
1288b0855b11Sandi/**
1289b0855b11Sandi * Verifies a cleartext password against a crypted hash
1290b0855b11Sandi *
1291b0855b11Sandi * @author Andreas Gohr <andi@splitbrain.org>
1292ab5d26daSAndreas Gohr * @param  string $clear The clear text password
1293ab5d26daSAndreas Gohr * @param  string $crypt The hash to compare with
1294ab5d26daSAndreas Gohr * @return bool true if both match
1295b0855b11Sandi */
1296b0855b11Sandifunction auth_verifyPassword($clear, $crypt) {
12973a0a2d05SAndreas Gohr    $pass = new PassHash();
12983a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1299b0855b11Sandi}
1300340756e4Sandi
1301a0b5b007SChris Smith/**
1302a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1303a0b5b007SChris Smith *
1304a0b5b007SChris Smith * @param string  $user       username
1305a0b5b007SChris Smith * @param string  $pass       encrypted password
1306a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1307ab5d26daSAndreas Gohr * @return bool
1308a0b5b007SChris Smith */
1309a0b5b007SChris Smithfunction auth_setCookie($user, $pass, $sticky) {
1310a0b5b007SChris Smith    global $conf;
131127058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
1312a0b5b007SChris Smith    global $auth;
131379d00841SOliver Geisen    global $USERINFO;
1314a0b5b007SChris Smith
1315beca106aSAdrian Lang    if(!$auth) return false;
1316a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1317a0b5b007SChris Smith
1318a0b5b007SChris Smith    // set cookie
1319645c0a36SAndreas Gohr    $cookie    = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
132073ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1321c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1322a0b5b007SChris Smith    if(version_compare(PHP_VERSION, '5.2.0', '>')) {
132373ab87deSGabriel Birke        setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
1324a0b5b007SChris Smith    } else {
132573ab87deSGabriel Birke        setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
1326a0b5b007SChris Smith    }
1327a0b5b007SChris Smith    // set session
1328a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1329234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1330a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1331a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1332a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1333ab5d26daSAndreas Gohr
1334ab5d26daSAndreas Gohr    return true;
1335a0b5b007SChris Smith}
1336a0b5b007SChris Smith
1337645c0a36SAndreas Gohr/**
1338645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1339645c0a36SAndreas Gohr *
1340645c0a36SAndreas Gohr * @returns array
1341645c0a36SAndreas Gohr */
1342645c0a36SAndreas Gohrfunction auth_getCookie() {
1343c66972f2SAdrian Lang    if(!isset($_COOKIE[DOKU_COOKIE])) {
1344c66972f2SAdrian Lang        return array(null, null, null);
1345c66972f2SAdrian Lang    }
1346645c0a36SAndreas Gohr    list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
1347645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1348645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1349645c0a36SAndreas Gohr    $user   = base64_decode($user);
1350645c0a36SAndreas Gohr    return array($user, $sticky, $pass);
1351645c0a36SAndreas Gohr}
1352645c0a36SAndreas Gohr
1353e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1354