xref: /dokuwiki/inc/auth.php (revision ec34bb300b254ecd0dba0fac22d8115635141cc5)
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
69b2665af7SMichael Hamann    // handle renamed HTTP_AUTHORIZATION variable (can happen when a fix like
70b2665af7SMichael Hamann    // the one presented at
71b2665af7SMichael Hamann    // http://www.besthostratings.com/articles/http-auth-php-cgi.html is used
72b2665af7SMichael Hamann    // for enabling HTTP authentication with CGI/SuExec)
73b2665af7SMichael Hamann    if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
74b2665af7SMichael Hamann        $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
75528ddc7cSAndreas Gohr    // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
7606156f3cSAndreas Gohr    if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
77528ddc7cSAndreas Gohr        list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
78528ddc7cSAndreas Gohr            explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
79528ddc7cSAndreas Gohr    }
80528ddc7cSAndreas Gohr
811e8c9c90SAndreas Gohr    // if no credentials were given try to use HTTP auth (for SSO)
82bcc94b2cSAndreas Gohr    if(!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])) {
83bcc94b2cSAndreas Gohr        $INPUT->set('u', $_SERVER['PHP_AUTH_USER']);
84bcc94b2cSAndreas Gohr        $INPUT->set('p', $_SERVER['PHP_AUTH_PW']);
85bcc94b2cSAndreas Gohr        $INPUT->set('http_credentials', true);
861e8c9c90SAndreas Gohr    }
871e8c9c90SAndreas Gohr
88395c2f0fSAndreas Gohr    // apply cleaning (auth specific user names, remove control chars)
8993a7873eSAndreas Gohr    if (true === $auth->success) {
90395c2f0fSAndreas Gohr        $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
91395c2f0fSAndreas Gohr        $INPUT->set('p', stripctl($INPUT->str('p')));
92f4476bd9SJan Schumann    }
93191bb90aSAndreas Gohr
9481e99965SPhy    $ok = null;
958eca974cSAndreas Gohr    if (!is_null($auth) && $auth->canDo('external')) {
9681e99965SPhy        $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
9781e99965SPhy    }
9881e99965SPhy
9981e99965SPhy    if ($ok === null) {
10081e99965SPhy        // external trust mechanism not in place, or returns no result,
10181e99965SPhy        // then attempt auth_login
1026080c584SRobin Gareus        $evdata = array(
103bcc94b2cSAndreas Gohr            'user'     => $INPUT->str('u'),
104bcc94b2cSAndreas Gohr            'password' => $INPUT->str('p'),
105bcc94b2cSAndreas Gohr            'sticky'   => $INPUT->bool('r'),
106bcc94b2cSAndreas Gohr            'silent'   => $INPUT->bool('http_credentials')
1076080c584SRobin Gareus        );
108cbb44eabSAndreas Gohr        Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
109f5cb575dSAndreas Gohr    }
110f5cb575dSAndreas Gohr
11116905344SAndreas Gohr    //load ACL into a global array XXX
11275c93b77SAndreas Gohr    $AUTH_ACL = auth_loadACL();
113ab5d26daSAndreas Gohr
114ab5d26daSAndreas Gohr    return true;
11575c93b77SAndreas Gohr}
11675c93b77SAndreas Gohr
11775c93b77SAndreas Gohr/**
11875c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards
11975c93b77SAndreas Gohr *
12075c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12142ea7f44SGerrit Uitslag *
122ab5d26daSAndreas Gohr * @return array
12375c93b77SAndreas Gohr */
12475c93b77SAndreas Gohrfunction auth_loadACL() {
12575c93b77SAndreas Gohr    global $config_cascade;
126b78bf706Sromain    global $USERINFO;
127585bf44eSChristopher Smith    /* @var Input $INPUT */
128585bf44eSChristopher Smith    global $INPUT;
12975c93b77SAndreas Gohr
13075c93b77SAndreas Gohr    if(!is_readable($config_cascade['acl']['default'])) return array();
13175c93b77SAndreas Gohr
13275c93b77SAndreas Gohr    $acl = file($config_cascade['acl']['default']);
13375c93b77SAndreas Gohr
13432e82180SAndreas Gohr    $out = array();
1359ce556d2SAndreas Gohr    foreach($acl as $line) {
1369ce556d2SAndreas Gohr        $line = trim($line);
1372401f18dSSyntaxseed        if(empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
13821c3090aSChristopher Smith        list($id,$rest) = preg_split('/[ \t]+/',$line,2);
13932e82180SAndreas Gohr
140443e135dSChristopher Smith        // substitute user wildcard first (its 1:1)
141ad3d68d7SChristopher Smith        if(strstr($line, '%USER%')){
142ad3d68d7SChristopher Smith            // if user is not logged in, this ACL line is meaningless - skip it
143585bf44eSChristopher Smith            if (!$INPUT->server->has('REMOTE_USER')) continue;
144ad3d68d7SChristopher Smith
145585bf44eSChristopher Smith            $id   = str_replace('%USER%',cleanID($INPUT->server->str('REMOTE_USER')),$id);
146585bf44eSChristopher Smith            $rest = str_replace('%USER%',auth_nameencode($INPUT->server->str('REMOTE_USER')),$rest);
147ad3d68d7SChristopher Smith        }
148ad3d68d7SChristopher Smith
149ad3d68d7SChristopher Smith        // substitute group wildcard (its 1:m)
1509ce556d2SAndreas Gohr        if(strstr($line, '%GROUP%')){
151ad3d68d7SChristopher Smith            // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
15206f34f54SPhy            if(isset($USERINFO['grps'])){
1539ce556d2SAndreas Gohr                foreach((array) $USERINFO['grps'] as $grp){
154b78bf706Sromain                    $nid   = str_replace('%GROUP%',cleanID($grp),$id);
15532e82180SAndreas Gohr                    $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest);
15632e82180SAndreas Gohr                    $out[] = "$nid\t$nrest";
157b78bf706Sromain                }
15806f34f54SPhy            }
15932e82180SAndreas Gohr        } else {
16032e82180SAndreas Gohr            $out[] = "$id\t$rest";
161a8fe108bSGuy Brand        }
16211799630Sandi    }
1639ce556d2SAndreas Gohr
16432e82180SAndreas Gohr    return $out;
165f3f0262cSandi}
166f3f0262cSandi
167ab5d26daSAndreas Gohr/**
168ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK
169ab5d26daSAndreas Gohr *
17042ea7f44SGerrit Uitslag * @param array $evdata
171ab5d26daSAndreas Gohr * @return bool
172ab5d26daSAndreas Gohr */
173b5ee21aaSAdrian Langfunction auth_login_wrapper($evdata) {
174ab5d26daSAndreas Gohr    return auth_login(
175ab5d26daSAndreas Gohr        $evdata['user'],
176b5ee21aaSAdrian Lang        $evdata['password'],
177b5ee21aaSAdrian Lang        $evdata['sticky'],
178ab5d26daSAndreas Gohr        $evdata['silent']
179ab5d26daSAndreas Gohr    );
180b5ee21aaSAdrian Lang}
181b5ee21aaSAdrian Lang
182f3f0262cSandi/**
183f3f0262cSandi * This tries to login the user based on the sent auth credentials
184f3f0262cSandi *
185f3f0262cSandi * The authentication works like this: if a username was given
18615fae107Sandi * a new login is assumed and user/password are checked. If they
18715fae107Sandi * are correct the password is encrypted with blowfish and stored
18815fae107Sandi * together with the username in a cookie - the same info is stored
18915fae107Sandi * in the session, too. Additonally a browserID is stored in the
19015fae107Sandi * session.
19115fae107Sandi *
19215fae107Sandi * If no username was given the cookie is checked: if the username,
19315fae107Sandi * crypted password and browserID match between session and cookie
19415fae107Sandi * no further testing is done and the user is accepted
19515fae107Sandi *
19615fae107Sandi * If a cookie was found but no session info was availabe the
197136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
19815fae107Sandi * together with username rechecked by calling this function again.
199f3f0262cSandi *
200f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
201f3f0262cSandi * are set.
20215fae107Sandi *
20315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
20415fae107Sandi *
20515fae107Sandi * @param   string  $user    Username
20615fae107Sandi * @param   string  $pass    Cleartext Password
20715fae107Sandi * @param   bool    $sticky  Cookie should not expire
208f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
20915fae107Sandi * @return  bool             true on successful auth
210f3f0262cSandi */
211f112c2faSAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false) {
212f3f0262cSandi    global $USERINFO;
213f3f0262cSandi    global $conf;
214f3f0262cSandi    global $lang;
215e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
216cd52f92dSchris    global $auth;
217585bf44eSChristopher Smith    /* @var Input $INPUT */
218585bf44eSChristopher Smith    global $INPUT;
219ab5d26daSAndreas Gohr
220132bdbfeSandi    $sticky ? $sticky = true : $sticky = false; //sanity check
221f3f0262cSandi
222beca106aSAdrian Lang    if(!$auth) return false;
223beca106aSAdrian Lang
224bbbd6568SAndreas Gohr    if(!empty($user)) {
225132bdbfeSandi        //usual login
2265e9e1054SAndreas Gohr        if(!empty($pass) && $auth->checkPass($user, $pass)) {
227132bdbfeSandi            // make logininfo globally available
228585bf44eSChristopher Smith            $INPUT->server->set('REMOTE_USER', $user);
22930d544a4SMichael Hamann            $secret                 = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
23004369c3eSMichael Hamann            auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
231132bdbfeSandi            return true;
232f3f0262cSandi        } else {
233f3f0262cSandi            //invalid credentials - log off
234f8b1e4e7SAndreas Gohr            if(!$silent) {
235f8b1e4e7SAndreas Gohr                http_status(403, 'Login failed');
236f8b1e4e7SAndreas Gohr                msg($lang['badlogin'], -1);
237f8b1e4e7SAndreas Gohr            }
238f3f0262cSandi            auth_logoff();
239132bdbfeSandi            return false;
240f3f0262cSandi        }
241f3f0262cSandi    } else {
242132bdbfeSandi        // read cookie information
243645c0a36SAndreas Gohr        list($user, $sticky, $pass) = auth_getCookie();
244132bdbfeSandi        if($user && $pass) {
245132bdbfeSandi            // we got a cookie - see if we can trust it
246fa7c70ffSAdrian Lang
247fa7c70ffSAdrian Lang            // get session info
2480058ae75SDamien Regad            if (isset($_SESSION[DOKU_COOKIE])) {
249fa7c70ffSAdrian Lang                $session = $_SESSION[DOKU_COOKIE]['auth'];
250132bdbfeSandi                if (isset($session) &&
2517172dbc0SAndreas Gohr                    $auth->useSessionCache($user) &&
2524c989037SChris Smith                    ($session['time'] >= time() - $conf['auth_security_timeout']) &&
253132bdbfeSandi                    ($session['user'] == $user) &&
254234ce57eSAndreas Gohr                    ($session['pass'] == sha1($pass)) && //still crypted
255ab5d26daSAndreas Gohr                    ($session['buid'] == auth_browseruid())
256ab5d26daSAndreas Gohr                ) {
257234ce57eSAndreas Gohr
258132bdbfeSandi                    // he has session, cookie and browser right - let him in
259585bf44eSChristopher Smith                    $INPUT->server->set('REMOTE_USER', $user);
260132bdbfeSandi                    $USERINFO = $session['info']; //FIXME move all references to session
261132bdbfeSandi                    return true;
262132bdbfeSandi                }
2630058ae75SDamien Regad            }
264f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
26530d544a4SMichael Hamann            $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
26604369c3eSMichael Hamann            $pass   = auth_decrypt($pass, $secret);
267f112c2faSAndreas Gohr            return auth_login($user, $pass, $sticky, true);
268132bdbfeSandi        }
269132bdbfeSandi    }
270f3f0262cSandi    //just to be sure
271883179a4SAndreas Gohr    auth_logoff(true);
272132bdbfeSandi    return false;
273f3f0262cSandi}
274132bdbfeSandi
275132bdbfeSandi/**
276136ce040Sandi * Builds a pseudo UID from browser and IP data
277132bdbfeSandi *
278132bdbfeSandi * This is neither unique nor unfakable - still it adds some
279136ce040Sandi * security. Using the first part of the IP makes sure
28080b4f376SAndreas Gohr * proxy farms like AOLs are still okay.
28115fae107Sandi *
28215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
28315fae107Sandi *
284b13c0e1aSAdaKaleh * @return  string  a SHA256 sum of various browser headers
285132bdbfeSandi */
286132bdbfeSandifunction auth_browseruid() {
287585bf44eSChristopher Smith    /* @var Input $INPUT */
288585bf44eSChristopher Smith    global $INPUT;
289585bf44eSChristopher Smith
2902f9daf16SAndreas Gohr    $ip = clientIP(true);
291b13c0e1aSAdaKaleh    // convert IP string to packed binary representation
292b13c0e1aSAdaKaleh    $pip = inet_pton($ip);
293b7c67f83SAndreas Gohr
294b7c67f83SAndreas Gohr    $uid = implode("\n", [
295b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_USER_AGENT'),
296b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_ACCEPT_LANGUAGE'),
297b7c67f83SAndreas Gohr        substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6)
298b7c67f83SAndreas Gohr    ]);
299b13c0e1aSAdaKaleh    return hash('sha256', $uid);
300132bdbfeSandi}
301132bdbfeSandi
302132bdbfeSandi/**
303132bdbfeSandi * Creates a random key to encrypt the password in cookies
30415fae107Sandi *
30515fae107Sandi * This function tries to read the password for encrypting
30698407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
30715fae107Sandi * if no such file is found a random key is created and
30815fae107Sandi * and stored in this file.
30915fae107Sandi *
31015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
31142ea7f44SGerrit Uitslag *
31232ed2b36SAndreas Gohr * @param   bool $addsession if true, the sessionid is added to the salt
31330d544a4SMichael Hamann * @param   bool $secure     if security is more important than keeping the old value
31415fae107Sandi * @return  string
315132bdbfeSandi */
31630d544a4SMichael Hamannfunction auth_cookiesalt($addsession = false, $secure = false) {
317a1fe3c9cSMichael Große    if (defined('SIMPLE_TEST')) {
318fe745becSMichael Große        return 'test';
319a1fe3c9cSMichael Große    }
320132bdbfeSandi    global $conf;
32198407a7aSandi    $file = $conf['metadir'].'/_htcookiesalt';
32230d544a4SMichael Hamann    if ($secure || !file_exists($file)) {
32330d544a4SMichael Hamann        $file = $conf['metadir'].'/_htcookiesalt2';
32430d544a4SMichael Hamann    }
325132bdbfeSandi    $salt = io_readFile($file);
326132bdbfeSandi    if(empty($salt)) {
32730d544a4SMichael Hamann        $salt = bin2hex(auth_randombytes(64));
328132bdbfeSandi        io_saveFile($file, $salt);
329132bdbfeSandi    }
33032ed2b36SAndreas Gohr    if($addsession) {
33132ed2b36SAndreas Gohr        $salt .= session_id();
33232ed2b36SAndreas Gohr    }
333132bdbfeSandi    return $salt;
334f3f0262cSandi}
335f3f0262cSandi
336f3f0262cSandi/**
3377a33d2f8SNiklas Keller * Return cryptographically secure random bytes.
338483b6238SMichael Hamann *
3397a33d2f8SNiklas Keller * @author Niklas Keller <me@kelunik.com>
34042ea7f44SGerrit Uitslag *
3417a33d2f8SNiklas Keller * @param int $length number of bytes
3427a33d2f8SNiklas Keller * @return string cryptographically secure random bytes
343483b6238SMichael Hamann */
344483b6238SMichael Hamannfunction auth_randombytes($length) {
3457a33d2f8SNiklas Keller    return random_bytes($length);
346483b6238SMichael Hamann}
347483b6238SMichael Hamann
348483b6238SMichael Hamann/**
3497a33d2f8SNiklas Keller * Cryptographically secure random number generator.
350483b6238SMichael Hamann *
3517a33d2f8SNiklas Keller * @author Niklas Keller <me@kelunik.com>
35242ea7f44SGerrit Uitslag *
353483b6238SMichael Hamann * @param int $min
354483b6238SMichael Hamann * @param int $max
355483b6238SMichael Hamann * @return int
356483b6238SMichael Hamann */
357483b6238SMichael Hamannfunction auth_random($min, $max) {
3587a33d2f8SNiklas Keller    return random_int($min, $max);
359483b6238SMichael Hamann}
360483b6238SMichael Hamann
361483b6238SMichael Hamann/**
36204369c3eSMichael Hamann * Encrypt data using the given secret using AES
36304369c3eSMichael Hamann *
36404369c3eSMichael Hamann * The mode is CBC with a random initialization vector, the key is derived
36504369c3eSMichael Hamann * using pbkdf2.
36604369c3eSMichael Hamann *
36704369c3eSMichael Hamann * @param string $data   The data that shall be encrypted
36804369c3eSMichael Hamann * @param string $secret The secret/password that shall be used
36904369c3eSMichael Hamann * @return string The ciphertext
37004369c3eSMichael Hamann */
37104369c3eSMichael Hamannfunction auth_encrypt($data, $secret) {
37204369c3eSMichael Hamann    $iv     = auth_randombytes(16);
3731af2f135SAndreas Gohr    $cipher = new \phpseclib\Crypt\AES();
37404369c3eSMichael Hamann    $cipher->setPassword($secret);
37504369c3eSMichael Hamann
3767b650cefSMichael Hamann    /*
3777b650cefSMichael Hamann    this uses the encrypted IV as IV as suggested in
3787b650cefSMichael Hamann    http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
3797b650cefSMichael Hamann    for unique but necessarily random IVs. The resulting ciphertext is
3807b650cefSMichael Hamann    compatible to ciphertext that was created using a "normal" IV.
3817b650cefSMichael Hamann    */
38204369c3eSMichael Hamann    return $cipher->encrypt($iv.$data);
38304369c3eSMichael Hamann}
38404369c3eSMichael Hamann
38504369c3eSMichael Hamann/**
38604369c3eSMichael Hamann * Decrypt the given AES ciphertext
38704369c3eSMichael Hamann *
38804369c3eSMichael Hamann * The mode is CBC, the key is derived using pbkdf2
38904369c3eSMichael Hamann *
39004369c3eSMichael Hamann * @param string $ciphertext The encrypted data
39104369c3eSMichael Hamann * @param string $secret     The secret/password that shall be used
39204369c3eSMichael Hamann * @return string The decrypted data
39304369c3eSMichael Hamann */
39404369c3eSMichael Hamannfunction auth_decrypt($ciphertext, $secret) {
3957b650cefSMichael Hamann    $iv     = substr($ciphertext, 0, 16);
3961af2f135SAndreas Gohr    $cipher = new \phpseclib\Crypt\AES();
39704369c3eSMichael Hamann    $cipher->setPassword($secret);
3987b650cefSMichael Hamann    $cipher->setIV($iv);
39904369c3eSMichael Hamann
4007b650cefSMichael Hamann    return $cipher->decrypt(substr($ciphertext, 16));
40104369c3eSMichael Hamann}
40204369c3eSMichael Hamann
40304369c3eSMichael Hamann/**
404883179a4SAndreas Gohr * Log out the current user
405883179a4SAndreas Gohr *
406f3f0262cSandi * This clears all authentication data and thus log the user
407883179a4SAndreas Gohr * off. It also clears session data.
40815fae107Sandi *
40915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
41042ea7f44SGerrit Uitslag *
411883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
412f3f0262cSandi */
413883179a4SAndreas Gohrfunction auth_logoff($keepbc = false) {
414f3f0262cSandi    global $conf;
415f3f0262cSandi    global $USERINFO;
416e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
4175298a619SAndreas Gohr    global $auth;
418585bf44eSChristopher Smith    /* @var Input $INPUT */
419585bf44eSChristopher Smith    global $INPUT;
42037065e65Sandi
421d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
422e9621d07SAndreas Gohr    @session_start();
423e9621d07SAndreas Gohr
424e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
425e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
426e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
427e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
428e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
429e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
430883179a4SAndreas Gohr    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
431e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
432585bf44eSChristopher Smith    $INPUT->server->remove('REMOTE_USER');
433132bdbfeSandi    $USERINFO = null; //FIXME
434f5c6743cSAndreas Gohr
43573ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
43673ab87deSGabriel Birke    setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
4375298a619SAndreas Gohr
438880f62faSAndreas Gohr    if($auth) $auth->logOff();
439f3f0262cSandi}
440f3f0262cSandi
441f3f0262cSandi/**
442f8cc712eSAndreas Gohr * Check if a user is a manager
443f8cc712eSAndreas Gohr *
444f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
445f8cc712eSAndreas Gohr * user.
446f8cc712eSAndreas Gohr *
447f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
448f8cc712eSAndreas Gohr *
449ab5d26daSAndreas Gohr * @param string $user Username
450ab5d26daSAndreas Gohr * @param array $groups List of groups the user is in
451ab5d26daSAndreas Gohr * @param bool $adminonly when true checks if user is admin
45210396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
453ab5d26daSAndreas Gohr * @return bool
45496348f27SAndreas Gohr * @see    auth_isadmin
45596348f27SAndreas Gohr *
45696348f27SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
457f8cc712eSAndreas Gohr */
45896348f27SAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false, $recache=false) {
459f8cc712eSAndreas Gohr    global $conf;
460f8cc712eSAndreas Gohr    global $USERINFO;
461e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
462d752aedeSAndreas Gohr    global $auth;
463585bf44eSChristopher Smith    /* @var Input $INPUT */
464585bf44eSChristopher Smith    global $INPUT;
465585bf44eSChristopher Smith
466f8cc712eSAndreas Gohr
467beca106aSAdrian Lang    if(!$auth) return false;
468c66972f2SAdrian Lang    if(is_null($user)) {
469585bf44eSChristopher Smith        if(!$INPUT->server->has('REMOTE_USER')) {
470c66972f2SAdrian Lang            return false;
471c66972f2SAdrian Lang        } else {
472585bf44eSChristopher Smith            $user = $INPUT->server->str('REMOTE_USER');
473c66972f2SAdrian Lang        }
474c66972f2SAdrian Lang    }
475d6dc956fSAndreas Gohr    if (is_null($groups)) {
4761525c228SAnna Dabrowska        // checking the logged in user, or another one?
4771525c228SAnna Dabrowska        if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) {
4781525c228SAnna Dabrowska            $groups =  (array) $USERINFO['grps'];
47966b108d6SAnna Dabrowska        } else {
4806cf7b139SAndreas Gohr            $groups = $auth->getUserData($user);
4816cf7b139SAndreas Gohr            $groups = $groups ? $groups['grps'] : [];
48266b108d6SAnna Dabrowska        }
483e259aa79SAndreas Gohr    }
484e259aa79SAndreas Gohr
48596348f27SAndreas Gohr    // prefer cached result
48696348f27SAndreas Gohr    static $cache = [];
48710396f77SAndreas Gohr    $cachekey = serialize([$user, $adminonly, $groups]);
48896348f27SAndreas Gohr    if (!isset($cache[$cachekey]) || $recache) {
489d6dc956fSAndreas Gohr        // check superuser match
49096348f27SAndreas Gohr        $ok = auth_isMember($conf['superuser'], $user, $groups);
49100ce12daSChris Smith
49296348f27SAndreas Gohr        // check managers
49396348f27SAndreas Gohr        if (!$ok && !$adminonly) {
49496348f27SAndreas Gohr            $ok = auth_isMember($conf['manager'], $user, $groups);
49596348f27SAndreas Gohr        }
49696348f27SAndreas Gohr
49796348f27SAndreas Gohr        $cache[$cachekey] = $ok;
49896348f27SAndreas Gohr    }
49996348f27SAndreas Gohr
50096348f27SAndreas Gohr    return $cache[$cachekey];
501f8cc712eSAndreas Gohr}
502f8cc712eSAndreas Gohr
503f8cc712eSAndreas Gohr/**
504f8cc712eSAndreas Gohr * Check if a user is admin
505f8cc712eSAndreas Gohr *
506f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
507f8cc712eSAndreas Gohr *
508f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
509f8cc712eSAndreas Gohr *
51096348f27SAndreas Gohr * @param string $user Username
51196348f27SAndreas Gohr * @param array $groups List of groups the user is in
51210396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
51396348f27SAndreas Gohr * @return bool
514f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
515ab5d26daSAndreas Gohr * @see auth_ismanager()
51642ea7f44SGerrit Uitslag *
517f8cc712eSAndreas Gohr */
51896348f27SAndreas Gohrfunction auth_isadmin($user = null, $groups = null, $recache=false) {
51996348f27SAndreas Gohr    return auth_ismanager($user, $groups, true, $recache);
520f8cc712eSAndreas Gohr}
521f8cc712eSAndreas Gohr
522d6dc956fSAndreas Gohr/**
523d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
524d6dc956fSAndreas Gohr * users and groups to determine membership status
525d6dc956fSAndreas Gohr *
526d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
527d6dc956fSAndreas Gohr *
52842ea7f44SGerrit Uitslag * @param string $memberlist commaseparated list of allowed users and groups
52942ea7f44SGerrit Uitslag * @param string $user       user to match against
53042ea7f44SGerrit Uitslag * @param array  $groups     groups the user is member of
5315446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
532d6dc956fSAndreas Gohr */
533d6dc956fSAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups) {
534e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
535d6dc956fSAndreas Gohr    global $auth;
536d6dc956fSAndreas Gohr    if(!$auth) return false;
537d6dc956fSAndreas Gohr
538d6dc956fSAndreas Gohr    // clean user and groups
5394f56ecbfSAdrian Lang    if(!$auth->isCaseSensitive()) {
5408cbc5ee8SAndreas Gohr        $user   = \dokuwiki\Utf8\PhpString::strtolower($user);
541a7e2efd2SAndreas Gohr        $groups = array_map([\dokuwiki\Utf8\PhpString::class, 'strtolower'], $groups);
542d6dc956fSAndreas Gohr    }
543d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
544d6dc956fSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), $groups);
545d6dc956fSAndreas Gohr
546d6dc956fSAndreas Gohr    // extract the memberlist
547d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
548d6dc956fSAndreas Gohr    $members = array_map('trim', $members);
549d6dc956fSAndreas Gohr    $members = array_unique($members);
550d6dc956fSAndreas Gohr    $members = array_filter($members);
551d6dc956fSAndreas Gohr
552d6dc956fSAndreas Gohr    // compare cleaned values
553d6dc956fSAndreas Gohr    foreach($members as $member) {
554e5204a12SJurgen Hart        if($member == '@ALL' ) return true;
5558cbc5ee8SAndreas Gohr        if(!$auth->isCaseSensitive()) $member = \dokuwiki\Utf8\PhpString::strtolower($member);
556d6dc956fSAndreas Gohr        if($member[0] == '@') {
557d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
558d6dc956fSAndreas Gohr            if(in_array($member, $groups)) return true;
559d6dc956fSAndreas Gohr        } else {
560d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
561d6dc956fSAndreas Gohr            if($member == $user) return true;
562d6dc956fSAndreas Gohr        }
563d6dc956fSAndreas Gohr    }
564d6dc956fSAndreas Gohr
565d6dc956fSAndreas Gohr    // still here? not a member!
566d6dc956fSAndreas Gohr    return false;
567d6dc956fSAndreas Gohr}
568d6dc956fSAndreas Gohr
569f8cc712eSAndreas Gohr/**
57015fae107Sandi * Convinience function for auth_aclcheck()
57115fae107Sandi *
57215fae107Sandi * This checks the permissions for the current user
57315fae107Sandi *
57415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
57515fae107Sandi *
5761698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
57715fae107Sandi * @return int          permission level
578f3f0262cSandi */
579f3f0262cSandifunction auth_quickaclcheck($id) {
580f3f0262cSandi    global $conf;
581f3f0262cSandi    global $USERINFO;
582585bf44eSChristopher Smith    /* @var Input $INPUT */
583585bf44eSChristopher Smith    global $INPUT;
584f3f0262cSandi    # if no ACL is used always return upload rights
585f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
5863e9ae63dSPhy    return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : array());
587f3f0262cSandi}
588f3f0262cSandi
589f3f0262cSandi/**
590c17acc9fSAndreas Gohr * Returns the maximum rights a user has for the given ID or its namespace
59115fae107Sandi *
59215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
59342ea7f44SGerrit Uitslag *
594c17acc9fSAndreas Gohr * @triggers AUTH_ACL_CHECK
5951698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
59615fae107Sandi * @param  string       $user   Username
5973272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
59815fae107Sandi * @return int             permission level
599f3f0262cSandi */
600f3f0262cSandifunction auth_aclcheck($id, $user, $groups) {
601c17acc9fSAndreas Gohr    $data = array(
602bf8f8509SAndreas Gohr        'id'     => $id ?? '',
603c17acc9fSAndreas Gohr        'user'   => $user,
604c17acc9fSAndreas Gohr        'groups' => $groups
605c17acc9fSAndreas Gohr    );
606c17acc9fSAndreas Gohr
607cbb44eabSAndreas Gohr    return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
608c17acc9fSAndreas Gohr}
609c17acc9fSAndreas Gohr
610c17acc9fSAndreas Gohr/**
611c17acc9fSAndreas Gohr * default ACL check method
612c17acc9fSAndreas Gohr *
613c17acc9fSAndreas Gohr * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
614c17acc9fSAndreas Gohr *
615c17acc9fSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
61642ea7f44SGerrit Uitslag *
617c17acc9fSAndreas Gohr * @param  array $data event data
618c17acc9fSAndreas Gohr * @return int   permission level
619c17acc9fSAndreas Gohr */
620c17acc9fSAndreas Gohrfunction auth_aclcheck_cb($data) {
621c17acc9fSAndreas Gohr    $id     =& $data['id'];
622c17acc9fSAndreas Gohr    $user   =& $data['user'];
623c17acc9fSAndreas Gohr    $groups =& $data['groups'];
624c17acc9fSAndreas Gohr
625f3f0262cSandi    global $conf;
626f3f0262cSandi    global $AUTH_ACL;
627e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
628d752aedeSAndreas Gohr    global $auth;
629f3f0262cSandi
63085d03f68SAndreas Gohr    // if no ACL is used always return upload rights
631f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
632beca106aSAdrian Lang    if(!$auth) return AUTH_NONE;
633bf8f8509SAndreas Gohr    if(!is_array($AUTH_ACL)) return AUTH_NONE;
634f3f0262cSandi
635074cf26bSandi    //make sure groups is an array
636074cf26bSandi    if(!is_array($groups)) $groups = array();
637074cf26bSandi
63885d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
639ab5d26daSAndreas Gohr    if(auth_isadmin($user, $groups)) {
640ab5d26daSAndreas Gohr        return AUTH_ADMIN;
641ab5d26daSAndreas Gohr    }
64285d03f68SAndreas Gohr
643eb3ce0d5SKazutaka Miyasaka    if(!$auth->isCaseSensitive()) {
6448cbc5ee8SAndreas Gohr        $user   = \dokuwiki\Utf8\PhpString::strtolower($user);
645c7dab4e8SAndreas Gohr        $groups = array_map([\dokuwiki\Utf8\PhpString::class, 'strtolower'], $groups);
646eb3ce0d5SKazutaka Miyasaka    }
64737ff2261SSascha Klopp    $user   = auth_nameencode($auth->cleanUser($user));
648d752aedeSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
64985d03f68SAndreas Gohr
6506c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
65137ff2261SSascha Klopp    foreach($groups as &$group) {
65237ff2261SSascha Klopp        $group = '@'.auth_nameencode($group);
65310a76f6fSfrank    }
65410a76f6fSfrank
655f3f0262cSandi    $ns   = getNS($id);
656f3f0262cSandi    $perm = -1;
657f3f0262cSandi
658f3f0262cSandi    //add ALL group
659f3f0262cSandi    $groups[] = '@ALL';
66037ff2261SSascha Klopp
661f3f0262cSandi    //add User
66234aeb4afSAndreas Gohr    if($user) $groups[] = $user;
663f3f0262cSandi
664f3f0262cSandi    //check exact match first
66521c3090aSChristopher Smith    $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
666f3f0262cSandi    if(count($matches)) {
667f3f0262cSandi        foreach($matches as $match) {
668f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
66921c3090aSChristopher Smith            $acl   = preg_split('/[ \t]+/', $match);
670eb3ce0d5SKazutaka Miyasaka            if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
6718cbc5ee8SAndreas Gohr                $acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]);
672eb3ce0d5SKazutaka Miyasaka            }
67348d7b7a6SDominik Eckelmann            if(!in_array($acl[1], $groups)) {
67448d7b7a6SDominik Eckelmann                continue;
67548d7b7a6SDominik Eckelmann            }
6768ef6b7caSandi            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
677f3f0262cSandi            if($acl[2] > $perm) {
678f3f0262cSandi                $perm = $acl[2];
679f3f0262cSandi            }
680f3f0262cSandi        }
681f3f0262cSandi        if($perm > -1) {
682f3f0262cSandi            //we had a match - return it
683def492a2SGuillaume Turri            return (int) $perm;
684f3f0262cSandi        }
685f3f0262cSandi    }
686f3f0262cSandi
687f3f0262cSandi    //still here? do the namespace checks
688f3f0262cSandi    if($ns) {
6893e304b55SMichael Hamann        $path = $ns.':*';
690f3f0262cSandi    } else {
6913e304b55SMichael Hamann        $path = '*'; //root document
692f3f0262cSandi    }
693f3f0262cSandi
694f3f0262cSandi    do {
69521c3090aSChristopher Smith        $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
696f3f0262cSandi        if(count($matches)) {
697f3f0262cSandi            foreach($matches as $match) {
698f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
69921c3090aSChristopher Smith                $acl   = preg_split('/[ \t]+/', $match);
700eb3ce0d5SKazutaka Miyasaka                if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
7018cbc5ee8SAndreas Gohr                    $acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]);
702eb3ce0d5SKazutaka Miyasaka                }
70348d7b7a6SDominik Eckelmann                if(!in_array($acl[1], $groups)) {
70448d7b7a6SDominik Eckelmann                    continue;
70548d7b7a6SDominik Eckelmann                }
7068ef6b7caSandi                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
707f3f0262cSandi                if($acl[2] > $perm) {
708f3f0262cSandi                    $perm = $acl[2];
709f3f0262cSandi                }
710f3f0262cSandi            }
711f3f0262cSandi            //we had a match - return it
71248d7b7a6SDominik Eckelmann            if($perm != -1) {
713def492a2SGuillaume Turri                return (int) $perm;
714f3f0262cSandi            }
71548d7b7a6SDominik Eckelmann        }
716f3f0262cSandi        //get next higher namespace
717f3f0262cSandi        $ns = getNS($ns);
718f3f0262cSandi
7193e304b55SMichael Hamann        if($path != '*') {
7203e304b55SMichael Hamann            $path = $ns.':*';
7213e304b55SMichael Hamann            if($path == ':*') $path = '*';
722f3f0262cSandi        } else {
723f3f0262cSandi            //we did this already
724f3f0262cSandi            //looks like there is something wrong with the ACL
725f3f0262cSandi            //break here
726d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
727d5ce66f6SAndreas Gohr            return AUTH_NONE;
728f3f0262cSandi        }
729f3f0262cSandi    } while(1); //this should never loop endless
730ab5d26daSAndreas Gohr    return AUTH_NONE;
731f3f0262cSandi}
732f3f0262cSandi
733f3f0262cSandi/**
7346c2bb100SAndreas Gohr * Encode ASCII special chars
7356c2bb100SAndreas Gohr *
7366c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
7376c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
7386c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
7396c2bb100SAndreas Gohr * urlencoding!).
7406c2bb100SAndreas Gohr *
7416c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
7426c2bb100SAndreas Gohr *
7436c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
7446c2bb100SAndreas Gohr * @see rawurldecode()
74542ea7f44SGerrit Uitslag *
74642ea7f44SGerrit Uitslag * @param string $name
74742ea7f44SGerrit Uitslag * @param bool $skip_group
74842ea7f44SGerrit Uitslag * @return string
7496c2bb100SAndreas Gohr */
750e838fc2eSAndreas Gohrfunction auth_nameencode($name, $skip_group = false) {
751a424cd8eSchris    global $cache_authname;
752a424cd8eSchris    $cache =& $cache_authname;
75331784267SAndreas Gohr    $name  = (string) $name;
754a424cd8eSchris
75580601d26SAndreas Gohr    // never encode wildcard FS#1955
75680601d26SAndreas Gohr    if($name == '%USER%') return $name;
757b78bf706Sromain    if($name == '%GROUP%') return $name;
75880601d26SAndreas Gohr
759a424cd8eSchris    if(!isset($cache[$name][$skip_group])) {
7602401f18dSSyntaxseed        if($skip_group && $name[0] == '@') {
76130f6faf0SChristopher Smith            $cache[$name][$skip_group] = '@'.preg_replace_callback(
76230f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
76330f6faf0SChristopher Smith                'auth_nameencode_callback', substr($name, 1)
764ab5d26daSAndreas Gohr            );
765e838fc2eSAndreas Gohr        } else {
76630f6faf0SChristopher Smith            $cache[$name][$skip_group] = preg_replace_callback(
76730f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
76830f6faf0SChristopher Smith                'auth_nameencode_callback', $name
769ab5d26daSAndreas Gohr            );
770e838fc2eSAndreas Gohr        }
7716c2bb100SAndreas Gohr    }
7726c2bb100SAndreas Gohr
773a424cd8eSchris    return $cache[$name][$skip_group];
774a424cd8eSchris}
775a424cd8eSchris
77604d68ae4SGerrit Uitslag/**
77704d68ae4SGerrit Uitslag * callback encodes the matches
77804d68ae4SGerrit Uitslag *
77904d68ae4SGerrit Uitslag * @param array $matches first complete match, next matching subpatterms
78004d68ae4SGerrit Uitslag * @return string
78104d68ae4SGerrit Uitslag */
78230f6faf0SChristopher Smithfunction auth_nameencode_callback($matches) {
78330f6faf0SChristopher Smith    return '%'.dechex(ord(substr($matches[1],-1)));
78430f6faf0SChristopher Smith}
78530f6faf0SChristopher Smith
7866c2bb100SAndreas Gohr/**
787f3f0262cSandi * Create a pronouncable password
788f3f0262cSandi *
7898a285f7fSAndreas Gohr * The $foruser variable might be used by plugins to run additional password
7908a285f7fSAndreas Gohr * policy checks, but is not used by the default implementation
7918a285f7fSAndreas Gohr *
79215fae107Sandi * @author   Andreas Gohr <andi@splitbrain.org>
79315fae107Sandi * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
7948a285f7fSAndreas Gohr * @triggers AUTH_PASSWORD_GENERATE
79515fae107Sandi *
7968a285f7fSAndreas Gohr * @param  string $foruser username for which the password is generated
79715fae107Sandi * @return string  pronouncable password
798f3f0262cSandi */
7998a285f7fSAndreas Gohrfunction auth_pwgen($foruser = '') {
8008a285f7fSAndreas Gohr    $data = array(
801d628dcf3SAndreas Gohr        'password' => '',
802d628dcf3SAndreas Gohr        'foruser'  => $foruser
8038a285f7fSAndreas Gohr    );
8048a285f7fSAndreas Gohr
805e1d9dcc8SAndreas Gohr    $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
8068a285f7fSAndreas Gohr    if($evt->advise_before(true)) {
807f3f0262cSandi        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
808f3f0262cSandi        $v = 'aeiou'; //vowels
809f3f0262cSandi        $a = $c.$v; //both
810987c8d26SAndreas Gohr        $s = '!$%&?+*~#-_:.;,'; // specials
811f3f0262cSandi
812987c8d26SAndreas Gohr        //use thre syllables...
813987c8d26SAndreas Gohr        for($i = 0; $i < 3; $i++) {
814483b6238SMichael Hamann            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
815483b6238SMichael Hamann            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
816483b6238SMichael Hamann            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
817f3f0262cSandi        }
818987c8d26SAndreas Gohr        //... and add a nice number and special
81943f71e05Ssdavis80        $data['password'] .= $s[auth_random(0, strlen($s) - 1)].auth_random(10, 99);
8208a285f7fSAndreas Gohr    }
8218a285f7fSAndreas Gohr    $evt->advise_after();
822f3f0262cSandi
8238a285f7fSAndreas Gohr    return $data['password'];
824f3f0262cSandi}
825f3f0262cSandi
826f3f0262cSandi/**
827f3f0262cSandi * Sends a password to the given user
828f3f0262cSandi *
82915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
83042ea7f44SGerrit Uitslag *
831ab5d26daSAndreas Gohr * @param string $user Login name of the user
832ab5d26daSAndreas Gohr * @param string $password The new password in clear text
83315fae107Sandi * @return bool  true on success
834f3f0262cSandi */
835f3f0262cSandifunction auth_sendPassword($user, $password) {
836f3f0262cSandi    global $lang;
837e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
838cd52f92dSchris    global $auth;
839beca106aSAdrian Lang    if(!$auth) return false;
840cd52f92dSchris
841d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
8422dc9e900SChristopher Smith    $userinfo = $auth->getUserData($user, $requireGroups = false);
843f3f0262cSandi
84487ddda95Sandi    if(!$userinfo['mail']) return false;
845f3f0262cSandi
846f3f0262cSandi    $text = rawLocale('password');
847d7169d19SAndreas Gohr    $trep = array(
848d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
849d7169d19SAndreas Gohr        'LOGIN'    => $user,
850d7169d19SAndreas Gohr        'PASSWORD' => $password
851d7169d19SAndreas Gohr    );
852f3f0262cSandi
853d7169d19SAndreas Gohr    $mail = new Mailer();
854102cdbd7SLarsGit223    $mail->to($mail->getCleanName($userinfo['name']).' <'.$userinfo['mail'].'>');
855d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
856d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
857d7169d19SAndreas Gohr    return $mail->send();
858f3f0262cSandi}
859f3f0262cSandi
860f3f0262cSandi/**
86115fae107Sandi * Register a new user
862f3f0262cSandi *
86315fae107Sandi * This registers a new user - Data is read directly from $_POST
86415fae107Sandi *
86515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
86642ea7f44SGerrit Uitslag *
86715fae107Sandi * @return bool  true on success, false on any error
868f3f0262cSandi */
869f3f0262cSandifunction register() {
870f3f0262cSandi    global $lang;
871eb5d07e4Sjan    global $conf;
872e1d9dcc8SAndreas Gohr    /* @var \dokuwiki\Extension\AuthPlugin $auth */
873cd52f92dSchris    global $auth;
87464273335SAndreas Gohr    global $INPUT;
875f3f0262cSandi
87664273335SAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
8773a48618aSAnika Henke    if(!actionOK('register')) return false;
878640145a5Sandi
87964273335SAndreas Gohr    // gather input
88064273335SAndreas Gohr    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
88164273335SAndreas Gohr    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
88264273335SAndreas Gohr    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
88364273335SAndreas Gohr    $pass     = $INPUT->post->str('pass');
88464273335SAndreas Gohr    $passchk  = $INPUT->post->str('passchk');
885d752aedeSAndreas Gohr
88664273335SAndreas Gohr    if(empty($login) || empty($fullname) || empty($email)) {
887f3f0262cSandi        msg($lang['regmissing'], -1);
888f3f0262cSandi        return false;
889f3f0262cSandi    }
890f3f0262cSandi
891cab2716aSmatthias.grimm    if($conf['autopasswd']) {
8928a285f7fSAndreas Gohr        $pass = auth_pwgen($login); // automatically generate password
89364273335SAndreas Gohr    } elseif(empty($pass) || empty($passchk)) {
894bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
895cab2716aSmatthias.grimm        return false;
89664273335SAndreas Gohr    } elseif($pass != $passchk) {
897bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
898cab2716aSmatthias.grimm        return false;
899cab2716aSmatthias.grimm    }
900cab2716aSmatthias.grimm
901f3f0262cSandi    //check mail
90264273335SAndreas Gohr    if(!mail_isvalid($email)) {
903f3f0262cSandi        msg($lang['regbadmail'], -1);
904f3f0262cSandi        return false;
905f3f0262cSandi    }
906f3f0262cSandi
907f3f0262cSandi    //okay try to create the user
90864273335SAndreas Gohr    if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) {
909db9faf02SPatrick Brown        msg($lang['regfail'], -1);
910f3f0262cSandi        return false;
911f3f0262cSandi    }
912f3f0262cSandi
913790b7720SAndreas Gohr    // send notification about the new user
91475d66495SMichael Große    $subscription = new RegistrationSubscriptionSender();
91575d66495SMichael Große    $subscription->sendRegister($login, $fullname, $email);
91602a498e7Schris
917790b7720SAndreas Gohr    // are we done?
918cab2716aSmatthias.grimm    if(!$conf['autopasswd']) {
919cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
920cab2716aSmatthias.grimm        return true;
921cab2716aSmatthias.grimm    }
922cab2716aSmatthias.grimm
923790b7720SAndreas Gohr    // autogenerated password? then send password to user
92464273335SAndreas Gohr    if(auth_sendPassword($login, $pass)) {
925f3f0262cSandi        msg($lang['regsuccess'], 1);
926f3f0262cSandi        return true;
927f3f0262cSandi    } else {
928f3f0262cSandi        msg($lang['regmailfail'], -1);
929f3f0262cSandi        return false;
930f3f0262cSandi    }
931f3f0262cSandi}
932f3f0262cSandi
93310a76f6fSfrank/**
9348b06d178Schris * Update user profile
9358b06d178Schris *
9368b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
9378b06d178Schris */
9388b06d178Schrisfunction updateprofile() {
9398b06d178Schris    global $conf;
9408b06d178Schris    global $lang;
941e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
942cd52f92dSchris    global $auth;
943bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
944bcc94b2cSAndreas Gohr    global $INPUT;
9458b06d178Schris
946bcc94b2cSAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
9471b2a85e8SAndreas Gohr    if(!checkSecurityToken()) return false;
9488b06d178Schris
9493a48618aSAnika Henke    if(!actionOK('profile')) {
9508b06d178Schris        msg($lang['profna'], -1);
9518b06d178Schris        return false;
9528b06d178Schris    }
9538b06d178Schris
954bcc94b2cSAndreas Gohr    $changes         = array();
955bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
956bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
957bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
958bcc94b2cSAndreas Gohr
959bcc94b2cSAndreas Gohr    // check misspelled passwords
960bcc94b2cSAndreas Gohr    if($changes['pass'] != $INPUT->post->str('passchk')) {
961bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
9628b06d178Schris        return false;
9638b06d178Schris    }
9648b06d178Schris
9658b06d178Schris    // clean fullname and email
966bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
967bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
9688b06d178Schris
969bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
970bcc94b2cSAndreas Gohr    if((empty($changes['name']) && $auth->canDo('modName')) ||
971bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
972ab5d26daSAndreas Gohr    ) {
9738b06d178Schris        msg($lang['profnoempty'], -1);
9748b06d178Schris        return false;
9758b06d178Schris    }
976bcc94b2cSAndreas Gohr    if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
9778b06d178Schris        msg($lang['regbadmail'], -1);
9788b06d178Schris        return false;
9798b06d178Schris    }
9808b06d178Schris
981bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
9824c21b7eeSAndreas Gohr
983bcc94b2cSAndreas Gohr    // check for unavailable capabilities
984bcc94b2cSAndreas Gohr    if(!$auth->canDo('modName')) unset($changes['name']);
985bcc94b2cSAndreas Gohr    if(!$auth->canDo('modMail')) unset($changes['mail']);
986bcc94b2cSAndreas Gohr    if(!$auth->canDo('modPass')) unset($changes['pass']);
987bcc94b2cSAndreas Gohr
988bcc94b2cSAndreas Gohr    // anything to do?
9898b06d178Schris    if(!count($changes)) {
9908b06d178Schris        msg($lang['profnochange'], -1);
9918b06d178Schris        return false;
9928b06d178Schris    }
9938b06d178Schris
9948b06d178Schris    if($conf['profileconfirm']) {
995585bf44eSChristopher Smith        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
99671422fc8SChristopher Smith            msg($lang['badpassconfirm'], -1);
9978b06d178Schris            return false;
9988b06d178Schris        }
9998b06d178Schris    }
10008b06d178Schris
1001e6c4392fSPatrick Brown    if(!$auth->triggerUserMod('modify', array($INPUT->server->str('REMOTE_USER'), &$changes))) {
1002db9faf02SPatrick Brown        msg($lang['proffail'], -1);
1003db9faf02SPatrick Brown        return false;
1004db9faf02SPatrick Brown    }
1005db9faf02SPatrick Brown
100632ed2b36SAndreas Gohr    if($changes['pass']) {
1007c276e9e8SMarcel Pennewiss        // update cookie and session with the changed data
1008ab5d26daSAndreas Gohr        list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
100904369c3eSMichael Hamann        $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1010585bf44eSChristopher Smith        auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
1011c276e9e8SMarcel Pennewiss    } else {
1012c276e9e8SMarcel Pennewiss        // make sure the session is writable
1013c276e9e8SMarcel Pennewiss        @session_start();
1014c276e9e8SMarcel Pennewiss        // invalidate session cache
1015c276e9e8SMarcel Pennewiss        $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
1016c276e9e8SMarcel Pennewiss        session_write_close();
101732ed2b36SAndreas Gohr    }
1018c276e9e8SMarcel Pennewiss
101925b2a98cSMichael Klier    return true;
1020a0b5b007SChris Smith}
1021ab5d26daSAndreas Gohr
102204d68ae4SGerrit Uitslag/**
102304d68ae4SGerrit Uitslag * Delete the current logged-in user
102404d68ae4SGerrit Uitslag *
102504d68ae4SGerrit Uitslag * @return bool true on success, false on any error
102604d68ae4SGerrit Uitslag */
10272a7abf2dSChristopher Smithfunction auth_deleteprofile(){
10282a7abf2dSChristopher Smith    global $conf;
10292a7abf2dSChristopher Smith    global $lang;
1030e1d9dcc8SAndreas Gohr    /* @var \dokuwiki\Extension\AuthPlugin $auth */
10312a7abf2dSChristopher Smith    global $auth;
10322a7abf2dSChristopher Smith    /* @var Input $INPUT */
10332a7abf2dSChristopher Smith    global $INPUT;
10342a7abf2dSChristopher Smith
10352a7abf2dSChristopher Smith    if(!$INPUT->post->bool('delete')) return false;
10362a7abf2dSChristopher Smith    if(!checkSecurityToken()) return false;
10372a7abf2dSChristopher Smith
10382a7abf2dSChristopher Smith    // action prevented or auth module disallows
10392a7abf2dSChristopher Smith    if(!actionOK('profile_delete') || !$auth->canDo('delUser')) {
10402a7abf2dSChristopher Smith        msg($lang['profnodelete'], -1);
10412a7abf2dSChristopher Smith        return false;
10422a7abf2dSChristopher Smith    }
10432a7abf2dSChristopher Smith
10442a7abf2dSChristopher Smith    if(!$INPUT->post->bool('confirm_delete')){
10452a7abf2dSChristopher Smith        msg($lang['profconfdeletemissing'], -1);
10462a7abf2dSChristopher Smith        return false;
10472a7abf2dSChristopher Smith    }
10482a7abf2dSChristopher Smith
10492a7abf2dSChristopher Smith    if($conf['profileconfirm']) {
1050585bf44eSChristopher Smith        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
10512a7abf2dSChristopher Smith            msg($lang['badpassconfirm'], -1);
10522a7abf2dSChristopher Smith            return false;
10532a7abf2dSChristopher Smith        }
10542a7abf2dSChristopher Smith    }
10552a7abf2dSChristopher Smith
105659bc3b48SGerrit Uitslag    $deleted = array();
1057585bf44eSChristopher Smith    $deleted[] = $INPUT->server->str('REMOTE_USER');
105873012efdSChristopher Smith    if($auth->triggerUserMod('delete', array($deleted))) {
10592a7abf2dSChristopher Smith        // force and immediate logout including removing the sticky cookie
10602a7abf2dSChristopher Smith        auth_logoff();
10612a7abf2dSChristopher Smith        return true;
10622a7abf2dSChristopher Smith    }
10632a7abf2dSChristopher Smith
10642a7abf2dSChristopher Smith    return false;
10652a7abf2dSChristopher Smith}
10662a7abf2dSChristopher Smith
10678b06d178Schris/**
10688b06d178Schris * Send a  new password
10698b06d178Schris *
10701d5856cfSAndreas Gohr * This function handles both phases of the password reset:
10711d5856cfSAndreas Gohr *
10721d5856cfSAndreas Gohr *   - handling the first request of password reset
10731d5856cfSAndreas Gohr *   - validating the password reset auth token
10741d5856cfSAndreas Gohr *
10758b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
10768b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
10771d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10788b06d178Schris *
10798b06d178Schris * @return bool true on success, false on any error
10808b06d178Schris */
10818b06d178Schrisfunction act_resendpwd() {
10828b06d178Schris    global $lang;
10838b06d178Schris    global $conf;
1084e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1085cd52f92dSchris    global $auth;
1086bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1087bcc94b2cSAndreas Gohr    global $INPUT;
10888b06d178Schris
10893a48618aSAnika Henke    if(!actionOK('resendpwd')) {
10908b06d178Schris        msg($lang['resendna'], -1);
10918b06d178Schris        return false;
10928b06d178Schris    }
10938b06d178Schris
1094bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
10958b06d178Schris
10961d5856cfSAndreas Gohr    if($token) {
1097cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
10981d5856cfSAndreas Gohr
10992401f18dSSyntaxseed        $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
110079e79377SAndreas Gohr        if(!file_exists($tfile)) {
11011d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1102bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
11031d5856cfSAndreas Gohr            return false;
11041d5856cfSAndreas Gohr        }
11058a9735e3SAndreas Gohr        // token is only valid for 3 days
11068a9735e3SAndreas Gohr        if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
11078a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1108bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
11091d5856cfSAndreas Gohr            @unlink($tfile);
11108a9735e3SAndreas Gohr            return false;
11118a9735e3SAndreas Gohr        }
11128a9735e3SAndreas Gohr
11138b06d178Schris        $user     = io_readfile($tfile);
11142dc9e900SChristopher Smith        $userinfo = $auth->getUserData($user, $requireGroups = false);
11158b06d178Schris        if(!$userinfo['mail']) {
11168b06d178Schris            msg($lang['resendpwdnouser'], -1);
11178b06d178Schris            return false;
11188b06d178Schris        }
11198b06d178Schris
1120cc204bbdSAndreas Gohr        if(!$conf['autopasswd']) { // we let the user choose a password
1121bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
1122bcc94b2cSAndreas Gohr
1123cc204bbdSAndreas Gohr            // password given correctly?
1124bcc94b2cSAndreas Gohr            if(!$pass) return false;
1125bcc94b2cSAndreas Gohr            if($pass != $INPUT->str('passchk')) {
1126451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
1127cc204bbdSAndreas Gohr                return false;
1128cc204bbdSAndreas Gohr            }
1129cc204bbdSAndreas Gohr
1130bcc94b2cSAndreas Gohr            // change it
1131cc204bbdSAndreas Gohr            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1132db9faf02SPatrick Brown                msg($lang['proffail'], -1);
1133cc204bbdSAndreas Gohr                return false;
1134cc204bbdSAndreas Gohr            }
1135cc204bbdSAndreas Gohr
1136cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
1137cc204bbdSAndreas Gohr
11388a285f7fSAndreas Gohr            $pass = auth_pwgen($user);
11397d3c8d42SGabriel Birke            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1140db9faf02SPatrick Brown                msg($lang['proffail'], -1);
11418b06d178Schris                return false;
11428b06d178Schris            }
11438b06d178Schris
11448b06d178Schris            if(auth_sendPassword($user, $pass)) {
11458b06d178Schris                msg($lang['resendpwdsuccess'], 1);
11468b06d178Schris            } else {
11478b06d178Schris                msg($lang['regmailfail'], -1);
11488b06d178Schris            }
1149cc204bbdSAndreas Gohr        }
1150cc204bbdSAndreas Gohr
1151cc204bbdSAndreas Gohr        @unlink($tfile);
11528b06d178Schris        return true;
11531d5856cfSAndreas Gohr
11541d5856cfSAndreas Gohr    } else {
11551d5856cfSAndreas Gohr        // we're in request phase
11561d5856cfSAndreas Gohr
1157bcc94b2cSAndreas Gohr        if(!$INPUT->post->bool('save')) return false;
11581d5856cfSAndreas Gohr
1159bcc94b2cSAndreas Gohr        if(!$INPUT->post->str('login')) {
11601d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
11611d5856cfSAndreas Gohr            return false;
11621d5856cfSAndreas Gohr        } else {
1163bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
11641d5856cfSAndreas Gohr        }
11651d5856cfSAndreas Gohr
11662dc9e900SChristopher Smith        $userinfo = $auth->getUserData($user, $requireGroups = false);
11671d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
11681d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
11691d5856cfSAndreas Gohr            return false;
11701d5856cfSAndreas Gohr        }
11711d5856cfSAndreas Gohr
11721d5856cfSAndreas Gohr        // generate auth token
1173483b6238SMichael Hamann        $token = md5(auth_randombytes(16)); // random secret
11742401f18dSSyntaxseed        $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
11751d5856cfSAndreas Gohr        $url   = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
11761d5856cfSAndreas Gohr
11771d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
11781d5856cfSAndreas Gohr
11791d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
1180d7169d19SAndreas Gohr        $trep = array(
1181d7169d19SAndreas Gohr            'FULLNAME' => $userinfo['name'],
1182d7169d19SAndreas Gohr            'LOGIN'    => $user,
1183d7169d19SAndreas Gohr            'CONFIRM'  => $url
1184d7169d19SAndreas Gohr        );
11851d5856cfSAndreas Gohr
1186d7169d19SAndreas Gohr        $mail = new Mailer();
1187d7169d19SAndreas Gohr        $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1188d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
1189d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
1190d7169d19SAndreas Gohr        if($mail->send()) {
11911d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
11921d5856cfSAndreas Gohr        } else {
11931d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
11941d5856cfSAndreas Gohr        }
11951d5856cfSAndreas Gohr        return true;
11961d5856cfSAndreas Gohr    }
1197ab5d26daSAndreas Gohr    // never reached
11988b06d178Schris}
11998b06d178Schris
12008b06d178Schris/**
1201b0855b11Sandi * Encrypts a password using the given method and salt
1202b0855b11Sandi *
1203b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1204b0855b11Sandi * is chosen.
1205b0855b11Sandi *
1206b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
120742ea7f44SGerrit Uitslag *
1208ab5d26daSAndreas Gohr * @param string $clear The clear text password
1209ab5d26daSAndreas Gohr * @param string $method The hashing method
1210ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1211b0855b11Sandi * @return  string  The crypted password
1212b0855b11Sandi */
1213577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null) {
1214b0855b11Sandi    global $conf;
1215b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
121610a76f6fSfrank
12173a0a2d05SAndreas Gohr    $pass = new PassHash();
12183a0a2d05SAndreas Gohr    $call = 'hash_'.$method;
1219b0855b11Sandi
12203a0a2d05SAndreas Gohr    if(!method_exists($pass, $call)) {
1221b0855b11Sandi        msg("Unsupported crypt method $method", -1);
12223a0a2d05SAndreas Gohr        return false;
1223b0855b11Sandi    }
12243a0a2d05SAndreas Gohr
12253a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1226b0855b11Sandi}
1227b0855b11Sandi
1228b0855b11Sandi/**
1229b0855b11Sandi * Verifies a cleartext password against a crypted hash
1230b0855b11Sandi *
1231b0855b11Sandi * @author Andreas Gohr <andi@splitbrain.org>
123242ea7f44SGerrit Uitslag *
1233ab5d26daSAndreas Gohr * @param  string $clear The clear text password
1234ab5d26daSAndreas Gohr * @param  string $crypt The hash to compare with
1235ab5d26daSAndreas Gohr * @return bool true if both match
1236b0855b11Sandi */
1237b0855b11Sandifunction auth_verifyPassword($clear, $crypt) {
12383a0a2d05SAndreas Gohr    $pass = new PassHash();
12393a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1240b0855b11Sandi}
1241340756e4Sandi
1242a0b5b007SChris Smith/**
1243a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1244a0b5b007SChris Smith *
1245a0b5b007SChris Smith * @param string  $user       username
1246a0b5b007SChris Smith * @param string  $pass       encrypted password
1247a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1248ab5d26daSAndreas Gohr * @return bool
1249a0b5b007SChris Smith */
1250a0b5b007SChris Smithfunction auth_setCookie($user, $pass, $sticky) {
1251a0b5b007SChris Smith    global $conf;
1252e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1253a0b5b007SChris Smith    global $auth;
125479d00841SOliver Geisen    global $USERINFO;
1255a0b5b007SChris Smith
1256beca106aSAdrian Lang    if(!$auth) return false;
1257a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1258a0b5b007SChris Smith
1259a0b5b007SChris Smith    // set cookie
1260645c0a36SAndreas Gohr    $cookie    = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
126173ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1262c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
126373ab87deSGabriel Birke    setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
126455a71a16SGerrit Uitslag
1265a0b5b007SChris Smith    // set session
1266a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1267234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1268a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1269a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1270a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1271ab5d26daSAndreas Gohr
1272ab5d26daSAndreas Gohr    return true;
1273a0b5b007SChris Smith}
1274a0b5b007SChris Smith
1275645c0a36SAndreas Gohr/**
1276645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1277645c0a36SAndreas Gohr *
1278645c0a36SAndreas Gohr * @returns array
1279645c0a36SAndreas Gohr */
1280645c0a36SAndreas Gohrfunction auth_getCookie() {
1281c66972f2SAdrian Lang    if(!isset($_COOKIE[DOKU_COOKIE])) {
1282c66972f2SAdrian Lang        return array(null, null, null);
1283c66972f2SAdrian Lang    }
1284*ec34bb30SAndreas Gohr    list($user, $sticky, $pass) = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, '');
1285645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1286645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1287645c0a36SAndreas Gohr    $user   = base64_decode($user);
1288645c0a36SAndreas Gohr    return array($user, $sticky, $pass);
1289645c0a36SAndreas Gohr}
1290645c0a36SAndreas Gohr
1291e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1292