xref: /dokuwiki/inc/auth.php (revision a7e2efd2e2d63580fa2ce52c7b64ac636e5be190)
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
59d2dde4ebSMatthias Grimm        unset($auth);
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
248fa7c70ffSAdrian Lang            $session = $_SESSION[DOKU_COOKIE]['auth'];
249132bdbfeSandi            if(isset($session) &&
2507172dbc0SAndreas Gohr                $auth->useSessionCache($user) &&
2514c989037SChris Smith                ($session['time'] >= time() - $conf['auth_security_timeout']) &&
252132bdbfeSandi                ($session['user'] == $user) &&
253234ce57eSAndreas Gohr                ($session['pass'] == sha1($pass)) && //still crypted
254ab5d26daSAndreas Gohr                ($session['buid'] == auth_browseruid())
255ab5d26daSAndreas Gohr            ) {
256234ce57eSAndreas Gohr
257132bdbfeSandi                // he has session, cookie and browser right - let him in
258585bf44eSChristopher Smith                $INPUT->server->set('REMOTE_USER', $user);
259132bdbfeSandi                $USERINFO               = $session['info']; //FIXME move all references to session
260132bdbfeSandi                return true;
261132bdbfeSandi            }
262f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
26330d544a4SMichael Hamann            $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
26404369c3eSMichael Hamann            $pass   = auth_decrypt($pass, $secret);
265f112c2faSAndreas Gohr            return auth_login($user, $pass, $sticky, true);
266132bdbfeSandi        }
267132bdbfeSandi    }
268f3f0262cSandi    //just to be sure
269883179a4SAndreas Gohr    auth_logoff(true);
270132bdbfeSandi    return false;
271f3f0262cSandi}
272132bdbfeSandi
273132bdbfeSandi/**
274136ce040Sandi * Builds a pseudo UID from browser and IP data
275132bdbfeSandi *
276132bdbfeSandi * This is neither unique nor unfakable - still it adds some
277136ce040Sandi * security. Using the first part of the IP makes sure
27880b4f376SAndreas Gohr * proxy farms like AOLs are still okay.
27915fae107Sandi *
28015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
28115fae107Sandi *
28215fae107Sandi * @return  string  a MD5 sum of various browser headers
283132bdbfeSandi */
284132bdbfeSandifunction auth_browseruid() {
285585bf44eSChristopher Smith    /* @var Input $INPUT */
286585bf44eSChristopher Smith    global $INPUT;
287585bf44eSChristopher Smith
2882f9daf16SAndreas Gohr    $ip  = clientIP(true);
289132bdbfeSandi    $uid = '';
290585bf44eSChristopher Smith    $uid .= $INPUT->server->str('HTTP_USER_AGENT');
291585bf44eSChristopher Smith    $uid .= $INPUT->server->str('HTTP_ACCEPT_CHARSET');
2922f9daf16SAndreas Gohr    $uid .= substr($ip, 0, strpos($ip, '.'));
293*a7e2efd2SAndreas Gohr    $uid = \dokuwiki\Utf8\PhpString::strtolower($uid);
294132bdbfeSandi    return md5($uid);
295132bdbfeSandi}
296132bdbfeSandi
297132bdbfeSandi/**
298132bdbfeSandi * Creates a random key to encrypt the password in cookies
29915fae107Sandi *
30015fae107Sandi * This function tries to read the password for encrypting
30198407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
30215fae107Sandi * if no such file is found a random key is created and
30315fae107Sandi * and stored in this file.
30415fae107Sandi *
30515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
30642ea7f44SGerrit Uitslag *
30732ed2b36SAndreas Gohr * @param   bool $addsession if true, the sessionid is added to the salt
30830d544a4SMichael Hamann * @param   bool $secure     if security is more important than keeping the old value
30915fae107Sandi * @return  string
310132bdbfeSandi */
31130d544a4SMichael Hamannfunction auth_cookiesalt($addsession = false, $secure = false) {
312a1fe3c9cSMichael Große    if (defined('SIMPLE_TEST')) {
313fe745becSMichael Große        return 'test';
314a1fe3c9cSMichael Große    }
315132bdbfeSandi    global $conf;
31698407a7aSandi    $file = $conf['metadir'].'/_htcookiesalt';
31730d544a4SMichael Hamann    if ($secure || !file_exists($file)) {
31830d544a4SMichael Hamann        $file = $conf['metadir'].'/_htcookiesalt2';
31930d544a4SMichael Hamann    }
320132bdbfeSandi    $salt = io_readFile($file);
321132bdbfeSandi    if(empty($salt)) {
32230d544a4SMichael Hamann        $salt = bin2hex(auth_randombytes(64));
323132bdbfeSandi        io_saveFile($file, $salt);
324132bdbfeSandi    }
32532ed2b36SAndreas Gohr    if($addsession) {
32632ed2b36SAndreas Gohr        $salt .= session_id();
32732ed2b36SAndreas Gohr    }
328132bdbfeSandi    return $salt;
329f3f0262cSandi}
330f3f0262cSandi
331f3f0262cSandi/**
3327a33d2f8SNiklas Keller * Return cryptographically secure random bytes.
333483b6238SMichael Hamann *
3347a33d2f8SNiklas Keller * @author Niklas Keller <me@kelunik.com>
33542ea7f44SGerrit Uitslag *
3367a33d2f8SNiklas Keller * @param int $length number of bytes
3377a33d2f8SNiklas Keller * @return string cryptographically secure random bytes
338483b6238SMichael Hamann */
339483b6238SMichael Hamannfunction auth_randombytes($length) {
3407a33d2f8SNiklas Keller    return random_bytes($length);
341483b6238SMichael Hamann}
342483b6238SMichael Hamann
343483b6238SMichael Hamann/**
3447a33d2f8SNiklas Keller * Cryptographically secure random number generator.
345483b6238SMichael Hamann *
3467a33d2f8SNiklas Keller * @author Niklas Keller <me@kelunik.com>
34742ea7f44SGerrit Uitslag *
348483b6238SMichael Hamann * @param int $min
349483b6238SMichael Hamann * @param int $max
350483b6238SMichael Hamann * @return int
351483b6238SMichael Hamann */
352483b6238SMichael Hamannfunction auth_random($min, $max) {
3537a33d2f8SNiklas Keller    return random_int($min, $max);
354483b6238SMichael Hamann}
355483b6238SMichael Hamann
356483b6238SMichael Hamann/**
35704369c3eSMichael Hamann * Encrypt data using the given secret using AES
35804369c3eSMichael Hamann *
35904369c3eSMichael Hamann * The mode is CBC with a random initialization vector, the key is derived
36004369c3eSMichael Hamann * using pbkdf2.
36104369c3eSMichael Hamann *
36204369c3eSMichael Hamann * @param string $data   The data that shall be encrypted
36304369c3eSMichael Hamann * @param string $secret The secret/password that shall be used
36404369c3eSMichael Hamann * @return string The ciphertext
36504369c3eSMichael Hamann */
36604369c3eSMichael Hamannfunction auth_encrypt($data, $secret) {
36704369c3eSMichael Hamann    $iv     = auth_randombytes(16);
3681af2f135SAndreas Gohr    $cipher = new \phpseclib\Crypt\AES();
36904369c3eSMichael Hamann    $cipher->setPassword($secret);
37004369c3eSMichael Hamann
3717b650cefSMichael Hamann    /*
3727b650cefSMichael Hamann    this uses the encrypted IV as IV as suggested in
3737b650cefSMichael Hamann    http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
3747b650cefSMichael Hamann    for unique but necessarily random IVs. The resulting ciphertext is
3757b650cefSMichael Hamann    compatible to ciphertext that was created using a "normal" IV.
3767b650cefSMichael Hamann    */
37704369c3eSMichael Hamann    return $cipher->encrypt($iv.$data);
37804369c3eSMichael Hamann}
37904369c3eSMichael Hamann
38004369c3eSMichael Hamann/**
38104369c3eSMichael Hamann * Decrypt the given AES ciphertext
38204369c3eSMichael Hamann *
38304369c3eSMichael Hamann * The mode is CBC, the key is derived using pbkdf2
38404369c3eSMichael Hamann *
38504369c3eSMichael Hamann * @param string $ciphertext The encrypted data
38604369c3eSMichael Hamann * @param string $secret     The secret/password that shall be used
38704369c3eSMichael Hamann * @return string The decrypted data
38804369c3eSMichael Hamann */
38904369c3eSMichael Hamannfunction auth_decrypt($ciphertext, $secret) {
3907b650cefSMichael Hamann    $iv     = substr($ciphertext, 0, 16);
3911af2f135SAndreas Gohr    $cipher = new \phpseclib\Crypt\AES();
39204369c3eSMichael Hamann    $cipher->setPassword($secret);
3937b650cefSMichael Hamann    $cipher->setIV($iv);
39404369c3eSMichael Hamann
3957b650cefSMichael Hamann    return $cipher->decrypt(substr($ciphertext, 16));
39604369c3eSMichael Hamann}
39704369c3eSMichael Hamann
39804369c3eSMichael Hamann/**
399883179a4SAndreas Gohr * Log out the current user
400883179a4SAndreas Gohr *
401f3f0262cSandi * This clears all authentication data and thus log the user
402883179a4SAndreas Gohr * off. It also clears session data.
40315fae107Sandi *
40415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
40542ea7f44SGerrit Uitslag *
406883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
407f3f0262cSandi */
408883179a4SAndreas Gohrfunction auth_logoff($keepbc = false) {
409f3f0262cSandi    global $conf;
410f3f0262cSandi    global $USERINFO;
411e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
4125298a619SAndreas Gohr    global $auth;
413585bf44eSChristopher Smith    /* @var Input $INPUT */
414585bf44eSChristopher Smith    global $INPUT;
41537065e65Sandi
416d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
417e9621d07SAndreas Gohr    @session_start();
418e9621d07SAndreas Gohr
419e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
420e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
421e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
422e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
423e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
424e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
425883179a4SAndreas Gohr    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
426e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
427585bf44eSChristopher Smith    $INPUT->server->remove('REMOTE_USER');
428132bdbfeSandi    $USERINFO = null; //FIXME
429f5c6743cSAndreas Gohr
43073ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
43173ab87deSGabriel Birke    setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
4325298a619SAndreas Gohr
433880f62faSAndreas Gohr    if($auth) $auth->logOff();
434f3f0262cSandi}
435f3f0262cSandi
436f3f0262cSandi/**
437f8cc712eSAndreas Gohr * Check if a user is a manager
438f8cc712eSAndreas Gohr *
439f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
440f8cc712eSAndreas Gohr * user.
441f8cc712eSAndreas Gohr *
442f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
443f8cc712eSAndreas Gohr *
444ab5d26daSAndreas Gohr * @param string $user Username
445ab5d26daSAndreas Gohr * @param array $groups List of groups the user is in
446ab5d26daSAndreas Gohr * @param bool $adminonly when true checks if user is admin
44710396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
448ab5d26daSAndreas Gohr * @return bool
44996348f27SAndreas Gohr * @see    auth_isadmin
45096348f27SAndreas Gohr *
45196348f27SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
452f8cc712eSAndreas Gohr */
45396348f27SAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false, $recache=false) {
454f8cc712eSAndreas Gohr    global $conf;
455f8cc712eSAndreas Gohr    global $USERINFO;
456e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
457d752aedeSAndreas Gohr    global $auth;
458585bf44eSChristopher Smith    /* @var Input $INPUT */
459585bf44eSChristopher Smith    global $INPUT;
460585bf44eSChristopher Smith
461f8cc712eSAndreas Gohr
462beca106aSAdrian Lang    if(!$auth) return false;
463c66972f2SAdrian Lang    if(is_null($user)) {
464585bf44eSChristopher Smith        if(!$INPUT->server->has('REMOTE_USER')) {
465c66972f2SAdrian Lang            return false;
466c66972f2SAdrian Lang        } else {
467585bf44eSChristopher Smith            $user = $INPUT->server->str('REMOTE_USER');
468c66972f2SAdrian Lang        }
469c66972f2SAdrian Lang    }
470d6dc956fSAndreas Gohr    if(is_null($groups)) {
4713e9ae63dSPhy        $groups = $USERINFO ? (array) $USERINFO['grps'] : array();
472e259aa79SAndreas Gohr    }
473e259aa79SAndreas Gohr
47496348f27SAndreas Gohr    // prefer cached result
47596348f27SAndreas Gohr    static $cache = [];
47610396f77SAndreas Gohr    $cachekey = serialize([$user, $adminonly, $groups]);
47796348f27SAndreas Gohr    if (!isset($cache[$cachekey]) || $recache) {
478d6dc956fSAndreas Gohr        // check superuser match
47996348f27SAndreas Gohr        $ok = auth_isMember($conf['superuser'], $user, $groups);
48000ce12daSChris Smith
48196348f27SAndreas Gohr        // check managers
48296348f27SAndreas Gohr        if (!$ok && !$adminonly) {
48396348f27SAndreas Gohr            $ok = auth_isMember($conf['manager'], $user, $groups);
48496348f27SAndreas Gohr        }
48596348f27SAndreas Gohr
48696348f27SAndreas Gohr        $cache[$cachekey] = $ok;
48796348f27SAndreas Gohr    }
48896348f27SAndreas Gohr
48996348f27SAndreas Gohr    return $cache[$cachekey];
490f8cc712eSAndreas Gohr}
491f8cc712eSAndreas Gohr
492f8cc712eSAndreas Gohr/**
493f8cc712eSAndreas Gohr * Check if a user is admin
494f8cc712eSAndreas Gohr *
495f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
496f8cc712eSAndreas Gohr *
497f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
498f8cc712eSAndreas Gohr *
49996348f27SAndreas Gohr * @param string $user Username
50096348f27SAndreas Gohr * @param array $groups List of groups the user is in
50110396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
50296348f27SAndreas Gohr * @return bool
503f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
504ab5d26daSAndreas Gohr * @see auth_ismanager()
50542ea7f44SGerrit Uitslag *
506f8cc712eSAndreas Gohr */
50796348f27SAndreas Gohrfunction auth_isadmin($user = null, $groups = null, $recache=false) {
50896348f27SAndreas Gohr    return auth_ismanager($user, $groups, true, $recache);
509f8cc712eSAndreas Gohr}
510f8cc712eSAndreas Gohr
511d6dc956fSAndreas Gohr/**
512d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
513d6dc956fSAndreas Gohr * users and groups to determine membership status
514d6dc956fSAndreas Gohr *
515d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
516d6dc956fSAndreas Gohr *
51742ea7f44SGerrit Uitslag * @param string $memberlist commaseparated list of allowed users and groups
51842ea7f44SGerrit Uitslag * @param string $user       user to match against
51942ea7f44SGerrit Uitslag * @param array  $groups     groups the user is member of
5205446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
521d6dc956fSAndreas Gohr */
522d6dc956fSAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups) {
523e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
524d6dc956fSAndreas Gohr    global $auth;
525d6dc956fSAndreas Gohr    if(!$auth) return false;
526d6dc956fSAndreas Gohr
527d6dc956fSAndreas Gohr    // clean user and groups
5284f56ecbfSAdrian Lang    if(!$auth->isCaseSensitive()) {
5298cbc5ee8SAndreas Gohr        $user   = \dokuwiki\Utf8\PhpString::strtolower($user);
530*a7e2efd2SAndreas Gohr        $groups = array_map([\dokuwiki\Utf8\PhpString::class, 'strtolower'], $groups);
531d6dc956fSAndreas Gohr    }
532d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
533d6dc956fSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), $groups);
534d6dc956fSAndreas Gohr
535d6dc956fSAndreas Gohr    // extract the memberlist
536d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
537d6dc956fSAndreas Gohr    $members = array_map('trim', $members);
538d6dc956fSAndreas Gohr    $members = array_unique($members);
539d6dc956fSAndreas Gohr    $members = array_filter($members);
540d6dc956fSAndreas Gohr
541d6dc956fSAndreas Gohr    // compare cleaned values
542d6dc956fSAndreas Gohr    foreach($members as $member) {
543e5204a12SJurgen Hart        if($member == '@ALL' ) return true;
5448cbc5ee8SAndreas Gohr        if(!$auth->isCaseSensitive()) $member = \dokuwiki\Utf8\PhpString::strtolower($member);
545d6dc956fSAndreas Gohr        if($member[0] == '@') {
546d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
547d6dc956fSAndreas Gohr            if(in_array($member, $groups)) return true;
548d6dc956fSAndreas Gohr        } else {
549d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
550d6dc956fSAndreas Gohr            if($member == $user) return true;
551d6dc956fSAndreas Gohr        }
552d6dc956fSAndreas Gohr    }
553d6dc956fSAndreas Gohr
554d6dc956fSAndreas Gohr    // still here? not a member!
555d6dc956fSAndreas Gohr    return false;
556d6dc956fSAndreas Gohr}
557d6dc956fSAndreas Gohr
558f8cc712eSAndreas Gohr/**
55915fae107Sandi * Convinience function for auth_aclcheck()
56015fae107Sandi *
56115fae107Sandi * This checks the permissions for the current user
56215fae107Sandi *
56315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
56415fae107Sandi *
5651698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
56615fae107Sandi * @return int          permission level
567f3f0262cSandi */
568f3f0262cSandifunction auth_quickaclcheck($id) {
569f3f0262cSandi    global $conf;
570f3f0262cSandi    global $USERINFO;
571585bf44eSChristopher Smith    /* @var Input $INPUT */
572585bf44eSChristopher Smith    global $INPUT;
573f3f0262cSandi    # if no ACL is used always return upload rights
574f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
5753e9ae63dSPhy    return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : array());
576f3f0262cSandi}
577f3f0262cSandi
578f3f0262cSandi/**
579c17acc9fSAndreas Gohr * Returns the maximum rights a user has for the given ID or its namespace
58015fae107Sandi *
58115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
58242ea7f44SGerrit Uitslag *
583c17acc9fSAndreas Gohr * @triggers AUTH_ACL_CHECK
5841698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
58515fae107Sandi * @param  string       $user   Username
5863272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
58715fae107Sandi * @return int             permission level
588f3f0262cSandi */
589f3f0262cSandifunction auth_aclcheck($id, $user, $groups) {
590c17acc9fSAndreas Gohr    $data = array(
591c17acc9fSAndreas Gohr        'id'     => $id,
592c17acc9fSAndreas Gohr        'user'   => $user,
593c17acc9fSAndreas Gohr        'groups' => $groups
594c17acc9fSAndreas Gohr    );
595c17acc9fSAndreas Gohr
596cbb44eabSAndreas Gohr    return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
597c17acc9fSAndreas Gohr}
598c17acc9fSAndreas Gohr
599c17acc9fSAndreas Gohr/**
600c17acc9fSAndreas Gohr * default ACL check method
601c17acc9fSAndreas Gohr *
602c17acc9fSAndreas Gohr * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
603c17acc9fSAndreas Gohr *
604c17acc9fSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
60542ea7f44SGerrit Uitslag *
606c17acc9fSAndreas Gohr * @param  array $data event data
607c17acc9fSAndreas Gohr * @return int   permission level
608c17acc9fSAndreas Gohr */
609c17acc9fSAndreas Gohrfunction auth_aclcheck_cb($data) {
610c17acc9fSAndreas Gohr    $id     =& $data['id'];
611c17acc9fSAndreas Gohr    $user   =& $data['user'];
612c17acc9fSAndreas Gohr    $groups =& $data['groups'];
613c17acc9fSAndreas Gohr
614f3f0262cSandi    global $conf;
615f3f0262cSandi    global $AUTH_ACL;
616e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
617d752aedeSAndreas Gohr    global $auth;
618f3f0262cSandi
61985d03f68SAndreas Gohr    // if no ACL is used always return upload rights
620f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
621beca106aSAdrian Lang    if(!$auth) return AUTH_NONE;
622f3f0262cSandi
623074cf26bSandi    //make sure groups is an array
624074cf26bSandi    if(!is_array($groups)) $groups = array();
625074cf26bSandi
62685d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
627ab5d26daSAndreas Gohr    if(auth_isadmin($user, $groups)) {
628ab5d26daSAndreas Gohr        return AUTH_ADMIN;
629ab5d26daSAndreas Gohr    }
63085d03f68SAndreas Gohr
631eb3ce0d5SKazutaka Miyasaka    if(!$auth->isCaseSensitive()) {
6328cbc5ee8SAndreas Gohr        $user   = \dokuwiki\Utf8\PhpString::strtolower($user);
633eb3ce0d5SKazutaka Miyasaka        $groups = array_map('utf8_strtolower', $groups);
634eb3ce0d5SKazutaka Miyasaka    }
63537ff2261SSascha Klopp    $user   = auth_nameencode($auth->cleanUser($user));
636d752aedeSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
63785d03f68SAndreas Gohr
6386c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
63937ff2261SSascha Klopp    foreach($groups as &$group) {
64037ff2261SSascha Klopp        $group = '@'.auth_nameencode($group);
64110a76f6fSfrank    }
64210a76f6fSfrank
643f3f0262cSandi    $ns   = getNS($id);
644f3f0262cSandi    $perm = -1;
645f3f0262cSandi
646f3f0262cSandi    //add ALL group
647f3f0262cSandi    $groups[] = '@ALL';
64837ff2261SSascha Klopp
649f3f0262cSandi    //add User
65034aeb4afSAndreas Gohr    if($user) $groups[] = $user;
651f3f0262cSandi
652f3f0262cSandi    //check exact match first
65321c3090aSChristopher Smith    $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
654f3f0262cSandi    if(count($matches)) {
655f3f0262cSandi        foreach($matches as $match) {
656f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
65721c3090aSChristopher Smith            $acl   = preg_split('/[ \t]+/', $match);
658eb3ce0d5SKazutaka Miyasaka            if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
6598cbc5ee8SAndreas Gohr                $acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]);
660eb3ce0d5SKazutaka Miyasaka            }
66148d7b7a6SDominik Eckelmann            if(!in_array($acl[1], $groups)) {
66248d7b7a6SDominik Eckelmann                continue;
66348d7b7a6SDominik Eckelmann            }
6648ef6b7caSandi            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
665f3f0262cSandi            if($acl[2] > $perm) {
666f3f0262cSandi                $perm = $acl[2];
667f3f0262cSandi            }
668f3f0262cSandi        }
669f3f0262cSandi        if($perm > -1) {
670f3f0262cSandi            //we had a match - return it
671def492a2SGuillaume Turri            return (int) $perm;
672f3f0262cSandi        }
673f3f0262cSandi    }
674f3f0262cSandi
675f3f0262cSandi    //still here? do the namespace checks
676f3f0262cSandi    if($ns) {
6773e304b55SMichael Hamann        $path = $ns.':*';
678f3f0262cSandi    } else {
6793e304b55SMichael Hamann        $path = '*'; //root document
680f3f0262cSandi    }
681f3f0262cSandi
682f3f0262cSandi    do {
68321c3090aSChristopher Smith        $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
684f3f0262cSandi        if(count($matches)) {
685f3f0262cSandi            foreach($matches as $match) {
686f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
68721c3090aSChristopher Smith                $acl   = preg_split('/[ \t]+/', $match);
688eb3ce0d5SKazutaka Miyasaka                if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
6898cbc5ee8SAndreas Gohr                    $acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]);
690eb3ce0d5SKazutaka Miyasaka                }
69148d7b7a6SDominik Eckelmann                if(!in_array($acl[1], $groups)) {
69248d7b7a6SDominik Eckelmann                    continue;
69348d7b7a6SDominik Eckelmann                }
6948ef6b7caSandi                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
695f3f0262cSandi                if($acl[2] > $perm) {
696f3f0262cSandi                    $perm = $acl[2];
697f3f0262cSandi                }
698f3f0262cSandi            }
699f3f0262cSandi            //we had a match - return it
70048d7b7a6SDominik Eckelmann            if($perm != -1) {
701def492a2SGuillaume Turri                return (int) $perm;
702f3f0262cSandi            }
70348d7b7a6SDominik Eckelmann        }
704f3f0262cSandi        //get next higher namespace
705f3f0262cSandi        $ns = getNS($ns);
706f3f0262cSandi
7073e304b55SMichael Hamann        if($path != '*') {
7083e304b55SMichael Hamann            $path = $ns.':*';
7093e304b55SMichael Hamann            if($path == ':*') $path = '*';
710f3f0262cSandi        } else {
711f3f0262cSandi            //we did this already
712f3f0262cSandi            //looks like there is something wrong with the ACL
713f3f0262cSandi            //break here
714d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
715d5ce66f6SAndreas Gohr            return AUTH_NONE;
716f3f0262cSandi        }
717f3f0262cSandi    } while(1); //this should never loop endless
718ab5d26daSAndreas Gohr    return AUTH_NONE;
719f3f0262cSandi}
720f3f0262cSandi
721f3f0262cSandi/**
7226c2bb100SAndreas Gohr * Encode ASCII special chars
7236c2bb100SAndreas Gohr *
7246c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
7256c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
7266c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
7276c2bb100SAndreas Gohr * urlencoding!).
7286c2bb100SAndreas Gohr *
7296c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
7306c2bb100SAndreas Gohr *
7316c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
7326c2bb100SAndreas Gohr * @see rawurldecode()
73342ea7f44SGerrit Uitslag *
73442ea7f44SGerrit Uitslag * @param string $name
73542ea7f44SGerrit Uitslag * @param bool $skip_group
73642ea7f44SGerrit Uitslag * @return string
7376c2bb100SAndreas Gohr */
738e838fc2eSAndreas Gohrfunction auth_nameencode($name, $skip_group = false) {
739a424cd8eSchris    global $cache_authname;
740a424cd8eSchris    $cache =& $cache_authname;
74131784267SAndreas Gohr    $name  = (string) $name;
742a424cd8eSchris
74380601d26SAndreas Gohr    // never encode wildcard FS#1955
74480601d26SAndreas Gohr    if($name == '%USER%') return $name;
745b78bf706Sromain    if($name == '%GROUP%') return $name;
74680601d26SAndreas Gohr
747a424cd8eSchris    if(!isset($cache[$name][$skip_group])) {
7482401f18dSSyntaxseed        if($skip_group && $name[0] == '@') {
74930f6faf0SChristopher Smith            $cache[$name][$skip_group] = '@'.preg_replace_callback(
75030f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
75130f6faf0SChristopher Smith                'auth_nameencode_callback', substr($name, 1)
752ab5d26daSAndreas Gohr            );
753e838fc2eSAndreas Gohr        } else {
75430f6faf0SChristopher Smith            $cache[$name][$skip_group] = preg_replace_callback(
75530f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
75630f6faf0SChristopher Smith                'auth_nameencode_callback', $name
757ab5d26daSAndreas Gohr            );
758e838fc2eSAndreas Gohr        }
7596c2bb100SAndreas Gohr    }
7606c2bb100SAndreas Gohr
761a424cd8eSchris    return $cache[$name][$skip_group];
762a424cd8eSchris}
763a424cd8eSchris
76404d68ae4SGerrit Uitslag/**
76504d68ae4SGerrit Uitslag * callback encodes the matches
76604d68ae4SGerrit Uitslag *
76704d68ae4SGerrit Uitslag * @param array $matches first complete match, next matching subpatterms
76804d68ae4SGerrit Uitslag * @return string
76904d68ae4SGerrit Uitslag */
77030f6faf0SChristopher Smithfunction auth_nameencode_callback($matches) {
77130f6faf0SChristopher Smith    return '%'.dechex(ord(substr($matches[1],-1)));
77230f6faf0SChristopher Smith}
77330f6faf0SChristopher Smith
7746c2bb100SAndreas Gohr/**
775f3f0262cSandi * Create a pronouncable password
776f3f0262cSandi *
7778a285f7fSAndreas Gohr * The $foruser variable might be used by plugins to run additional password
7788a285f7fSAndreas Gohr * policy checks, but is not used by the default implementation
7798a285f7fSAndreas Gohr *
78015fae107Sandi * @author   Andreas Gohr <andi@splitbrain.org>
78115fae107Sandi * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
7828a285f7fSAndreas Gohr * @triggers AUTH_PASSWORD_GENERATE
78315fae107Sandi *
7848a285f7fSAndreas Gohr * @param  string $foruser username for which the password is generated
78515fae107Sandi * @return string  pronouncable password
786f3f0262cSandi */
7878a285f7fSAndreas Gohrfunction auth_pwgen($foruser = '') {
7888a285f7fSAndreas Gohr    $data = array(
789d628dcf3SAndreas Gohr        'password' => '',
790d628dcf3SAndreas Gohr        'foruser'  => $foruser
7918a285f7fSAndreas Gohr    );
7928a285f7fSAndreas Gohr
793e1d9dcc8SAndreas Gohr    $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
7948a285f7fSAndreas Gohr    if($evt->advise_before(true)) {
795f3f0262cSandi        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
796f3f0262cSandi        $v = 'aeiou'; //vowels
797f3f0262cSandi        $a = $c.$v; //both
798987c8d26SAndreas Gohr        $s = '!$%&?+*~#-_:.;,'; // specials
799f3f0262cSandi
800987c8d26SAndreas Gohr        //use thre syllables...
801987c8d26SAndreas Gohr        for($i = 0; $i < 3; $i++) {
802483b6238SMichael Hamann            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
803483b6238SMichael Hamann            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
804483b6238SMichael Hamann            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
805f3f0262cSandi        }
806987c8d26SAndreas Gohr        //... and add a nice number and special
80743f71e05Ssdavis80        $data['password'] .= $s[auth_random(0, strlen($s) - 1)].auth_random(10, 99);
8088a285f7fSAndreas Gohr    }
8098a285f7fSAndreas Gohr    $evt->advise_after();
810f3f0262cSandi
8118a285f7fSAndreas Gohr    return $data['password'];
812f3f0262cSandi}
813f3f0262cSandi
814f3f0262cSandi/**
815f3f0262cSandi * Sends a password to the given user
816f3f0262cSandi *
81715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
81842ea7f44SGerrit Uitslag *
819ab5d26daSAndreas Gohr * @param string $user Login name of the user
820ab5d26daSAndreas Gohr * @param string $password The new password in clear text
82115fae107Sandi * @return bool  true on success
822f3f0262cSandi */
823f3f0262cSandifunction auth_sendPassword($user, $password) {
824f3f0262cSandi    global $lang;
825e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
826cd52f92dSchris    global $auth;
827beca106aSAdrian Lang    if(!$auth) return false;
828cd52f92dSchris
829d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
8302dc9e900SChristopher Smith    $userinfo = $auth->getUserData($user, $requireGroups = false);
831f3f0262cSandi
83287ddda95Sandi    if(!$userinfo['mail']) return false;
833f3f0262cSandi
834f3f0262cSandi    $text = rawLocale('password');
835d7169d19SAndreas Gohr    $trep = array(
836d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
837d7169d19SAndreas Gohr        'LOGIN'    => $user,
838d7169d19SAndreas Gohr        'PASSWORD' => $password
839d7169d19SAndreas Gohr    );
840f3f0262cSandi
841d7169d19SAndreas Gohr    $mail = new Mailer();
842102cdbd7SLarsGit223    $mail->to($mail->getCleanName($userinfo['name']).' <'.$userinfo['mail'].'>');
843d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
844d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
845d7169d19SAndreas Gohr    return $mail->send();
846f3f0262cSandi}
847f3f0262cSandi
848f3f0262cSandi/**
84915fae107Sandi * Register a new user
850f3f0262cSandi *
85115fae107Sandi * This registers a new user - Data is read directly from $_POST
85215fae107Sandi *
85315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
85442ea7f44SGerrit Uitslag *
85515fae107Sandi * @return bool  true on success, false on any error
856f3f0262cSandi */
857f3f0262cSandifunction register() {
858f3f0262cSandi    global $lang;
859eb5d07e4Sjan    global $conf;
860e1d9dcc8SAndreas Gohr    /* @var \dokuwiki\Extension\AuthPlugin $auth */
861cd52f92dSchris    global $auth;
86264273335SAndreas Gohr    global $INPUT;
863f3f0262cSandi
86464273335SAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
8653a48618aSAnika Henke    if(!actionOK('register')) return false;
866640145a5Sandi
86764273335SAndreas Gohr    // gather input
86864273335SAndreas Gohr    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
86964273335SAndreas Gohr    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
87064273335SAndreas Gohr    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
87164273335SAndreas Gohr    $pass     = $INPUT->post->str('pass');
87264273335SAndreas Gohr    $passchk  = $INPUT->post->str('passchk');
873d752aedeSAndreas Gohr
87464273335SAndreas Gohr    if(empty($login) || empty($fullname) || empty($email)) {
875f3f0262cSandi        msg($lang['regmissing'], -1);
876f3f0262cSandi        return false;
877f3f0262cSandi    }
878f3f0262cSandi
879cab2716aSmatthias.grimm    if($conf['autopasswd']) {
8808a285f7fSAndreas Gohr        $pass = auth_pwgen($login); // automatically generate password
88164273335SAndreas Gohr    } elseif(empty($pass) || empty($passchk)) {
882bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
883cab2716aSmatthias.grimm        return false;
88464273335SAndreas Gohr    } elseif($pass != $passchk) {
885bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
886cab2716aSmatthias.grimm        return false;
887cab2716aSmatthias.grimm    }
888cab2716aSmatthias.grimm
889f3f0262cSandi    //check mail
89064273335SAndreas Gohr    if(!mail_isvalid($email)) {
891f3f0262cSandi        msg($lang['regbadmail'], -1);
892f3f0262cSandi        return false;
893f3f0262cSandi    }
894f3f0262cSandi
895f3f0262cSandi    //okay try to create the user
89664273335SAndreas Gohr    if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) {
897db9faf02SPatrick Brown        msg($lang['regfail'], -1);
898f3f0262cSandi        return false;
899f3f0262cSandi    }
900f3f0262cSandi
901790b7720SAndreas Gohr    // send notification about the new user
90275d66495SMichael Große    $subscription = new RegistrationSubscriptionSender();
90375d66495SMichael Große    $subscription->sendRegister($login, $fullname, $email);
90402a498e7Schris
905790b7720SAndreas Gohr    // are we done?
906cab2716aSmatthias.grimm    if(!$conf['autopasswd']) {
907cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
908cab2716aSmatthias.grimm        return true;
909cab2716aSmatthias.grimm    }
910cab2716aSmatthias.grimm
911790b7720SAndreas Gohr    // autogenerated password? then send password to user
91264273335SAndreas Gohr    if(auth_sendPassword($login, $pass)) {
913f3f0262cSandi        msg($lang['regsuccess'], 1);
914f3f0262cSandi        return true;
915f3f0262cSandi    } else {
916f3f0262cSandi        msg($lang['regmailfail'], -1);
917f3f0262cSandi        return false;
918f3f0262cSandi    }
919f3f0262cSandi}
920f3f0262cSandi
92110a76f6fSfrank/**
9228b06d178Schris * Update user profile
9238b06d178Schris *
9248b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
9258b06d178Schris */
9268b06d178Schrisfunction updateprofile() {
9278b06d178Schris    global $conf;
9288b06d178Schris    global $lang;
929e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
930cd52f92dSchris    global $auth;
931bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
932bcc94b2cSAndreas Gohr    global $INPUT;
9338b06d178Schris
934bcc94b2cSAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
9351b2a85e8SAndreas Gohr    if(!checkSecurityToken()) return false;
9368b06d178Schris
9373a48618aSAnika Henke    if(!actionOK('profile')) {
9388b06d178Schris        msg($lang['profna'], -1);
9398b06d178Schris        return false;
9408b06d178Schris    }
9418b06d178Schris
942bcc94b2cSAndreas Gohr    $changes         = array();
943bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
944bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
945bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
946bcc94b2cSAndreas Gohr
947bcc94b2cSAndreas Gohr    // check misspelled passwords
948bcc94b2cSAndreas Gohr    if($changes['pass'] != $INPUT->post->str('passchk')) {
949bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
9508b06d178Schris        return false;
9518b06d178Schris    }
9528b06d178Schris
9538b06d178Schris    // clean fullname and email
954bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
955bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
9568b06d178Schris
957bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
958bcc94b2cSAndreas Gohr    if((empty($changes['name']) && $auth->canDo('modName')) ||
959bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
960ab5d26daSAndreas Gohr    ) {
9618b06d178Schris        msg($lang['profnoempty'], -1);
9628b06d178Schris        return false;
9638b06d178Schris    }
964bcc94b2cSAndreas Gohr    if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
9658b06d178Schris        msg($lang['regbadmail'], -1);
9668b06d178Schris        return false;
9678b06d178Schris    }
9688b06d178Schris
969bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
9704c21b7eeSAndreas Gohr
971bcc94b2cSAndreas Gohr    // check for unavailable capabilities
972bcc94b2cSAndreas Gohr    if(!$auth->canDo('modName')) unset($changes['name']);
973bcc94b2cSAndreas Gohr    if(!$auth->canDo('modMail')) unset($changes['mail']);
974bcc94b2cSAndreas Gohr    if(!$auth->canDo('modPass')) unset($changes['pass']);
975bcc94b2cSAndreas Gohr
976bcc94b2cSAndreas Gohr    // anything to do?
9778b06d178Schris    if(!count($changes)) {
9788b06d178Schris        msg($lang['profnochange'], -1);
9798b06d178Schris        return false;
9808b06d178Schris    }
9818b06d178Schris
9828b06d178Schris    if($conf['profileconfirm']) {
983585bf44eSChristopher Smith        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
98471422fc8SChristopher Smith            msg($lang['badpassconfirm'], -1);
9858b06d178Schris            return false;
9868b06d178Schris        }
9878b06d178Schris    }
9888b06d178Schris
989e6c4392fSPatrick Brown    if(!$auth->triggerUserMod('modify', array($INPUT->server->str('REMOTE_USER'), &$changes))) {
990db9faf02SPatrick Brown        msg($lang['proffail'], -1);
991db9faf02SPatrick Brown        return false;
992db9faf02SPatrick Brown    }
993db9faf02SPatrick Brown
99432ed2b36SAndreas Gohr    if($changes['pass']) {
995c276e9e8SMarcel Pennewiss        // update cookie and session with the changed data
996ab5d26daSAndreas Gohr        list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
99704369c3eSMichael Hamann        $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
998585bf44eSChristopher Smith        auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
999c276e9e8SMarcel Pennewiss    } else {
1000c276e9e8SMarcel Pennewiss        // make sure the session is writable
1001c276e9e8SMarcel Pennewiss        @session_start();
1002c276e9e8SMarcel Pennewiss        // invalidate session cache
1003c276e9e8SMarcel Pennewiss        $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
1004c276e9e8SMarcel Pennewiss        session_write_close();
100532ed2b36SAndreas Gohr    }
1006c276e9e8SMarcel Pennewiss
100725b2a98cSMichael Klier    return true;
1008a0b5b007SChris Smith}
1009ab5d26daSAndreas Gohr
101004d68ae4SGerrit Uitslag/**
101104d68ae4SGerrit Uitslag * Delete the current logged-in user
101204d68ae4SGerrit Uitslag *
101304d68ae4SGerrit Uitslag * @return bool true on success, false on any error
101404d68ae4SGerrit Uitslag */
10152a7abf2dSChristopher Smithfunction auth_deleteprofile(){
10162a7abf2dSChristopher Smith    global $conf;
10172a7abf2dSChristopher Smith    global $lang;
1018e1d9dcc8SAndreas Gohr    /* @var \dokuwiki\Extension\AuthPlugin $auth */
10192a7abf2dSChristopher Smith    global $auth;
10202a7abf2dSChristopher Smith    /* @var Input $INPUT */
10212a7abf2dSChristopher Smith    global $INPUT;
10222a7abf2dSChristopher Smith
10232a7abf2dSChristopher Smith    if(!$INPUT->post->bool('delete')) return false;
10242a7abf2dSChristopher Smith    if(!checkSecurityToken()) return false;
10252a7abf2dSChristopher Smith
10262a7abf2dSChristopher Smith    // action prevented or auth module disallows
10272a7abf2dSChristopher Smith    if(!actionOK('profile_delete') || !$auth->canDo('delUser')) {
10282a7abf2dSChristopher Smith        msg($lang['profnodelete'], -1);
10292a7abf2dSChristopher Smith        return false;
10302a7abf2dSChristopher Smith    }
10312a7abf2dSChristopher Smith
10322a7abf2dSChristopher Smith    if(!$INPUT->post->bool('confirm_delete')){
10332a7abf2dSChristopher Smith        msg($lang['profconfdeletemissing'], -1);
10342a7abf2dSChristopher Smith        return false;
10352a7abf2dSChristopher Smith    }
10362a7abf2dSChristopher Smith
10372a7abf2dSChristopher Smith    if($conf['profileconfirm']) {
1038585bf44eSChristopher Smith        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
10392a7abf2dSChristopher Smith            msg($lang['badpassconfirm'], -1);
10402a7abf2dSChristopher Smith            return false;
10412a7abf2dSChristopher Smith        }
10422a7abf2dSChristopher Smith    }
10432a7abf2dSChristopher Smith
104459bc3b48SGerrit Uitslag    $deleted = array();
1045585bf44eSChristopher Smith    $deleted[] = $INPUT->server->str('REMOTE_USER');
104673012efdSChristopher Smith    if($auth->triggerUserMod('delete', array($deleted))) {
10472a7abf2dSChristopher Smith        // force and immediate logout including removing the sticky cookie
10482a7abf2dSChristopher Smith        auth_logoff();
10492a7abf2dSChristopher Smith        return true;
10502a7abf2dSChristopher Smith    }
10512a7abf2dSChristopher Smith
10522a7abf2dSChristopher Smith    return false;
10532a7abf2dSChristopher Smith}
10542a7abf2dSChristopher Smith
10558b06d178Schris/**
10568b06d178Schris * Send a  new password
10578b06d178Schris *
10581d5856cfSAndreas Gohr * This function handles both phases of the password reset:
10591d5856cfSAndreas Gohr *
10601d5856cfSAndreas Gohr *   - handling the first request of password reset
10611d5856cfSAndreas Gohr *   - validating the password reset auth token
10621d5856cfSAndreas Gohr *
10638b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
10648b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
10651d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10668b06d178Schris *
10678b06d178Schris * @return bool true on success, false on any error
10688b06d178Schris */
10698b06d178Schrisfunction act_resendpwd() {
10708b06d178Schris    global $lang;
10718b06d178Schris    global $conf;
1072e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1073cd52f92dSchris    global $auth;
1074bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1075bcc94b2cSAndreas Gohr    global $INPUT;
10768b06d178Schris
10773a48618aSAnika Henke    if(!actionOK('resendpwd')) {
10788b06d178Schris        msg($lang['resendna'], -1);
10798b06d178Schris        return false;
10808b06d178Schris    }
10818b06d178Schris
1082bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
10838b06d178Schris
10841d5856cfSAndreas Gohr    if($token) {
1085cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
10861d5856cfSAndreas Gohr
10872401f18dSSyntaxseed        $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
108879e79377SAndreas Gohr        if(!file_exists($tfile)) {
10891d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1090bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
10911d5856cfSAndreas Gohr            return false;
10921d5856cfSAndreas Gohr        }
10938a9735e3SAndreas Gohr        // token is only valid for 3 days
10948a9735e3SAndreas Gohr        if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
10958a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1096bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
10971d5856cfSAndreas Gohr            @unlink($tfile);
10988a9735e3SAndreas Gohr            return false;
10998a9735e3SAndreas Gohr        }
11008a9735e3SAndreas Gohr
11018b06d178Schris        $user     = io_readfile($tfile);
11022dc9e900SChristopher Smith        $userinfo = $auth->getUserData($user, $requireGroups = false);
11038b06d178Schris        if(!$userinfo['mail']) {
11048b06d178Schris            msg($lang['resendpwdnouser'], -1);
11058b06d178Schris            return false;
11068b06d178Schris        }
11078b06d178Schris
1108cc204bbdSAndreas Gohr        if(!$conf['autopasswd']) { // we let the user choose a password
1109bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
1110bcc94b2cSAndreas Gohr
1111cc204bbdSAndreas Gohr            // password given correctly?
1112bcc94b2cSAndreas Gohr            if(!$pass) return false;
1113bcc94b2cSAndreas Gohr            if($pass != $INPUT->str('passchk')) {
1114451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
1115cc204bbdSAndreas Gohr                return false;
1116cc204bbdSAndreas Gohr            }
1117cc204bbdSAndreas Gohr
1118bcc94b2cSAndreas Gohr            // change it
1119cc204bbdSAndreas Gohr            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1120db9faf02SPatrick Brown                msg($lang['proffail'], -1);
1121cc204bbdSAndreas Gohr                return false;
1122cc204bbdSAndreas Gohr            }
1123cc204bbdSAndreas Gohr
1124cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
1125cc204bbdSAndreas Gohr
11268a285f7fSAndreas Gohr            $pass = auth_pwgen($user);
11277d3c8d42SGabriel Birke            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1128db9faf02SPatrick Brown                msg($lang['proffail'], -1);
11298b06d178Schris                return false;
11308b06d178Schris            }
11318b06d178Schris
11328b06d178Schris            if(auth_sendPassword($user, $pass)) {
11338b06d178Schris                msg($lang['resendpwdsuccess'], 1);
11348b06d178Schris            } else {
11358b06d178Schris                msg($lang['regmailfail'], -1);
11368b06d178Schris            }
1137cc204bbdSAndreas Gohr        }
1138cc204bbdSAndreas Gohr
1139cc204bbdSAndreas Gohr        @unlink($tfile);
11408b06d178Schris        return true;
11411d5856cfSAndreas Gohr
11421d5856cfSAndreas Gohr    } else {
11431d5856cfSAndreas Gohr        // we're in request phase
11441d5856cfSAndreas Gohr
1145bcc94b2cSAndreas Gohr        if(!$INPUT->post->bool('save')) return false;
11461d5856cfSAndreas Gohr
1147bcc94b2cSAndreas Gohr        if(!$INPUT->post->str('login')) {
11481d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
11491d5856cfSAndreas Gohr            return false;
11501d5856cfSAndreas Gohr        } else {
1151bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
11521d5856cfSAndreas Gohr        }
11531d5856cfSAndreas Gohr
11542dc9e900SChristopher Smith        $userinfo = $auth->getUserData($user, $requireGroups = false);
11551d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
11561d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
11571d5856cfSAndreas Gohr            return false;
11581d5856cfSAndreas Gohr        }
11591d5856cfSAndreas Gohr
11601d5856cfSAndreas Gohr        // generate auth token
1161483b6238SMichael Hamann        $token = md5(auth_randombytes(16)); // random secret
11622401f18dSSyntaxseed        $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
11631d5856cfSAndreas Gohr        $url   = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
11641d5856cfSAndreas Gohr
11651d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
11661d5856cfSAndreas Gohr
11671d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
1168d7169d19SAndreas Gohr        $trep = array(
1169d7169d19SAndreas Gohr            'FULLNAME' => $userinfo['name'],
1170d7169d19SAndreas Gohr            'LOGIN'    => $user,
1171d7169d19SAndreas Gohr            'CONFIRM'  => $url
1172d7169d19SAndreas Gohr        );
11731d5856cfSAndreas Gohr
1174d7169d19SAndreas Gohr        $mail = new Mailer();
1175d7169d19SAndreas Gohr        $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1176d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
1177d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
1178d7169d19SAndreas Gohr        if($mail->send()) {
11791d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
11801d5856cfSAndreas Gohr        } else {
11811d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
11821d5856cfSAndreas Gohr        }
11831d5856cfSAndreas Gohr        return true;
11841d5856cfSAndreas Gohr    }
1185ab5d26daSAndreas Gohr    // never reached
11868b06d178Schris}
11878b06d178Schris
11888b06d178Schris/**
1189b0855b11Sandi * Encrypts a password using the given method and salt
1190b0855b11Sandi *
1191b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1192b0855b11Sandi * is chosen.
1193b0855b11Sandi *
1194b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
119542ea7f44SGerrit Uitslag *
1196ab5d26daSAndreas Gohr * @param string $clear The clear text password
1197ab5d26daSAndreas Gohr * @param string $method The hashing method
1198ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1199b0855b11Sandi * @return  string  The crypted password
1200b0855b11Sandi */
1201577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null) {
1202b0855b11Sandi    global $conf;
1203b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
120410a76f6fSfrank
12053a0a2d05SAndreas Gohr    $pass = new PassHash();
12063a0a2d05SAndreas Gohr    $call = 'hash_'.$method;
1207b0855b11Sandi
12083a0a2d05SAndreas Gohr    if(!method_exists($pass, $call)) {
1209b0855b11Sandi        msg("Unsupported crypt method $method", -1);
12103a0a2d05SAndreas Gohr        return false;
1211b0855b11Sandi    }
12123a0a2d05SAndreas Gohr
12133a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1214b0855b11Sandi}
1215b0855b11Sandi
1216b0855b11Sandi/**
1217b0855b11Sandi * Verifies a cleartext password against a crypted hash
1218b0855b11Sandi *
1219b0855b11Sandi * @author Andreas Gohr <andi@splitbrain.org>
122042ea7f44SGerrit Uitslag *
1221ab5d26daSAndreas Gohr * @param  string $clear The clear text password
1222ab5d26daSAndreas Gohr * @param  string $crypt The hash to compare with
1223ab5d26daSAndreas Gohr * @return bool true if both match
1224b0855b11Sandi */
1225b0855b11Sandifunction auth_verifyPassword($clear, $crypt) {
12263a0a2d05SAndreas Gohr    $pass = new PassHash();
12273a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1228b0855b11Sandi}
1229340756e4Sandi
1230a0b5b007SChris Smith/**
1231a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1232a0b5b007SChris Smith *
1233a0b5b007SChris Smith * @param string  $user       username
1234a0b5b007SChris Smith * @param string  $pass       encrypted password
1235a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1236ab5d26daSAndreas Gohr * @return bool
1237a0b5b007SChris Smith */
1238a0b5b007SChris Smithfunction auth_setCookie($user, $pass, $sticky) {
1239a0b5b007SChris Smith    global $conf;
1240e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1241a0b5b007SChris Smith    global $auth;
124279d00841SOliver Geisen    global $USERINFO;
1243a0b5b007SChris Smith
1244beca106aSAdrian Lang    if(!$auth) return false;
1245a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1246a0b5b007SChris Smith
1247a0b5b007SChris Smith    // set cookie
1248645c0a36SAndreas Gohr    $cookie    = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
124973ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1250c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
125173ab87deSGabriel Birke    setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
125255a71a16SGerrit Uitslag
1253a0b5b007SChris Smith    // set session
1254a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1255234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1256a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1257a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1258a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1259ab5d26daSAndreas Gohr
1260ab5d26daSAndreas Gohr    return true;
1261a0b5b007SChris Smith}
1262a0b5b007SChris Smith
1263645c0a36SAndreas Gohr/**
1264645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1265645c0a36SAndreas Gohr *
1266645c0a36SAndreas Gohr * @returns array
1267645c0a36SAndreas Gohr */
1268645c0a36SAndreas Gohrfunction auth_getCookie() {
1269c66972f2SAdrian Lang    if(!isset($_COOKIE[DOKU_COOKIE])) {
1270c66972f2SAdrian Lang        return array(null, null, null);
1271c66972f2SAdrian Lang    }
1272645c0a36SAndreas Gohr    list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
1273645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1274645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1275645c0a36SAndreas Gohr    $user   = base64_decode($user);
1276645c0a36SAndreas Gohr    return array($user, $sticky, $pass);
1277645c0a36SAndreas Gohr}
1278645c0a36SAndreas Gohr
1279e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1280