xref: /dokuwiki/inc/auth.php (revision 486f82fcdeb063c787481ca7ff91976dc6961f85)
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
1296348f27SAndreas Gohruse dokuwiki\Extension\AuthPlugin;
1396348f27SAndreas Gohruse dokuwiki\Extension\Event;
1496348f27SAndreas Gohruse dokuwiki\Extension\PluginController;
15c3cc6e05SAndreas Gohruse dokuwiki\PassHash;
1675d66495SMichael Großeuse dokuwiki\Subscriptions\RegistrationSubscriptionSender;
17c3cc6e05SAndreas Gohr
1816905344SAndreas Gohr/**
1916905344SAndreas Gohr * Initialize the auth system.
2016905344SAndreas Gohr *
2116905344SAndreas Gohr * This function is automatically called at the end of init.php
2216905344SAndreas Gohr *
2316905344SAndreas Gohr * This used to be the main() of the auth.php
2416905344SAndreas Gohr *
2516905344SAndreas Gohr * @todo backend loading maybe should be handled by the class autoloader
2616905344SAndreas Gohr * @todo maybe split into multiple functions at the XXX marked positions
27ab5d26daSAndreas Gohr * @triggers AUTH_LOGIN_CHECK
28ab5d26daSAndreas Gohr * @return bool
2916905344SAndreas Gohr */
3016905344SAndreas Gohrfunction auth_setup() {
31742c66f8Schris    global $conf;
32e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
3303c4aec3Schris    global $auth;
34bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
35bcc94b2cSAndreas Gohr    global $INPUT;
369a9714acSDominik Eckelmann    global $AUTH_ACL;
379a9714acSDominik Eckelmann    global $lang;
383a7140a1SAndreas Gohr    /* @var PluginController $plugin_controller */
399c29eea5SJan Schumann    global $plugin_controller;
409a9714acSDominik Eckelmann    $AUTH_ACL = array();
4103c4aec3Schris
4216905344SAndreas Gohr    if(!$conf['useacl']) return false;
4316905344SAndreas Gohr
449c29eea5SJan Schumann    // try to load auth backend from plugins
459c29eea5SJan Schumann    foreach ($plugin_controller->getList('auth') as $plugin) {
469c29eea5SJan Schumann        if ($conf['authtype'] === $plugin) {
47f4476bd9SJan Schumann            $auth = $plugin_controller->load('auth', $plugin);
489c29eea5SJan Schumann            break;
499c29eea5SJan Schumann        }
509c29eea5SJan Schumann    }
518b06d178Schris
526416b708SMichael Hamann    if(!isset($auth) || !$auth){
533094e817SAndreas Gohr        msg($lang['authtempfail'], -1);
543094e817SAndreas Gohr        return false;
553094e817SAndreas Gohr    }
568b06d178Schris
576416b708SMichael Hamann    if ($auth->success == false) {
580f4f4adfSAndreas Gohr        // degrade to unauthenticated user
59ecad51ddSAndreas Gohr        $auth = null;
600f4f4adfSAndreas Gohr        auth_logoff();
61cd52f92dSchris        msg($lang['authtempfail'], -1);
626416b708SMichael Hamann        return false;
63d2dde4ebSMatthias Grimm    }
6416905344SAndreas Gohr
6516905344SAndreas Gohr    // do the login either by cookie or provided credentials XXX
66bcc94b2cSAndreas Gohr    $INPUT->set('http_credentials', false);
67bcc94b2cSAndreas Gohr    if(!$conf['rememberme']) $INPUT->set('r', false);
68bbbd6568SAndreas Gohr
6962bf3ac0SDamien Regad    // Populate Basic Auth user/password from Authorization header
7062bf3ac0SDamien Regad    // Note: with FastCGI, data is in REDIRECT_HTTP_AUTHORIZATION instead of HTTP_AUTHORIZATION
7162bf3ac0SDamien Regad    $header = $INPUT->server->str('HTTP_AUTHORIZATION') ?: $INPUT->server->str('REDIRECT_HTTP_AUTHORIZATION');
7262bf3ac0SDamien Regad    if(preg_match( '~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches )) {
7362bf3ac0SDamien Regad        $userpass = explode(':', base64_decode($matches[1]));
7462bf3ac0SDamien Regad        list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = $userpass;
75528ddc7cSAndreas Gohr    }
76528ddc7cSAndreas Gohr
771e8c9c90SAndreas Gohr    // if no credentials were given try to use HTTP auth (for SSO)
7803062864SAndreas Gohr    if (!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($INPUT->server->str('PHP_AUTH_USER'))) {
7903062864SAndreas Gohr        $INPUT->set('u', $INPUT->server->str('PHP_AUTH_USER'));
8003062864SAndreas Gohr        $INPUT->set('p', $INPUT->server->str('PHP_AUTH_PW'));
81bcc94b2cSAndreas Gohr        $INPUT->set('http_credentials', true);
821e8c9c90SAndreas Gohr    }
831e8c9c90SAndreas Gohr
84395c2f0fSAndreas Gohr    // apply cleaning (auth specific user names, remove control chars)
8593a7873eSAndreas Gohr    if (true === $auth->success) {
86395c2f0fSAndreas Gohr        $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
87395c2f0fSAndreas Gohr        $INPUT->set('p', stripctl($INPUT->str('p')));
88f4476bd9SJan Schumann    }
89191bb90aSAndreas Gohr
9081e99965SPhy    $ok = null;
918eca974cSAndreas Gohr    if (!is_null($auth) && $auth->canDo('external')) {
9281e99965SPhy        $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
9381e99965SPhy    }
9481e99965SPhy
9581e99965SPhy    if ($ok === null) {
9681e99965SPhy        // external trust mechanism not in place, or returns no result,
9781e99965SPhy        // then attempt auth_login
986080c584SRobin Gareus        $evdata = array(
99bcc94b2cSAndreas Gohr            'user'     => $INPUT->str('u'),
100bcc94b2cSAndreas Gohr            'password' => $INPUT->str('p'),
101bcc94b2cSAndreas Gohr            'sticky'   => $INPUT->bool('r'),
102bcc94b2cSAndreas Gohr            'silent'   => $INPUT->bool('http_credentials')
1036080c584SRobin Gareus        );
104cbb44eabSAndreas Gohr        Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
105f5cb575dSAndreas Gohr    }
106f5cb575dSAndreas Gohr
10716905344SAndreas Gohr    //load ACL into a global array XXX
10875c93b77SAndreas Gohr    $AUTH_ACL = auth_loadACL();
109ab5d26daSAndreas Gohr
110ab5d26daSAndreas Gohr    return true;
11175c93b77SAndreas Gohr}
11275c93b77SAndreas Gohr
11375c93b77SAndreas Gohr/**
11475c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards
11575c93b77SAndreas Gohr *
11675c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
11742ea7f44SGerrit Uitslag *
118ab5d26daSAndreas Gohr * @return array
11975c93b77SAndreas Gohr */
12075c93b77SAndreas Gohrfunction auth_loadACL() {
12175c93b77SAndreas Gohr    global $config_cascade;
122b78bf706Sromain    global $USERINFO;
123585bf44eSChristopher Smith    /* @var Input $INPUT */
124585bf44eSChristopher Smith    global $INPUT;
12575c93b77SAndreas Gohr
12675c93b77SAndreas Gohr    if(!is_readable($config_cascade['acl']['default'])) return array();
12775c93b77SAndreas Gohr
12875c93b77SAndreas Gohr    $acl = file($config_cascade['acl']['default']);
12975c93b77SAndreas Gohr
13032e82180SAndreas Gohr    $out = array();
1319ce556d2SAndreas Gohr    foreach($acl as $line) {
1329ce556d2SAndreas Gohr        $line = trim($line);
1332401f18dSSyntaxseed        if(empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
13421c3090aSChristopher Smith        list($id,$rest) = preg_split('/[ \t]+/',$line,2);
13532e82180SAndreas Gohr
136443e135dSChristopher Smith        // substitute user wildcard first (its 1:1)
137ad3d68d7SChristopher Smith        if(strstr($line, '%USER%')){
138ad3d68d7SChristopher Smith            // if user is not logged in, this ACL line is meaningless - skip it
139585bf44eSChristopher Smith            if (!$INPUT->server->has('REMOTE_USER')) continue;
140ad3d68d7SChristopher Smith
141585bf44eSChristopher Smith            $id   = str_replace('%USER%',cleanID($INPUT->server->str('REMOTE_USER')),$id);
142585bf44eSChristopher Smith            $rest = str_replace('%USER%',auth_nameencode($INPUT->server->str('REMOTE_USER')),$rest);
143ad3d68d7SChristopher Smith        }
144ad3d68d7SChristopher Smith
145ad3d68d7SChristopher Smith        // substitute group wildcard (its 1:m)
1469ce556d2SAndreas Gohr        if(strstr($line, '%GROUP%')){
147ad3d68d7SChristopher Smith            // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
14806f34f54SPhy            if(isset($USERINFO['grps'])){
1499ce556d2SAndreas Gohr                foreach((array) $USERINFO['grps'] as $grp){
150b78bf706Sromain                    $nid   = str_replace('%GROUP%',cleanID($grp),$id);
15132e82180SAndreas Gohr                    $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest);
15232e82180SAndreas Gohr                    $out[] = "$nid\t$nrest";
153b78bf706Sromain                }
15406f34f54SPhy            }
15532e82180SAndreas Gohr        } else {
15632e82180SAndreas Gohr            $out[] = "$id\t$rest";
157a8fe108bSGuy Brand        }
15811799630Sandi    }
1599ce556d2SAndreas Gohr
16032e82180SAndreas Gohr    return $out;
161f3f0262cSandi}
162f3f0262cSandi
163ab5d26daSAndreas Gohr/**
164ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK
165ab5d26daSAndreas Gohr *
16642ea7f44SGerrit Uitslag * @param array $evdata
167ab5d26daSAndreas Gohr * @return bool
168ab5d26daSAndreas Gohr */
169b5ee21aaSAdrian Langfunction auth_login_wrapper($evdata) {
170ab5d26daSAndreas Gohr    return auth_login(
171ab5d26daSAndreas Gohr        $evdata['user'],
172b5ee21aaSAdrian Lang        $evdata['password'],
173b5ee21aaSAdrian Lang        $evdata['sticky'],
174ab5d26daSAndreas Gohr        $evdata['silent']
175ab5d26daSAndreas Gohr    );
176b5ee21aaSAdrian Lang}
177b5ee21aaSAdrian Lang
178f3f0262cSandi/**
179f3f0262cSandi * This tries to login the user based on the sent auth credentials
180f3f0262cSandi *
181f3f0262cSandi * The authentication works like this: if a username was given
18215fae107Sandi * a new login is assumed and user/password are checked. If they
18315fae107Sandi * are correct the password is encrypted with blowfish and stored
18415fae107Sandi * together with the username in a cookie - the same info is stored
18515fae107Sandi * in the session, too. Additonally a browserID is stored in the
18615fae107Sandi * session.
18715fae107Sandi *
18815fae107Sandi * If no username was given the cookie is checked: if the username,
18915fae107Sandi * crypted password and browserID match between session and cookie
19015fae107Sandi * no further testing is done and the user is accepted
19115fae107Sandi *
19215fae107Sandi * If a cookie was found but no session info was availabe the
193136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
19415fae107Sandi * together with username rechecked by calling this function again.
195f3f0262cSandi *
196f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
197f3f0262cSandi * are set.
19815fae107Sandi *
19915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
20015fae107Sandi *
20115fae107Sandi * @param   string  $user    Username
20215fae107Sandi * @param   string  $pass    Cleartext Password
20315fae107Sandi * @param   bool    $sticky  Cookie should not expire
204f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
20515fae107Sandi * @return  bool             true on successful auth
206f3f0262cSandi */
207f112c2faSAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false) {
208f3f0262cSandi    global $USERINFO;
209f3f0262cSandi    global $conf;
210f3f0262cSandi    global $lang;
211e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
212cd52f92dSchris    global $auth;
213585bf44eSChristopher Smith    /* @var Input $INPUT */
214585bf44eSChristopher Smith    global $INPUT;
215ab5d26daSAndreas Gohr
216132bdbfeSandi    $sticky ? $sticky = true : $sticky = false; //sanity check
217f3f0262cSandi
218beca106aSAdrian Lang    if(!$auth) return false;
219beca106aSAdrian Lang
220bbbd6568SAndreas Gohr    if(!empty($user)) {
221132bdbfeSandi        //usual login
2225e9e1054SAndreas Gohr        if(!empty($pass) && $auth->checkPass($user, $pass)) {
223132bdbfeSandi            // make logininfo globally available
224585bf44eSChristopher Smith            $INPUT->server->set('REMOTE_USER', $user);
22530d544a4SMichael Hamann            $secret                 = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
22604369c3eSMichael Hamann            auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
227132bdbfeSandi            return true;
228f3f0262cSandi        } else {
229f3f0262cSandi            //invalid credentials - log off
230f8b1e4e7SAndreas Gohr            if(!$silent) {
231f8b1e4e7SAndreas Gohr                http_status(403, 'Login failed');
232f8b1e4e7SAndreas Gohr                msg($lang['badlogin'], -1);
233f8b1e4e7SAndreas Gohr            }
234f3f0262cSandi            auth_logoff();
235132bdbfeSandi            return false;
236f3f0262cSandi        }
237f3f0262cSandi    } else {
238132bdbfeSandi        // read cookie information
239645c0a36SAndreas Gohr        list($user, $sticky, $pass) = auth_getCookie();
240132bdbfeSandi        if($user && $pass) {
241132bdbfeSandi            // we got a cookie - see if we can trust it
242fa7c70ffSAdrian Lang
243fa7c70ffSAdrian Lang            // get session info
2440058ae75SDamien Regad            if (isset($_SESSION[DOKU_COOKIE])) {
245fa7c70ffSAdrian Lang                $session = $_SESSION[DOKU_COOKIE]['auth'];
246132bdbfeSandi                if (isset($session) &&
2477172dbc0SAndreas Gohr                    $auth->useSessionCache($user) &&
2484c989037SChris Smith                    ($session['time'] >= time() - $conf['auth_security_timeout']) &&
249132bdbfeSandi                    ($session['user'] == $user) &&
250234ce57eSAndreas Gohr                    ($session['pass'] == sha1($pass)) && //still crypted
251ab5d26daSAndreas Gohr                    ($session['buid'] == auth_browseruid())
252ab5d26daSAndreas Gohr                ) {
253234ce57eSAndreas Gohr
254132bdbfeSandi                    // he has session, cookie and browser right - let him in
255585bf44eSChristopher Smith                    $INPUT->server->set('REMOTE_USER', $user);
256132bdbfeSandi                    $USERINFO = $session['info']; //FIXME move all references to session
257132bdbfeSandi                    return true;
258132bdbfeSandi                }
2590058ae75SDamien Regad            }
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/**
272136ce040Sandi * Builds a pseudo UID from browser and IP data
273132bdbfeSandi *
274132bdbfeSandi * This is neither unique nor unfakable - still it adds some
275136ce040Sandi * security. Using the first part of the IP makes sure
27680b4f376SAndreas Gohr * proxy farms like AOLs are still okay.
27715fae107Sandi *
27815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
27915fae107Sandi *
280b13c0e1aSAdaKaleh * @return  string  a SHA256 sum of various browser headers
281132bdbfeSandi */
282132bdbfeSandifunction auth_browseruid() {
283585bf44eSChristopher Smith    /* @var Input $INPUT */
284585bf44eSChristopher Smith    global $INPUT;
285585bf44eSChristopher Smith
2862f9daf16SAndreas Gohr    $ip = clientIP(true);
287b13c0e1aSAdaKaleh    // convert IP string to packed binary representation
288b13c0e1aSAdaKaleh    $pip = inet_pton($ip);
289b7c67f83SAndreas Gohr
290b7c67f83SAndreas Gohr    $uid = implode("\n", [
291b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_USER_AGENT'),
292b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_ACCEPT_LANGUAGE'),
293b7c67f83SAndreas Gohr        substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6)
294b7c67f83SAndreas Gohr    ]);
295b13c0e1aSAdaKaleh    return hash('sha256', $uid);
296132bdbfeSandi}
297132bdbfeSandi
298132bdbfeSandi/**
299132bdbfeSandi * Creates a random key to encrypt the password in cookies
30015fae107Sandi *
30115fae107Sandi * This function tries to read the password for encrypting
30298407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
30315fae107Sandi * if no such file is found a random key is created and
30415fae107Sandi * and stored in this file.
30515fae107Sandi *
30615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
30742ea7f44SGerrit Uitslag *
30832ed2b36SAndreas Gohr * @param   bool $addsession if true, the sessionid is added to the salt
30930d544a4SMichael Hamann * @param   bool $secure     if security is more important than keeping the old value
31015fae107Sandi * @return  string
311132bdbfeSandi */
31230d544a4SMichael Hamannfunction auth_cookiesalt($addsession = false, $secure = false) {
313a1fe3c9cSMichael Große    if (defined('SIMPLE_TEST')) {
314fe745becSMichael Große        return 'test';
315a1fe3c9cSMichael Große    }
316132bdbfeSandi    global $conf;
31798407a7aSandi    $file = $conf['metadir'].'/_htcookiesalt';
31830d544a4SMichael Hamann    if ($secure || !file_exists($file)) {
31930d544a4SMichael Hamann        $file = $conf['metadir'].'/_htcookiesalt2';
32030d544a4SMichael Hamann    }
321132bdbfeSandi    $salt = io_readFile($file);
322132bdbfeSandi    if(empty($salt)) {
32330d544a4SMichael Hamann        $salt = bin2hex(auth_randombytes(64));
324132bdbfeSandi        io_saveFile($file, $salt);
325132bdbfeSandi    }
32632ed2b36SAndreas Gohr    if($addsession) {
32732ed2b36SAndreas Gohr        $salt .= session_id();
32832ed2b36SAndreas Gohr    }
329132bdbfeSandi    return $salt;
330f3f0262cSandi}
331f3f0262cSandi
332f3f0262cSandi/**
3337a33d2f8SNiklas Keller * Return cryptographically secure random bytes.
334483b6238SMichael Hamann *
3357a33d2f8SNiklas Keller * @author Niklas Keller <me@kelunik.com>
33642ea7f44SGerrit Uitslag *
3377a33d2f8SNiklas Keller * @param int $length number of bytes
3387a33d2f8SNiklas Keller * @return string cryptographically secure random bytes
339483b6238SMichael Hamann */
340483b6238SMichael Hamannfunction auth_randombytes($length) {
3417a33d2f8SNiklas Keller    return random_bytes($length);
342483b6238SMichael Hamann}
343483b6238SMichael Hamann
344483b6238SMichael Hamann/**
3457a33d2f8SNiklas Keller * Cryptographically secure random number generator.
346483b6238SMichael Hamann *
3477a33d2f8SNiklas Keller * @author Niklas Keller <me@kelunik.com>
34842ea7f44SGerrit Uitslag *
349483b6238SMichael Hamann * @param int $min
350483b6238SMichael Hamann * @param int $max
351483b6238SMichael Hamann * @return int
352483b6238SMichael Hamann */
353483b6238SMichael Hamannfunction auth_random($min, $max) {
3547a33d2f8SNiklas Keller    return random_int($min, $max);
355483b6238SMichael Hamann}
356483b6238SMichael Hamann
357483b6238SMichael Hamann/**
35804369c3eSMichael Hamann * Encrypt data using the given secret using AES
35904369c3eSMichael Hamann *
36004369c3eSMichael Hamann * The mode is CBC with a random initialization vector, the key is derived
36104369c3eSMichael Hamann * using pbkdf2.
36204369c3eSMichael Hamann *
36304369c3eSMichael Hamann * @param string $data   The data that shall be encrypted
36404369c3eSMichael Hamann * @param string $secret The secret/password that shall be used
36504369c3eSMichael Hamann * @return string The ciphertext
36604369c3eSMichael Hamann */
36704369c3eSMichael Hamannfunction auth_encrypt($data, $secret) {
36804369c3eSMichael Hamann    $iv     = auth_randombytes(16);
3691af2f135SAndreas Gohr    $cipher = new \phpseclib\Crypt\AES();
37004369c3eSMichael Hamann    $cipher->setPassword($secret);
37104369c3eSMichael Hamann
3727b650cefSMichael Hamann    /*
3737b650cefSMichael Hamann    this uses the encrypted IV as IV as suggested in
3747b650cefSMichael Hamann    http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
3757b650cefSMichael Hamann    for unique but necessarily random IVs. The resulting ciphertext is
3767b650cefSMichael Hamann    compatible to ciphertext that was created using a "normal" IV.
3777b650cefSMichael Hamann    */
37804369c3eSMichael Hamann    return $cipher->encrypt($iv.$data);
37904369c3eSMichael Hamann}
38004369c3eSMichael Hamann
38104369c3eSMichael Hamann/**
38204369c3eSMichael Hamann * Decrypt the given AES ciphertext
38304369c3eSMichael Hamann *
38404369c3eSMichael Hamann * The mode is CBC, the key is derived using pbkdf2
38504369c3eSMichael Hamann *
38604369c3eSMichael Hamann * @param string $ciphertext The encrypted data
38704369c3eSMichael Hamann * @param string $secret     The secret/password that shall be used
38804369c3eSMichael Hamann * @return string The decrypted data
38904369c3eSMichael Hamann */
39004369c3eSMichael Hamannfunction auth_decrypt($ciphertext, $secret) {
3917b650cefSMichael Hamann    $iv     = substr($ciphertext, 0, 16);
3921af2f135SAndreas Gohr    $cipher = new \phpseclib\Crypt\AES();
39304369c3eSMichael Hamann    $cipher->setPassword($secret);
3947b650cefSMichael Hamann    $cipher->setIV($iv);
39504369c3eSMichael Hamann
3967b650cefSMichael Hamann    return $cipher->decrypt(substr($ciphertext, 16));
39704369c3eSMichael Hamann}
39804369c3eSMichael Hamann
39904369c3eSMichael Hamann/**
400883179a4SAndreas Gohr * Log out the current user
401883179a4SAndreas Gohr *
402f3f0262cSandi * This clears all authentication data and thus log the user
403883179a4SAndreas Gohr * off. It also clears session data.
40415fae107Sandi *
40515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
40642ea7f44SGerrit Uitslag *
407883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
408f3f0262cSandi */
409883179a4SAndreas Gohrfunction auth_logoff($keepbc = false) {
410f3f0262cSandi    global $conf;
411f3f0262cSandi    global $USERINFO;
412e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
4135298a619SAndreas Gohr    global $auth;
414585bf44eSChristopher Smith    /* @var Input $INPUT */
415585bf44eSChristopher Smith    global $INPUT;
41637065e65Sandi
417d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
418e9621d07SAndreas Gohr    @session_start();
419e9621d07SAndreas Gohr
420e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
421e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
422e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
423e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
424e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
425e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
426883179a4SAndreas Gohr    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
427e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
428585bf44eSChristopher Smith    $INPUT->server->remove('REMOTE_USER');
429132bdbfeSandi    $USERINFO = null; //FIXME
430f5c6743cSAndreas Gohr
43173ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
432bf8392ebSAndreas Gohr    setcookie(DOKU_COOKIE, '', [
433bf8392ebSAndreas Gohr        'expires' => time() - 600000,
434bf8392ebSAndreas Gohr        'path' => $cookieDir,
435bf8392ebSAndreas Gohr        'secure' => ($conf['securecookie'] && is_ssl()),
436bf8392ebSAndreas Gohr        'httponly' => true,
437*486f82fcSAndreas Gohr        'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
438bf8392ebSAndreas Gohr    ]);
4395298a619SAndreas Gohr
440880f62faSAndreas Gohr    if($auth) $auth->logOff();
441f3f0262cSandi}
442f3f0262cSandi
443f3f0262cSandi/**
444f8cc712eSAndreas Gohr * Check if a user is a manager
445f8cc712eSAndreas Gohr *
446f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
447f8cc712eSAndreas Gohr * user.
448f8cc712eSAndreas Gohr *
449f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
450f8cc712eSAndreas Gohr *
451ab5d26daSAndreas Gohr * @param string $user Username
452ab5d26daSAndreas Gohr * @param array $groups List of groups the user is in
453ab5d26daSAndreas Gohr * @param bool $adminonly when true checks if user is admin
45410396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
455ab5d26daSAndreas Gohr * @return bool
45696348f27SAndreas Gohr * @see    auth_isadmin
45796348f27SAndreas Gohr *
45896348f27SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
459f8cc712eSAndreas Gohr */
46096348f27SAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false, $recache=false) {
461f8cc712eSAndreas Gohr    global $conf;
462f8cc712eSAndreas Gohr    global $USERINFO;
463e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
464d752aedeSAndreas Gohr    global $auth;
465585bf44eSChristopher Smith    /* @var Input $INPUT */
466585bf44eSChristopher Smith    global $INPUT;
467585bf44eSChristopher Smith
468f8cc712eSAndreas Gohr
469beca106aSAdrian Lang    if(!$auth) return false;
470c66972f2SAdrian Lang    if(is_null($user)) {
471585bf44eSChristopher Smith        if(!$INPUT->server->has('REMOTE_USER')) {
472c66972f2SAdrian Lang            return false;
473c66972f2SAdrian Lang        } else {
474585bf44eSChristopher Smith            $user = $INPUT->server->str('REMOTE_USER');
475c66972f2SAdrian Lang        }
476c66972f2SAdrian Lang    }
477d6dc956fSAndreas Gohr    if (is_null($groups)) {
4781525c228SAnna Dabrowska        // checking the logged in user, or another one?
4791525c228SAnna Dabrowska        if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) {
4801525c228SAnna Dabrowska            $groups =  (array) $USERINFO['grps'];
48166b108d6SAnna Dabrowska        } else {
4826cf7b139SAndreas Gohr            $groups = $auth->getUserData($user);
4836cf7b139SAndreas Gohr            $groups = $groups ? $groups['grps'] : [];
48466b108d6SAnna Dabrowska        }
485e259aa79SAndreas Gohr    }
486e259aa79SAndreas Gohr
48796348f27SAndreas Gohr    // prefer cached result
48896348f27SAndreas Gohr    static $cache = [];
48910396f77SAndreas Gohr    $cachekey = serialize([$user, $adminonly, $groups]);
49096348f27SAndreas Gohr    if (!isset($cache[$cachekey]) || $recache) {
491d6dc956fSAndreas Gohr        // check superuser match
49296348f27SAndreas Gohr        $ok = auth_isMember($conf['superuser'], $user, $groups);
49300ce12daSChris Smith
49496348f27SAndreas Gohr        // check managers
49596348f27SAndreas Gohr        if (!$ok && !$adminonly) {
49696348f27SAndreas Gohr            $ok = auth_isMember($conf['manager'], $user, $groups);
49796348f27SAndreas Gohr        }
49896348f27SAndreas Gohr
49996348f27SAndreas Gohr        $cache[$cachekey] = $ok;
50096348f27SAndreas Gohr    }
50196348f27SAndreas Gohr
50296348f27SAndreas Gohr    return $cache[$cachekey];
503f8cc712eSAndreas Gohr}
504f8cc712eSAndreas Gohr
505f8cc712eSAndreas Gohr/**
506f8cc712eSAndreas Gohr * Check if a user is admin
507f8cc712eSAndreas Gohr *
508f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
509f8cc712eSAndreas Gohr *
510f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
511f8cc712eSAndreas Gohr *
51296348f27SAndreas Gohr * @param string $user Username
51396348f27SAndreas Gohr * @param array $groups List of groups the user is in
51410396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
51596348f27SAndreas Gohr * @return bool
516f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
517ab5d26daSAndreas Gohr * @see auth_ismanager()
51842ea7f44SGerrit Uitslag *
519f8cc712eSAndreas Gohr */
52096348f27SAndreas Gohrfunction auth_isadmin($user = null, $groups = null, $recache=false) {
52196348f27SAndreas Gohr    return auth_ismanager($user, $groups, true, $recache);
522f8cc712eSAndreas Gohr}
523f8cc712eSAndreas Gohr
524d6dc956fSAndreas Gohr/**
525d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
526d6dc956fSAndreas Gohr * users and groups to determine membership status
527d6dc956fSAndreas Gohr *
528d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
529d6dc956fSAndreas Gohr *
53042ea7f44SGerrit Uitslag * @param string $memberlist commaseparated list of allowed users and groups
53142ea7f44SGerrit Uitslag * @param string $user       user to match against
53242ea7f44SGerrit Uitslag * @param array  $groups     groups the user is member of
5335446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
534d6dc956fSAndreas Gohr */
535d6dc956fSAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups) {
536e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
537d6dc956fSAndreas Gohr    global $auth;
538d6dc956fSAndreas Gohr    if(!$auth) return false;
539d6dc956fSAndreas Gohr
540d6dc956fSAndreas Gohr    // clean user and groups
5414f56ecbfSAdrian Lang    if(!$auth->isCaseSensitive()) {
5428cbc5ee8SAndreas Gohr        $user   = \dokuwiki\Utf8\PhpString::strtolower($user);
543a7e2efd2SAndreas Gohr        $groups = array_map([\dokuwiki\Utf8\PhpString::class, 'strtolower'], $groups);
544d6dc956fSAndreas Gohr    }
545d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
546d6dc956fSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), $groups);
547d6dc956fSAndreas Gohr
548d6dc956fSAndreas Gohr    // extract the memberlist
549d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
550d6dc956fSAndreas Gohr    $members = array_map('trim', $members);
551d6dc956fSAndreas Gohr    $members = array_unique($members);
552d6dc956fSAndreas Gohr    $members = array_filter($members);
553d6dc956fSAndreas Gohr
554d6dc956fSAndreas Gohr    // compare cleaned values
555d6dc956fSAndreas Gohr    foreach($members as $member) {
556e5204a12SJurgen Hart        if($member == '@ALL' ) return true;
5578cbc5ee8SAndreas Gohr        if(!$auth->isCaseSensitive()) $member = \dokuwiki\Utf8\PhpString::strtolower($member);
558d6dc956fSAndreas Gohr        if($member[0] == '@') {
559d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
560d6dc956fSAndreas Gohr            if(in_array($member, $groups)) return true;
561d6dc956fSAndreas Gohr        } else {
562d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
563d6dc956fSAndreas Gohr            if($member == $user) return true;
564d6dc956fSAndreas Gohr        }
565d6dc956fSAndreas Gohr    }
566d6dc956fSAndreas Gohr
567d6dc956fSAndreas Gohr    // still here? not a member!
568d6dc956fSAndreas Gohr    return false;
569d6dc956fSAndreas Gohr}
570d6dc956fSAndreas Gohr
571f8cc712eSAndreas Gohr/**
57215fae107Sandi * Convinience function for auth_aclcheck()
57315fae107Sandi *
57415fae107Sandi * This checks the permissions for the current user
57515fae107Sandi *
57615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
57715fae107Sandi *
5781698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
57915fae107Sandi * @return int          permission level
580f3f0262cSandi */
581f3f0262cSandifunction auth_quickaclcheck($id) {
582f3f0262cSandi    global $conf;
583f3f0262cSandi    global $USERINFO;
584585bf44eSChristopher Smith    /* @var Input $INPUT */
585585bf44eSChristopher Smith    global $INPUT;
586f3f0262cSandi    # if no ACL is used always return upload rights
587f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
5883e9ae63dSPhy    return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : array());
589f3f0262cSandi}
590f3f0262cSandi
591f3f0262cSandi/**
592c17acc9fSAndreas Gohr * Returns the maximum rights a user has for the given ID or its namespace
59315fae107Sandi *
59415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
59542ea7f44SGerrit Uitslag *
596c17acc9fSAndreas Gohr * @triggers AUTH_ACL_CHECK
5971698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
59815fae107Sandi * @param  string       $user   Username
5993272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
60015fae107Sandi * @return int             permission level
601f3f0262cSandi */
602f3f0262cSandifunction auth_aclcheck($id, $user, $groups) {
603c17acc9fSAndreas Gohr    $data = array(
604bf8f8509SAndreas Gohr        'id'     => $id ?? '',
605c17acc9fSAndreas Gohr        'user'   => $user,
606c17acc9fSAndreas Gohr        'groups' => $groups
607c17acc9fSAndreas Gohr    );
608c17acc9fSAndreas Gohr
609cbb44eabSAndreas Gohr    return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
610c17acc9fSAndreas Gohr}
611c17acc9fSAndreas Gohr
612c17acc9fSAndreas Gohr/**
613c17acc9fSAndreas Gohr * default ACL check method
614c17acc9fSAndreas Gohr *
615c17acc9fSAndreas Gohr * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
616c17acc9fSAndreas Gohr *
617c17acc9fSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
61842ea7f44SGerrit Uitslag *
619c17acc9fSAndreas Gohr * @param  array $data event data
620c17acc9fSAndreas Gohr * @return int   permission level
621c17acc9fSAndreas Gohr */
622c17acc9fSAndreas Gohrfunction auth_aclcheck_cb($data) {
623c17acc9fSAndreas Gohr    $id     =& $data['id'];
624c17acc9fSAndreas Gohr    $user   =& $data['user'];
625c17acc9fSAndreas Gohr    $groups =& $data['groups'];
626c17acc9fSAndreas Gohr
627f3f0262cSandi    global $conf;
628f3f0262cSandi    global $AUTH_ACL;
629e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
630d752aedeSAndreas Gohr    global $auth;
631f3f0262cSandi
63285d03f68SAndreas Gohr    // if no ACL is used always return upload rights
633f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
634beca106aSAdrian Lang    if(!$auth) return AUTH_NONE;
635bf8f8509SAndreas Gohr    if(!is_array($AUTH_ACL)) return AUTH_NONE;
636f3f0262cSandi
637074cf26bSandi    //make sure groups is an array
638074cf26bSandi    if(!is_array($groups)) $groups = array();
639074cf26bSandi
64085d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
641ab5d26daSAndreas Gohr    if(auth_isadmin($user, $groups)) {
642ab5d26daSAndreas Gohr        return AUTH_ADMIN;
643ab5d26daSAndreas Gohr    }
64485d03f68SAndreas Gohr
645eb3ce0d5SKazutaka Miyasaka    if(!$auth->isCaseSensitive()) {
6468cbc5ee8SAndreas Gohr        $user   = \dokuwiki\Utf8\PhpString::strtolower($user);
647c7dab4e8SAndreas Gohr        $groups = array_map([\dokuwiki\Utf8\PhpString::class, 'strtolower'], $groups);
648eb3ce0d5SKazutaka Miyasaka    }
64937ff2261SSascha Klopp    $user   = auth_nameencode($auth->cleanUser($user));
650d752aedeSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
65185d03f68SAndreas Gohr
6526c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
65337ff2261SSascha Klopp    foreach($groups as &$group) {
65437ff2261SSascha Klopp        $group = '@'.auth_nameencode($group);
65510a76f6fSfrank    }
65610a76f6fSfrank
657f3f0262cSandi    $ns   = getNS($id);
658f3f0262cSandi    $perm = -1;
659f3f0262cSandi
660f3f0262cSandi    //add ALL group
661f3f0262cSandi    $groups[] = '@ALL';
66237ff2261SSascha Klopp
663f3f0262cSandi    //add User
66434aeb4afSAndreas Gohr    if($user) $groups[] = $user;
665f3f0262cSandi
666f3f0262cSandi    //check exact match first
66721c3090aSChristopher Smith    $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
668f3f0262cSandi    if(count($matches)) {
669f3f0262cSandi        foreach($matches as $match) {
670f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
67121c3090aSChristopher Smith            $acl   = preg_split('/[ \t]+/', $match);
672eb3ce0d5SKazutaka Miyasaka            if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
6738cbc5ee8SAndreas Gohr                $acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]);
674eb3ce0d5SKazutaka Miyasaka            }
67548d7b7a6SDominik Eckelmann            if(!in_array($acl[1], $groups)) {
67648d7b7a6SDominik Eckelmann                continue;
67748d7b7a6SDominik Eckelmann            }
6788ef6b7caSandi            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
679f3f0262cSandi            if($acl[2] > $perm) {
680f3f0262cSandi                $perm = $acl[2];
681f3f0262cSandi            }
682f3f0262cSandi        }
683f3f0262cSandi        if($perm > -1) {
684f3f0262cSandi            //we had a match - return it
685def492a2SGuillaume Turri            return (int) $perm;
686f3f0262cSandi        }
687f3f0262cSandi    }
688f3f0262cSandi
689f3f0262cSandi    //still here? do the namespace checks
690f3f0262cSandi    if($ns) {
6913e304b55SMichael Hamann        $path = $ns.':*';
692f3f0262cSandi    } else {
6933e304b55SMichael Hamann        $path = '*'; //root document
694f3f0262cSandi    }
695f3f0262cSandi
696f3f0262cSandi    do {
69721c3090aSChristopher Smith        $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
698f3f0262cSandi        if(count($matches)) {
699f3f0262cSandi            foreach($matches as $match) {
700f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
70121c3090aSChristopher Smith                $acl   = preg_split('/[ \t]+/', $match);
702eb3ce0d5SKazutaka Miyasaka                if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
7038cbc5ee8SAndreas Gohr                    $acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]);
704eb3ce0d5SKazutaka Miyasaka                }
70548d7b7a6SDominik Eckelmann                if(!in_array($acl[1], $groups)) {
70648d7b7a6SDominik Eckelmann                    continue;
70748d7b7a6SDominik Eckelmann                }
7088ef6b7caSandi                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
709f3f0262cSandi                if($acl[2] > $perm) {
710f3f0262cSandi                    $perm = $acl[2];
711f3f0262cSandi                }
712f3f0262cSandi            }
713f3f0262cSandi            //we had a match - return it
71448d7b7a6SDominik Eckelmann            if($perm != -1) {
715def492a2SGuillaume Turri                return (int) $perm;
716f3f0262cSandi            }
71748d7b7a6SDominik Eckelmann        }
718f3f0262cSandi        //get next higher namespace
719f3f0262cSandi        $ns = getNS($ns);
720f3f0262cSandi
7213e304b55SMichael Hamann        if($path != '*') {
7223e304b55SMichael Hamann            $path = $ns.':*';
7233e304b55SMichael Hamann            if($path == ':*') $path = '*';
724f3f0262cSandi        } else {
725f3f0262cSandi            //we did this already
726f3f0262cSandi            //looks like there is something wrong with the ACL
727f3f0262cSandi            //break here
728d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
729d5ce66f6SAndreas Gohr            return AUTH_NONE;
730f3f0262cSandi        }
731f3f0262cSandi    } while(1); //this should never loop endless
732ab5d26daSAndreas Gohr    return AUTH_NONE;
733f3f0262cSandi}
734f3f0262cSandi
735f3f0262cSandi/**
7366c2bb100SAndreas Gohr * Encode ASCII special chars
7376c2bb100SAndreas Gohr *
7386c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
7396c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
7406c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
7416c2bb100SAndreas Gohr * urlencoding!).
7426c2bb100SAndreas Gohr *
7436c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
7446c2bb100SAndreas Gohr *
7456c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
7466c2bb100SAndreas Gohr * @see rawurldecode()
74742ea7f44SGerrit Uitslag *
74842ea7f44SGerrit Uitslag * @param string $name
74942ea7f44SGerrit Uitslag * @param bool $skip_group
75042ea7f44SGerrit Uitslag * @return string
7516c2bb100SAndreas Gohr */
752e838fc2eSAndreas Gohrfunction auth_nameencode($name, $skip_group = false) {
753a424cd8eSchris    global $cache_authname;
754a424cd8eSchris    $cache =& $cache_authname;
75531784267SAndreas Gohr    $name  = (string) $name;
756a424cd8eSchris
75780601d26SAndreas Gohr    // never encode wildcard FS#1955
75880601d26SAndreas Gohr    if($name == '%USER%') return $name;
759b78bf706Sromain    if($name == '%GROUP%') return $name;
76080601d26SAndreas Gohr
761a424cd8eSchris    if(!isset($cache[$name][$skip_group])) {
7622401f18dSSyntaxseed        if($skip_group && $name[0] == '@') {
76330f6faf0SChristopher Smith            $cache[$name][$skip_group] = '@'.preg_replace_callback(
76430f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
76530f6faf0SChristopher Smith                'auth_nameencode_callback', substr($name, 1)
766ab5d26daSAndreas Gohr            );
767e838fc2eSAndreas Gohr        } else {
76830f6faf0SChristopher Smith            $cache[$name][$skip_group] = preg_replace_callback(
76930f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
77030f6faf0SChristopher Smith                'auth_nameencode_callback', $name
771ab5d26daSAndreas Gohr            );
772e838fc2eSAndreas Gohr        }
7736c2bb100SAndreas Gohr    }
7746c2bb100SAndreas Gohr
775a424cd8eSchris    return $cache[$name][$skip_group];
776a424cd8eSchris}
777a424cd8eSchris
77804d68ae4SGerrit Uitslag/**
77904d68ae4SGerrit Uitslag * callback encodes the matches
78004d68ae4SGerrit Uitslag *
78104d68ae4SGerrit Uitslag * @param array $matches first complete match, next matching subpatterms
78204d68ae4SGerrit Uitslag * @return string
78304d68ae4SGerrit Uitslag */
78430f6faf0SChristopher Smithfunction auth_nameencode_callback($matches) {
78530f6faf0SChristopher Smith    return '%'.dechex(ord(substr($matches[1],-1)));
78630f6faf0SChristopher Smith}
78730f6faf0SChristopher Smith
7886c2bb100SAndreas Gohr/**
789f3f0262cSandi * Create a pronouncable password
790f3f0262cSandi *
7918a285f7fSAndreas Gohr * The $foruser variable might be used by plugins to run additional password
7928a285f7fSAndreas Gohr * policy checks, but is not used by the default implementation
7938a285f7fSAndreas Gohr *
79415fae107Sandi * @author   Andreas Gohr <andi@splitbrain.org>
79515fae107Sandi * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
7968a285f7fSAndreas Gohr * @triggers AUTH_PASSWORD_GENERATE
79715fae107Sandi *
7988a285f7fSAndreas Gohr * @param  string $foruser username for which the password is generated
79915fae107Sandi * @return string  pronouncable password
800f3f0262cSandi */
8018a285f7fSAndreas Gohrfunction auth_pwgen($foruser = '') {
8028a285f7fSAndreas Gohr    $data = array(
803d628dcf3SAndreas Gohr        'password' => '',
804d628dcf3SAndreas Gohr        'foruser'  => $foruser
8058a285f7fSAndreas Gohr    );
8068a285f7fSAndreas Gohr
807e1d9dcc8SAndreas Gohr    $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
8088a285f7fSAndreas Gohr    if($evt->advise_before(true)) {
809f3f0262cSandi        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
810f3f0262cSandi        $v = 'aeiou'; //vowels
811f3f0262cSandi        $a = $c.$v; //both
812987c8d26SAndreas Gohr        $s = '!$%&?+*~#-_:.;,'; // specials
813f3f0262cSandi
814987c8d26SAndreas Gohr        //use thre syllables...
815987c8d26SAndreas Gohr        for($i = 0; $i < 3; $i++) {
816483b6238SMichael Hamann            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
817483b6238SMichael Hamann            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
818483b6238SMichael Hamann            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
819f3f0262cSandi        }
820987c8d26SAndreas Gohr        //... and add a nice number and special
82143f71e05Ssdavis80        $data['password'] .= $s[auth_random(0, strlen($s) - 1)].auth_random(10, 99);
8228a285f7fSAndreas Gohr    }
8238a285f7fSAndreas Gohr    $evt->advise_after();
824f3f0262cSandi
8258a285f7fSAndreas Gohr    return $data['password'];
826f3f0262cSandi}
827f3f0262cSandi
828f3f0262cSandi/**
829f3f0262cSandi * Sends a password to the given user
830f3f0262cSandi *
83115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
83242ea7f44SGerrit Uitslag *
833ab5d26daSAndreas Gohr * @param string $user Login name of the user
834ab5d26daSAndreas Gohr * @param string $password The new password in clear text
83515fae107Sandi * @return bool  true on success
836f3f0262cSandi */
837f3f0262cSandifunction auth_sendPassword($user, $password) {
838f3f0262cSandi    global $lang;
839e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
840cd52f92dSchris    global $auth;
841beca106aSAdrian Lang    if(!$auth) return false;
842cd52f92dSchris
843d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
8442dc9e900SChristopher Smith    $userinfo = $auth->getUserData($user, $requireGroups = false);
845f3f0262cSandi
84687ddda95Sandi    if(!$userinfo['mail']) return false;
847f3f0262cSandi
848f3f0262cSandi    $text = rawLocale('password');
849d7169d19SAndreas Gohr    $trep = array(
850d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
851d7169d19SAndreas Gohr        'LOGIN'    => $user,
852d7169d19SAndreas Gohr        'PASSWORD' => $password
853d7169d19SAndreas Gohr    );
854f3f0262cSandi
855d7169d19SAndreas Gohr    $mail = new Mailer();
856102cdbd7SLarsGit223    $mail->to($mail->getCleanName($userinfo['name']).' <'.$userinfo['mail'].'>');
857d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
858d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
859d7169d19SAndreas Gohr    return $mail->send();
860f3f0262cSandi}
861f3f0262cSandi
862f3f0262cSandi/**
86315fae107Sandi * Register a new user
864f3f0262cSandi *
86515fae107Sandi * This registers a new user - Data is read directly from $_POST
86615fae107Sandi *
86715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
86842ea7f44SGerrit Uitslag *
86915fae107Sandi * @return bool  true on success, false on any error
870f3f0262cSandi */
871f3f0262cSandifunction register() {
872f3f0262cSandi    global $lang;
873eb5d07e4Sjan    global $conf;
874e1d9dcc8SAndreas Gohr    /* @var \dokuwiki\Extension\AuthPlugin $auth */
875cd52f92dSchris    global $auth;
87664273335SAndreas Gohr    global $INPUT;
877f3f0262cSandi
87864273335SAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
8793a48618aSAnika Henke    if(!actionOK('register')) return false;
880640145a5Sandi
88164273335SAndreas Gohr    // gather input
88264273335SAndreas Gohr    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
88364273335SAndreas Gohr    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
88464273335SAndreas Gohr    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
88564273335SAndreas Gohr    $pass     = $INPUT->post->str('pass');
88664273335SAndreas Gohr    $passchk  = $INPUT->post->str('passchk');
887d752aedeSAndreas Gohr
88864273335SAndreas Gohr    if(empty($login) || empty($fullname) || empty($email)) {
889f3f0262cSandi        msg($lang['regmissing'], -1);
890f3f0262cSandi        return false;
891f3f0262cSandi    }
892f3f0262cSandi
893cab2716aSmatthias.grimm    if($conf['autopasswd']) {
8948a285f7fSAndreas Gohr        $pass = auth_pwgen($login); // automatically generate password
89564273335SAndreas Gohr    } elseif(empty($pass) || empty($passchk)) {
896bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
897cab2716aSmatthias.grimm        return false;
89864273335SAndreas Gohr    } elseif($pass != $passchk) {
899bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
900cab2716aSmatthias.grimm        return false;
901cab2716aSmatthias.grimm    }
902cab2716aSmatthias.grimm
903f3f0262cSandi    //check mail
90464273335SAndreas Gohr    if(!mail_isvalid($email)) {
905f3f0262cSandi        msg($lang['regbadmail'], -1);
906f3f0262cSandi        return false;
907f3f0262cSandi    }
908f3f0262cSandi
909f3f0262cSandi    //okay try to create the user
91064273335SAndreas Gohr    if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) {
911db9faf02SPatrick Brown        msg($lang['regfail'], -1);
912f3f0262cSandi        return false;
913f3f0262cSandi    }
914f3f0262cSandi
915790b7720SAndreas Gohr    // send notification about the new user
91675d66495SMichael Große    $subscription = new RegistrationSubscriptionSender();
91775d66495SMichael Große    $subscription->sendRegister($login, $fullname, $email);
91802a498e7Schris
919790b7720SAndreas Gohr    // are we done?
920cab2716aSmatthias.grimm    if(!$conf['autopasswd']) {
921cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
922cab2716aSmatthias.grimm        return true;
923cab2716aSmatthias.grimm    }
924cab2716aSmatthias.grimm
925790b7720SAndreas Gohr    // autogenerated password? then send password to user
92664273335SAndreas Gohr    if(auth_sendPassword($login, $pass)) {
927f3f0262cSandi        msg($lang['regsuccess'], 1);
928f3f0262cSandi        return true;
929f3f0262cSandi    } else {
930f3f0262cSandi        msg($lang['regmailfail'], -1);
931f3f0262cSandi        return false;
932f3f0262cSandi    }
933f3f0262cSandi}
934f3f0262cSandi
93510a76f6fSfrank/**
9368b06d178Schris * Update user profile
9378b06d178Schris *
9388b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
9398b06d178Schris */
9408b06d178Schrisfunction updateprofile() {
9418b06d178Schris    global $conf;
9428b06d178Schris    global $lang;
943e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
944cd52f92dSchris    global $auth;
945bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
946bcc94b2cSAndreas Gohr    global $INPUT;
9478b06d178Schris
948bcc94b2cSAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
9491b2a85e8SAndreas Gohr    if(!checkSecurityToken()) return false;
9508b06d178Schris
9513a48618aSAnika Henke    if(!actionOK('profile')) {
9528b06d178Schris        msg($lang['profna'], -1);
9538b06d178Schris        return false;
9548b06d178Schris    }
9558b06d178Schris
956bcc94b2cSAndreas Gohr    $changes         = array();
957bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
958bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
959bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
960bcc94b2cSAndreas Gohr
961bcc94b2cSAndreas Gohr    // check misspelled passwords
962bcc94b2cSAndreas Gohr    if($changes['pass'] != $INPUT->post->str('passchk')) {
963bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
9648b06d178Schris        return false;
9658b06d178Schris    }
9668b06d178Schris
9678b06d178Schris    // clean fullname and email
968bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
969bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
9708b06d178Schris
971bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
972bcc94b2cSAndreas Gohr    if((empty($changes['name']) && $auth->canDo('modName')) ||
973bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
974ab5d26daSAndreas Gohr    ) {
9758b06d178Schris        msg($lang['profnoempty'], -1);
9768b06d178Schris        return false;
9778b06d178Schris    }
978bcc94b2cSAndreas Gohr    if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
9798b06d178Schris        msg($lang['regbadmail'], -1);
9808b06d178Schris        return false;
9818b06d178Schris    }
9828b06d178Schris
983bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
9844c21b7eeSAndreas Gohr
985bcc94b2cSAndreas Gohr    // check for unavailable capabilities
986bcc94b2cSAndreas Gohr    if(!$auth->canDo('modName')) unset($changes['name']);
987bcc94b2cSAndreas Gohr    if(!$auth->canDo('modMail')) unset($changes['mail']);
988bcc94b2cSAndreas Gohr    if(!$auth->canDo('modPass')) unset($changes['pass']);
989bcc94b2cSAndreas Gohr
990bcc94b2cSAndreas Gohr    // anything to do?
9918b06d178Schris    if(!count($changes)) {
9928b06d178Schris        msg($lang['profnochange'], -1);
9938b06d178Schris        return false;
9948b06d178Schris    }
9958b06d178Schris
9968b06d178Schris    if($conf['profileconfirm']) {
997585bf44eSChristopher Smith        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
99871422fc8SChristopher Smith            msg($lang['badpassconfirm'], -1);
9998b06d178Schris            return false;
10008b06d178Schris        }
10018b06d178Schris    }
10028b06d178Schris
1003e6c4392fSPatrick Brown    if(!$auth->triggerUserMod('modify', array($INPUT->server->str('REMOTE_USER'), &$changes))) {
1004db9faf02SPatrick Brown        msg($lang['proffail'], -1);
1005db9faf02SPatrick Brown        return false;
1006db9faf02SPatrick Brown    }
1007db9faf02SPatrick Brown
100832ed2b36SAndreas Gohr    if($changes['pass']) {
1009c276e9e8SMarcel Pennewiss        // update cookie and session with the changed data
1010ab5d26daSAndreas Gohr        list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
101104369c3eSMichael Hamann        $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1012585bf44eSChristopher Smith        auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
1013c276e9e8SMarcel Pennewiss    } else {
1014c276e9e8SMarcel Pennewiss        // make sure the session is writable
1015c276e9e8SMarcel Pennewiss        @session_start();
1016c276e9e8SMarcel Pennewiss        // invalidate session cache
1017c276e9e8SMarcel Pennewiss        $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
1018c276e9e8SMarcel Pennewiss        session_write_close();
101932ed2b36SAndreas Gohr    }
1020c276e9e8SMarcel Pennewiss
102125b2a98cSMichael Klier    return true;
1022a0b5b007SChris Smith}
1023ab5d26daSAndreas Gohr
102404d68ae4SGerrit Uitslag/**
102504d68ae4SGerrit Uitslag * Delete the current logged-in user
102604d68ae4SGerrit Uitslag *
102704d68ae4SGerrit Uitslag * @return bool true on success, false on any error
102804d68ae4SGerrit Uitslag */
10292a7abf2dSChristopher Smithfunction auth_deleteprofile(){
10302a7abf2dSChristopher Smith    global $conf;
10312a7abf2dSChristopher Smith    global $lang;
1032e1d9dcc8SAndreas Gohr    /* @var \dokuwiki\Extension\AuthPlugin $auth */
10332a7abf2dSChristopher Smith    global $auth;
10342a7abf2dSChristopher Smith    /* @var Input $INPUT */
10352a7abf2dSChristopher Smith    global $INPUT;
10362a7abf2dSChristopher Smith
10372a7abf2dSChristopher Smith    if(!$INPUT->post->bool('delete')) return false;
10382a7abf2dSChristopher Smith    if(!checkSecurityToken()) return false;
10392a7abf2dSChristopher Smith
10402a7abf2dSChristopher Smith    // action prevented or auth module disallows
10412a7abf2dSChristopher Smith    if(!actionOK('profile_delete') || !$auth->canDo('delUser')) {
10422a7abf2dSChristopher Smith        msg($lang['profnodelete'], -1);
10432a7abf2dSChristopher Smith        return false;
10442a7abf2dSChristopher Smith    }
10452a7abf2dSChristopher Smith
10462a7abf2dSChristopher Smith    if(!$INPUT->post->bool('confirm_delete')){
10472a7abf2dSChristopher Smith        msg($lang['profconfdeletemissing'], -1);
10482a7abf2dSChristopher Smith        return false;
10492a7abf2dSChristopher Smith    }
10502a7abf2dSChristopher Smith
10512a7abf2dSChristopher Smith    if($conf['profileconfirm']) {
1052585bf44eSChristopher Smith        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
10532a7abf2dSChristopher Smith            msg($lang['badpassconfirm'], -1);
10542a7abf2dSChristopher Smith            return false;
10552a7abf2dSChristopher Smith        }
10562a7abf2dSChristopher Smith    }
10572a7abf2dSChristopher Smith
105859bc3b48SGerrit Uitslag    $deleted = array();
1059585bf44eSChristopher Smith    $deleted[] = $INPUT->server->str('REMOTE_USER');
106073012efdSChristopher Smith    if($auth->triggerUserMod('delete', array($deleted))) {
10612a7abf2dSChristopher Smith        // force and immediate logout including removing the sticky cookie
10622a7abf2dSChristopher Smith        auth_logoff();
10632a7abf2dSChristopher Smith        return true;
10642a7abf2dSChristopher Smith    }
10652a7abf2dSChristopher Smith
10662a7abf2dSChristopher Smith    return false;
10672a7abf2dSChristopher Smith}
10682a7abf2dSChristopher Smith
10698b06d178Schris/**
10708b06d178Schris * Send a  new password
10718b06d178Schris *
10721d5856cfSAndreas Gohr * This function handles both phases of the password reset:
10731d5856cfSAndreas Gohr *
10741d5856cfSAndreas Gohr *   - handling the first request of password reset
10751d5856cfSAndreas Gohr *   - validating the password reset auth token
10761d5856cfSAndreas Gohr *
10778b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
10788b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
10791d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10808b06d178Schris *
10818b06d178Schris * @return bool true on success, false on any error
10828b06d178Schris */
10838b06d178Schrisfunction act_resendpwd() {
10848b06d178Schris    global $lang;
10858b06d178Schris    global $conf;
1086e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1087cd52f92dSchris    global $auth;
1088bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1089bcc94b2cSAndreas Gohr    global $INPUT;
10908b06d178Schris
10913a48618aSAnika Henke    if(!actionOK('resendpwd')) {
10928b06d178Schris        msg($lang['resendna'], -1);
10938b06d178Schris        return false;
10948b06d178Schris    }
10958b06d178Schris
1096bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
10978b06d178Schris
10981d5856cfSAndreas Gohr    if($token) {
1099cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
11001d5856cfSAndreas Gohr
11012401f18dSSyntaxseed        $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
110279e79377SAndreas Gohr        if(!file_exists($tfile)) {
11031d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1104bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
11051d5856cfSAndreas Gohr            return false;
11061d5856cfSAndreas Gohr        }
11078a9735e3SAndreas Gohr        // token is only valid for 3 days
11088a9735e3SAndreas Gohr        if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
11098a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1110bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
11111d5856cfSAndreas Gohr            @unlink($tfile);
11128a9735e3SAndreas Gohr            return false;
11138a9735e3SAndreas Gohr        }
11148a9735e3SAndreas Gohr
11158b06d178Schris        $user     = io_readfile($tfile);
11162dc9e900SChristopher Smith        $userinfo = $auth->getUserData($user, $requireGroups = false);
11178b06d178Schris        if(!$userinfo['mail']) {
11188b06d178Schris            msg($lang['resendpwdnouser'], -1);
11198b06d178Schris            return false;
11208b06d178Schris        }
11218b06d178Schris
1122cc204bbdSAndreas Gohr        if(!$conf['autopasswd']) { // we let the user choose a password
1123bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
1124bcc94b2cSAndreas Gohr
1125cc204bbdSAndreas Gohr            // password given correctly?
1126bcc94b2cSAndreas Gohr            if(!$pass) return false;
1127bcc94b2cSAndreas Gohr            if($pass != $INPUT->str('passchk')) {
1128451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
1129cc204bbdSAndreas Gohr                return false;
1130cc204bbdSAndreas Gohr            }
1131cc204bbdSAndreas Gohr
1132bcc94b2cSAndreas Gohr            // change it
1133cc204bbdSAndreas Gohr            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1134db9faf02SPatrick Brown                msg($lang['proffail'], -1);
1135cc204bbdSAndreas Gohr                return false;
1136cc204bbdSAndreas Gohr            }
1137cc204bbdSAndreas Gohr
1138cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
1139cc204bbdSAndreas Gohr
11408a285f7fSAndreas Gohr            $pass = auth_pwgen($user);
11417d3c8d42SGabriel Birke            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1142db9faf02SPatrick Brown                msg($lang['proffail'], -1);
11438b06d178Schris                return false;
11448b06d178Schris            }
11458b06d178Schris
11468b06d178Schris            if(auth_sendPassword($user, $pass)) {
11478b06d178Schris                msg($lang['resendpwdsuccess'], 1);
11488b06d178Schris            } else {
11498b06d178Schris                msg($lang['regmailfail'], -1);
11508b06d178Schris            }
1151cc204bbdSAndreas Gohr        }
1152cc204bbdSAndreas Gohr
1153cc204bbdSAndreas Gohr        @unlink($tfile);
11548b06d178Schris        return true;
11551d5856cfSAndreas Gohr
11561d5856cfSAndreas Gohr    } else {
11571d5856cfSAndreas Gohr        // we're in request phase
11581d5856cfSAndreas Gohr
1159bcc94b2cSAndreas Gohr        if(!$INPUT->post->bool('save')) return false;
11601d5856cfSAndreas Gohr
1161bcc94b2cSAndreas Gohr        if(!$INPUT->post->str('login')) {
11621d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
11631d5856cfSAndreas Gohr            return false;
11641d5856cfSAndreas Gohr        } else {
1165bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
11661d5856cfSAndreas Gohr        }
11671d5856cfSAndreas Gohr
11682dc9e900SChristopher Smith        $userinfo = $auth->getUserData($user, $requireGroups = false);
11691d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
11701d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
11711d5856cfSAndreas Gohr            return false;
11721d5856cfSAndreas Gohr        }
11731d5856cfSAndreas Gohr
11741d5856cfSAndreas Gohr        // generate auth token
1175483b6238SMichael Hamann        $token = md5(auth_randombytes(16)); // random secret
11762401f18dSSyntaxseed        $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
11771d5856cfSAndreas Gohr        $url   = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
11781d5856cfSAndreas Gohr
11791d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
11801d5856cfSAndreas Gohr
11811d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
1182d7169d19SAndreas Gohr        $trep = array(
1183d7169d19SAndreas Gohr            'FULLNAME' => $userinfo['name'],
1184d7169d19SAndreas Gohr            'LOGIN'    => $user,
1185d7169d19SAndreas Gohr            'CONFIRM'  => $url
1186d7169d19SAndreas Gohr        );
11871d5856cfSAndreas Gohr
1188d7169d19SAndreas Gohr        $mail = new Mailer();
1189d7169d19SAndreas Gohr        $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1190d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
1191d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
1192d7169d19SAndreas Gohr        if($mail->send()) {
11931d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
11941d5856cfSAndreas Gohr        } else {
11951d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
11961d5856cfSAndreas Gohr        }
11971d5856cfSAndreas Gohr        return true;
11981d5856cfSAndreas Gohr    }
1199ab5d26daSAndreas Gohr    // never reached
12008b06d178Schris}
12018b06d178Schris
12028b06d178Schris/**
1203b0855b11Sandi * Encrypts a password using the given method and salt
1204b0855b11Sandi *
1205b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1206b0855b11Sandi * is chosen.
1207b0855b11Sandi *
1208b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
120942ea7f44SGerrit Uitslag *
1210ab5d26daSAndreas Gohr * @param string $clear The clear text password
1211ab5d26daSAndreas Gohr * @param string $method The hashing method
1212ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1213b0855b11Sandi * @return  string  The crypted password
1214b0855b11Sandi */
1215577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null) {
1216b0855b11Sandi    global $conf;
1217b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
121810a76f6fSfrank
12193a0a2d05SAndreas Gohr    $pass = new PassHash();
12203a0a2d05SAndreas Gohr    $call = 'hash_'.$method;
1221b0855b11Sandi
12223a0a2d05SAndreas Gohr    if(!method_exists($pass, $call)) {
1223b0855b11Sandi        msg("Unsupported crypt method $method", -1);
12243a0a2d05SAndreas Gohr        return false;
1225b0855b11Sandi    }
12263a0a2d05SAndreas Gohr
12273a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1228b0855b11Sandi}
1229b0855b11Sandi
1230b0855b11Sandi/**
1231b0855b11Sandi * Verifies a cleartext password against a crypted hash
1232b0855b11Sandi *
1233b0855b11Sandi * @author Andreas Gohr <andi@splitbrain.org>
123442ea7f44SGerrit Uitslag *
1235ab5d26daSAndreas Gohr * @param  string $clear The clear text password
1236ab5d26daSAndreas Gohr * @param  string $crypt The hash to compare with
1237ab5d26daSAndreas Gohr * @return bool true if both match
1238b0855b11Sandi */
1239b0855b11Sandifunction auth_verifyPassword($clear, $crypt) {
12403a0a2d05SAndreas Gohr    $pass = new PassHash();
12413a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1242b0855b11Sandi}
1243340756e4Sandi
1244a0b5b007SChris Smith/**
1245a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1246a0b5b007SChris Smith *
1247a0b5b007SChris Smith * @param string  $user       username
1248a0b5b007SChris Smith * @param string  $pass       encrypted password
1249a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1250ab5d26daSAndreas Gohr * @return bool
1251a0b5b007SChris Smith */
1252a0b5b007SChris Smithfunction auth_setCookie($user, $pass, $sticky) {
1253a0b5b007SChris Smith    global $conf;
1254e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1255a0b5b007SChris Smith    global $auth;
125679d00841SOliver Geisen    global $USERINFO;
1257a0b5b007SChris Smith
1258beca106aSAdrian Lang    if(!$auth) return false;
1259a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1260a0b5b007SChris Smith
1261a0b5b007SChris Smith    // set cookie
1262645c0a36SAndreas Gohr    $cookie    = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
126373ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1264c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1265bf8392ebSAndreas Gohr    setcookie(DOKU_COOKIE, $cookie, [
1266bf8392ebSAndreas Gohr        'expires' => $time,
1267bf8392ebSAndreas Gohr        'path' => $cookieDir,
1268bf8392ebSAndreas Gohr        'secure' => ($conf['securecookie'] && is_ssl()),
1269bf8392ebSAndreas Gohr        'httponly' => true,
1270*486f82fcSAndreas Gohr        'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
1271bf8392ebSAndreas Gohr    ]);
127255a71a16SGerrit Uitslag
1273a0b5b007SChris Smith    // set session
1274a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1275234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1276a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1277a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1278a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1279ab5d26daSAndreas Gohr
1280ab5d26daSAndreas Gohr    return true;
1281a0b5b007SChris Smith}
1282a0b5b007SChris Smith
1283645c0a36SAndreas Gohr/**
1284645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1285645c0a36SAndreas Gohr *
1286645c0a36SAndreas Gohr * @returns array
1287645c0a36SAndreas Gohr */
1288645c0a36SAndreas Gohrfunction auth_getCookie() {
1289c66972f2SAdrian Lang    if(!isset($_COOKIE[DOKU_COOKIE])) {
1290c66972f2SAdrian Lang        return array(null, null, null);
1291c66972f2SAdrian Lang    }
1292ec34bb30SAndreas Gohr    list($user, $sticky, $pass) = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, '');
1293645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1294645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1295645c0a36SAndreas Gohr    $user   = base64_decode($user);
1296645c0a36SAndreas Gohr    return array($user, $sticky, $pass);
1297645c0a36SAndreas Gohr}
1298645c0a36SAndreas Gohr
1299e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1300