xref: /dokuwiki/inc/auth.php (revision 3e9ae63d53254e2111f41edfd84e8122f8ac8fcc)
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
12ebf97c8fSAndreas Gohr// some ACL level defines
13c3cc6e05SAndreas Gohruse dokuwiki\PassHash;
1475d66495SMichael Großeuse dokuwiki\Subscriptions\RegistrationSubscriptionSender;
15e1d9dcc8SAndreas Gohruse dokuwiki\Extension\AuthPlugin;
163a7140a1SAndreas Gohruse dokuwiki\Extension\PluginController;
17e1d9dcc8SAndreas Gohruse dokuwiki\Extension\Event;
18c3cc6e05SAndreas Gohr
19ebf97c8fSAndreas Gohrdefine('AUTH_NONE', 0);
20ebf97c8fSAndreas Gohrdefine('AUTH_READ', 1);
21ebf97c8fSAndreas Gohrdefine('AUTH_EDIT', 2);
22ebf97c8fSAndreas Gohrdefine('AUTH_CREATE', 4);
23ebf97c8fSAndreas Gohrdefine('AUTH_UPLOAD', 8);
24ebf97c8fSAndreas Gohrdefine('AUTH_DELETE', 16);
25ebf97c8fSAndreas Gohrdefine('AUTH_ADMIN', 255);
26ebf97c8fSAndreas Gohr
2716905344SAndreas Gohr/**
2816905344SAndreas Gohr * Initialize the auth system.
2916905344SAndreas Gohr *
3016905344SAndreas Gohr * This function is automatically called at the end of init.php
3116905344SAndreas Gohr *
3216905344SAndreas Gohr * This used to be the main() of the auth.php
3316905344SAndreas Gohr *
3416905344SAndreas Gohr * @todo backend loading maybe should be handled by the class autoloader
3516905344SAndreas Gohr * @todo maybe split into multiple functions at the XXX marked positions
36ab5d26daSAndreas Gohr * @triggers AUTH_LOGIN_CHECK
37ab5d26daSAndreas Gohr * @return bool
3816905344SAndreas Gohr */
3916905344SAndreas Gohrfunction auth_setup() {
40742c66f8Schris    global $conf;
41e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
4203c4aec3Schris    global $auth;
43bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
44bcc94b2cSAndreas Gohr    global $INPUT;
459a9714acSDominik Eckelmann    global $AUTH_ACL;
469a9714acSDominik Eckelmann    global $lang;
473a7140a1SAndreas Gohr    /* @var PluginController $plugin_controller */
489c29eea5SJan Schumann    global $plugin_controller;
499a9714acSDominik Eckelmann    $AUTH_ACL = array();
5003c4aec3Schris
5116905344SAndreas Gohr    if(!$conf['useacl']) return false;
5216905344SAndreas Gohr
539c29eea5SJan Schumann    // try to load auth backend from plugins
549c29eea5SJan Schumann    foreach ($plugin_controller->getList('auth') as $plugin) {
559c29eea5SJan Schumann        if ($conf['authtype'] === $plugin) {
56f4476bd9SJan Schumann            $auth = $plugin_controller->load('auth', $plugin);
579c29eea5SJan Schumann            break;
589c29eea5SJan Schumann        }
599c29eea5SJan Schumann    }
608b06d178Schris
616416b708SMichael Hamann    if(!isset($auth) || !$auth){
623094e817SAndreas Gohr        msg($lang['authtempfail'], -1);
633094e817SAndreas Gohr        return false;
643094e817SAndreas Gohr    }
658b06d178Schris
666416b708SMichael Hamann    if ($auth->success == false) {
670f4f4adfSAndreas Gohr        // degrade to unauthenticated user
68d2dde4ebSMatthias Grimm        unset($auth);
690f4f4adfSAndreas Gohr        auth_logoff();
70cd52f92dSchris        msg($lang['authtempfail'], -1);
716416b708SMichael Hamann        return false;
72d2dde4ebSMatthias Grimm    }
7316905344SAndreas Gohr
7416905344SAndreas Gohr    // do the login either by cookie or provided credentials XXX
75bcc94b2cSAndreas Gohr    $INPUT->set('http_credentials', false);
76bcc94b2cSAndreas Gohr    if(!$conf['rememberme']) $INPUT->set('r', false);
77bbbd6568SAndreas Gohr
78b2665af7SMichael Hamann    // handle renamed HTTP_AUTHORIZATION variable (can happen when a fix like
79b2665af7SMichael Hamann    // the one presented at
80b2665af7SMichael Hamann    // http://www.besthostratings.com/articles/http-auth-php-cgi.html is used
81b2665af7SMichael Hamann    // for enabling HTTP authentication with CGI/SuExec)
82b2665af7SMichael Hamann    if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
83b2665af7SMichael Hamann        $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
84528ddc7cSAndreas Gohr    // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
8506156f3cSAndreas Gohr    if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
86528ddc7cSAndreas Gohr        list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
87528ddc7cSAndreas Gohr            explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
88528ddc7cSAndreas Gohr    }
89528ddc7cSAndreas Gohr
901e8c9c90SAndreas Gohr    // if no credentials were given try to use HTTP auth (for SSO)
91bcc94b2cSAndreas Gohr    if(!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])) {
92bcc94b2cSAndreas Gohr        $INPUT->set('u', $_SERVER['PHP_AUTH_USER']);
93bcc94b2cSAndreas Gohr        $INPUT->set('p', $_SERVER['PHP_AUTH_PW']);
94bcc94b2cSAndreas Gohr        $INPUT->set('http_credentials', true);
951e8c9c90SAndreas Gohr    }
961e8c9c90SAndreas Gohr
97395c2f0fSAndreas Gohr    // apply cleaning (auth specific user names, remove control chars)
9893a7873eSAndreas Gohr    if (true === $auth->success) {
99395c2f0fSAndreas Gohr        $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
100395c2f0fSAndreas Gohr        $INPUT->set('p', stripctl($INPUT->str('p')));
101f4476bd9SJan Schumann    }
102191bb90aSAndreas Gohr
1038eca974cSAndreas Gohr    if(!is_null($auth) && $auth->canDo('external')) {
104f13fa892SAndreas Gohr        // external trust mechanism in place
105bcc94b2cSAndreas Gohr        $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
106f5cb575dSAndreas Gohr    } else {
1076080c584SRobin Gareus        $evdata = array(
108bcc94b2cSAndreas Gohr            'user'     => $INPUT->str('u'),
109bcc94b2cSAndreas Gohr            'password' => $INPUT->str('p'),
110bcc94b2cSAndreas Gohr            'sticky'   => $INPUT->bool('r'),
111bcc94b2cSAndreas Gohr            'silent'   => $INPUT->bool('http_credentials')
1126080c584SRobin Gareus        );
113cbb44eabSAndreas Gohr        Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
114f5cb575dSAndreas Gohr    }
115f5cb575dSAndreas Gohr
11616905344SAndreas Gohr    //load ACL into a global array XXX
11775c93b77SAndreas Gohr    $AUTH_ACL = auth_loadACL();
118ab5d26daSAndreas Gohr
119ab5d26daSAndreas Gohr    return true;
12075c93b77SAndreas Gohr}
12175c93b77SAndreas Gohr
12275c93b77SAndreas Gohr/**
12375c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards
12475c93b77SAndreas Gohr *
12575c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12642ea7f44SGerrit Uitslag *
127ab5d26daSAndreas Gohr * @return array
12875c93b77SAndreas Gohr */
12975c93b77SAndreas Gohrfunction auth_loadACL() {
13075c93b77SAndreas Gohr    global $config_cascade;
131b78bf706Sromain    global $USERINFO;
132585bf44eSChristopher Smith    /* @var Input $INPUT */
133585bf44eSChristopher Smith    global $INPUT;
13475c93b77SAndreas Gohr
13575c93b77SAndreas Gohr    if(!is_readable($config_cascade['acl']['default'])) return array();
13675c93b77SAndreas Gohr
13775c93b77SAndreas Gohr    $acl = file($config_cascade['acl']['default']);
13875c93b77SAndreas Gohr
13932e82180SAndreas Gohr    $out = array();
1409ce556d2SAndreas Gohr    foreach($acl as $line) {
1419ce556d2SAndreas Gohr        $line = trim($line);
1422401f18dSSyntaxseed        if(empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
14321c3090aSChristopher Smith        list($id,$rest) = preg_split('/[ \t]+/',$line,2);
14432e82180SAndreas Gohr
145443e135dSChristopher Smith        // substitute user wildcard first (its 1:1)
146ad3d68d7SChristopher Smith        if(strstr($line, '%USER%')){
147ad3d68d7SChristopher Smith            // if user is not logged in, this ACL line is meaningless - skip it
148585bf44eSChristopher Smith            if (!$INPUT->server->has('REMOTE_USER')) continue;
149ad3d68d7SChristopher Smith
150585bf44eSChristopher Smith            $id   = str_replace('%USER%',cleanID($INPUT->server->str('REMOTE_USER')),$id);
151585bf44eSChristopher Smith            $rest = str_replace('%USER%',auth_nameencode($INPUT->server->str('REMOTE_USER')),$rest);
152ad3d68d7SChristopher Smith        }
153ad3d68d7SChristopher Smith
154ad3d68d7SChristopher Smith        // substitute group wildcard (its 1:m)
1559ce556d2SAndreas Gohr        if(strstr($line, '%GROUP%')){
156ad3d68d7SChristopher Smith            // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
15706f34f54SPhy            if(isset($USERINFO['grps'])){
1589ce556d2SAndreas Gohr                foreach((array) $USERINFO['grps'] as $grp){
159b78bf706Sromain                    $nid   = str_replace('%GROUP%',cleanID($grp),$id);
16032e82180SAndreas Gohr                    $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest);
16132e82180SAndreas Gohr                    $out[] = "$nid\t$nrest";
162b78bf706Sromain                }
16306f34f54SPhy            }
16432e82180SAndreas Gohr        } else {
16532e82180SAndreas Gohr            $out[] = "$id\t$rest";
166a8fe108bSGuy Brand        }
16711799630Sandi    }
1689ce556d2SAndreas Gohr
16932e82180SAndreas Gohr    return $out;
170f3f0262cSandi}
171f3f0262cSandi
172ab5d26daSAndreas Gohr/**
173ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK
174ab5d26daSAndreas Gohr *
17542ea7f44SGerrit Uitslag * @param array $evdata
176ab5d26daSAndreas Gohr * @return bool
177ab5d26daSAndreas Gohr */
178b5ee21aaSAdrian Langfunction auth_login_wrapper($evdata) {
179ab5d26daSAndreas Gohr    return auth_login(
180ab5d26daSAndreas Gohr        $evdata['user'],
181b5ee21aaSAdrian Lang        $evdata['password'],
182b5ee21aaSAdrian Lang        $evdata['sticky'],
183ab5d26daSAndreas Gohr        $evdata['silent']
184ab5d26daSAndreas Gohr    );
185b5ee21aaSAdrian Lang}
186b5ee21aaSAdrian Lang
187f3f0262cSandi/**
188f3f0262cSandi * This tries to login the user based on the sent auth credentials
189f3f0262cSandi *
190f3f0262cSandi * The authentication works like this: if a username was given
19115fae107Sandi * a new login is assumed and user/password are checked. If they
19215fae107Sandi * are correct the password is encrypted with blowfish and stored
19315fae107Sandi * together with the username in a cookie - the same info is stored
19415fae107Sandi * in the session, too. Additonally a browserID is stored in the
19515fae107Sandi * session.
19615fae107Sandi *
19715fae107Sandi * If no username was given the cookie is checked: if the username,
19815fae107Sandi * crypted password and browserID match between session and cookie
19915fae107Sandi * no further testing is done and the user is accepted
20015fae107Sandi *
20115fae107Sandi * If a cookie was found but no session info was availabe the
202136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
20315fae107Sandi * together with username rechecked by calling this function again.
204f3f0262cSandi *
205f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
206f3f0262cSandi * are set.
20715fae107Sandi *
20815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
20915fae107Sandi *
21015fae107Sandi * @param   string  $user    Username
21115fae107Sandi * @param   string  $pass    Cleartext Password
21215fae107Sandi * @param   bool    $sticky  Cookie should not expire
213f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
21415fae107Sandi * @return  bool             true on successful auth
215f3f0262cSandi */
216f112c2faSAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false) {
217f3f0262cSandi    global $USERINFO;
218f3f0262cSandi    global $conf;
219f3f0262cSandi    global $lang;
220e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
221cd52f92dSchris    global $auth;
222585bf44eSChristopher Smith    /* @var Input $INPUT */
223585bf44eSChristopher Smith    global $INPUT;
224ab5d26daSAndreas Gohr
225132bdbfeSandi    $sticky ? $sticky = true : $sticky = false; //sanity check
226f3f0262cSandi
227beca106aSAdrian Lang    if(!$auth) return false;
228beca106aSAdrian Lang
229bbbd6568SAndreas Gohr    if(!empty($user)) {
230132bdbfeSandi        //usual login
2315e9e1054SAndreas Gohr        if(!empty($pass) && $auth->checkPass($user, $pass)) {
232132bdbfeSandi            // make logininfo globally available
233585bf44eSChristopher Smith            $INPUT->server->set('REMOTE_USER', $user);
23430d544a4SMichael Hamann            $secret                 = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
23504369c3eSMichael Hamann            auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
236132bdbfeSandi            return true;
237f3f0262cSandi        } else {
238f3f0262cSandi            //invalid credentials - log off
239f8b1e4e7SAndreas Gohr            if(!$silent) {
240f8b1e4e7SAndreas Gohr                http_status(403, 'Login failed');
241f8b1e4e7SAndreas Gohr                msg($lang['badlogin'], -1);
242f8b1e4e7SAndreas Gohr            }
243f3f0262cSandi            auth_logoff();
244132bdbfeSandi            return false;
245f3f0262cSandi        }
246f3f0262cSandi    } else {
247132bdbfeSandi        // read cookie information
248645c0a36SAndreas Gohr        list($user, $sticky, $pass) = auth_getCookie();
249132bdbfeSandi        if($user && $pass) {
250132bdbfeSandi            // we got a cookie - see if we can trust it
251fa7c70ffSAdrian Lang
252fa7c70ffSAdrian Lang            // get session info
253fa7c70ffSAdrian Lang            $session = $_SESSION[DOKU_COOKIE]['auth'];
254132bdbfeSandi            if(isset($session) &&
2557172dbc0SAndreas Gohr                $auth->useSessionCache($user) &&
2564c989037SChris Smith                ($session['time'] >= time() - $conf['auth_security_timeout']) &&
257132bdbfeSandi                ($session['user'] == $user) &&
258234ce57eSAndreas Gohr                ($session['pass'] == sha1($pass)) && //still crypted
259ab5d26daSAndreas Gohr                ($session['buid'] == auth_browseruid())
260ab5d26daSAndreas Gohr            ) {
261234ce57eSAndreas Gohr
262132bdbfeSandi                // he has session, cookie and browser right - let him in
263585bf44eSChristopher Smith                $INPUT->server->set('REMOTE_USER', $user);
264132bdbfeSandi                $USERINFO               = $session['info']; //FIXME move all references to session
265132bdbfeSandi                return true;
266132bdbfeSandi            }
267f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
26830d544a4SMichael Hamann            $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
26904369c3eSMichael Hamann            $pass   = auth_decrypt($pass, $secret);
270f112c2faSAndreas Gohr            return auth_login($user, $pass, $sticky, true);
271132bdbfeSandi        }
272132bdbfeSandi    }
273f3f0262cSandi    //just to be sure
274883179a4SAndreas Gohr    auth_logoff(true);
275132bdbfeSandi    return false;
276f3f0262cSandi}
277132bdbfeSandi
278132bdbfeSandi/**
279136ce040Sandi * Builds a pseudo UID from browser and IP data
280132bdbfeSandi *
281132bdbfeSandi * This is neither unique nor unfakable - still it adds some
282136ce040Sandi * security. Using the first part of the IP makes sure
28380b4f376SAndreas Gohr * proxy farms like AOLs are still okay.
28415fae107Sandi *
28515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
28615fae107Sandi *
28715fae107Sandi * @return  string  a MD5 sum of various browser headers
288132bdbfeSandi */
289132bdbfeSandifunction auth_browseruid() {
290585bf44eSChristopher Smith    /* @var Input $INPUT */
291585bf44eSChristopher Smith    global $INPUT;
292585bf44eSChristopher Smith
2932f9daf16SAndreas Gohr    $ip  = clientIP(true);
294132bdbfeSandi    $uid = '';
295585bf44eSChristopher Smith    $uid .= $INPUT->server->str('HTTP_USER_AGENT');
296585bf44eSChristopher Smith    $uid .= $INPUT->server->str('HTTP_ACCEPT_CHARSET');
2972f9daf16SAndreas Gohr    $uid .= substr($ip, 0, strpos($ip, '.'));
29880b4f376SAndreas Gohr    $uid = strtolower($uid);
299132bdbfeSandi    return md5($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 *
449f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
450f8cc712eSAndreas Gohr * @see    auth_isadmin
45142ea7f44SGerrit Uitslag *
452ab5d26daSAndreas Gohr * @param  string $user       Username
453ab5d26daSAndreas Gohr * @param  array  $groups     List of groups the user is in
454ab5d26daSAndreas Gohr * @param  bool   $adminonly  when true checks if user is admin
455ab5d26daSAndreas Gohr * @return bool
456f8cc712eSAndreas Gohr */
457f8cc712eSAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false) {
458f8cc712eSAndreas Gohr    global $conf;
459f8cc712eSAndreas Gohr    global $USERINFO;
460e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
461d752aedeSAndreas Gohr    global $auth;
462585bf44eSChristopher Smith    /* @var Input $INPUT */
463585bf44eSChristopher Smith    global $INPUT;
464585bf44eSChristopher Smith
465f8cc712eSAndreas Gohr
466beca106aSAdrian Lang    if(!$auth) return false;
467c66972f2SAdrian Lang    if(is_null($user)) {
468585bf44eSChristopher Smith        if(!$INPUT->server->has('REMOTE_USER')) {
469c66972f2SAdrian Lang            return false;
470c66972f2SAdrian Lang        } else {
471585bf44eSChristopher Smith            $user = $INPUT->server->str('REMOTE_USER');
472c66972f2SAdrian Lang        }
473c66972f2SAdrian Lang    }
474d6dc956fSAndreas Gohr    if(is_null($groups)) {
475*3e9ae63dSPhy        $groups = $USERINFO ? (array) $USERINFO['grps'] : array();
476e259aa79SAndreas Gohr    }
477e259aa79SAndreas Gohr
478d6dc956fSAndreas Gohr    // check superuser match
479d6dc956fSAndreas Gohr    if(auth_isMember($conf['superuser'], $user, $groups)) return true;
480d6dc956fSAndreas Gohr    if($adminonly) return false;
481e259aa79SAndreas Gohr    // check managers
482d6dc956fSAndreas Gohr    if(auth_isMember($conf['manager'], $user, $groups)) return true;
48300ce12daSChris Smith
484f8cc712eSAndreas Gohr    return false;
485f8cc712eSAndreas Gohr}
486f8cc712eSAndreas Gohr
487f8cc712eSAndreas Gohr/**
488f8cc712eSAndreas Gohr * Check if a user is admin
489f8cc712eSAndreas Gohr *
490f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
491f8cc712eSAndreas Gohr *
492f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
493f8cc712eSAndreas Gohr *
494f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
495ab5d26daSAndreas Gohr * @see auth_ismanager()
49642ea7f44SGerrit Uitslag *
497ab5d26daSAndreas Gohr * @param  string $user       Username
498ab5d26daSAndreas Gohr * @param  array  $groups     List of groups the user is in
499ab5d26daSAndreas Gohr * @return bool
500f8cc712eSAndreas Gohr */
501f8cc712eSAndreas Gohrfunction auth_isadmin($user = null, $groups = null) {
502f8cc712eSAndreas Gohr    return auth_ismanager($user, $groups, true);
503f8cc712eSAndreas Gohr}
504f8cc712eSAndreas Gohr
505d6dc956fSAndreas Gohr/**
506d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
507d6dc956fSAndreas Gohr * users and groups to determine membership status
508d6dc956fSAndreas Gohr *
509d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
510d6dc956fSAndreas Gohr *
51142ea7f44SGerrit Uitslag * @param string $memberlist commaseparated list of allowed users and groups
51242ea7f44SGerrit Uitslag * @param string $user       user to match against
51342ea7f44SGerrit Uitslag * @param array  $groups     groups the user is member of
5145446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
515d6dc956fSAndreas Gohr */
516d6dc956fSAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups) {
517e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
518d6dc956fSAndreas Gohr    global $auth;
519d6dc956fSAndreas Gohr    if(!$auth) return false;
520d6dc956fSAndreas Gohr
521d6dc956fSAndreas Gohr    // clean user and groups
5224f56ecbfSAdrian Lang    if(!$auth->isCaseSensitive()) {
5238cbc5ee8SAndreas Gohr        $user   = \dokuwiki\Utf8\PhpString::strtolower($user);
524d6dc956fSAndreas Gohr        $groups = array_map('utf8_strtolower', $groups);
525d6dc956fSAndreas Gohr    }
526d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
527d6dc956fSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), $groups);
528d6dc956fSAndreas Gohr
529d6dc956fSAndreas Gohr    // extract the memberlist
530d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
531d6dc956fSAndreas Gohr    $members = array_map('trim', $members);
532d6dc956fSAndreas Gohr    $members = array_unique($members);
533d6dc956fSAndreas Gohr    $members = array_filter($members);
534d6dc956fSAndreas Gohr
535d6dc956fSAndreas Gohr    // compare cleaned values
536d6dc956fSAndreas Gohr    foreach($members as $member) {
537e5204a12SJurgen Hart        if($member == '@ALL' ) return true;
5388cbc5ee8SAndreas Gohr        if(!$auth->isCaseSensitive()) $member = \dokuwiki\Utf8\PhpString::strtolower($member);
539d6dc956fSAndreas Gohr        if($member[0] == '@') {
540d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
541d6dc956fSAndreas Gohr            if(in_array($member, $groups)) return true;
542d6dc956fSAndreas Gohr        } else {
543d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
544d6dc956fSAndreas Gohr            if($member == $user) return true;
545d6dc956fSAndreas Gohr        }
546d6dc956fSAndreas Gohr    }
547d6dc956fSAndreas Gohr
548d6dc956fSAndreas Gohr    // still here? not a member!
549d6dc956fSAndreas Gohr    return false;
550d6dc956fSAndreas Gohr}
551d6dc956fSAndreas Gohr
552f8cc712eSAndreas Gohr/**
55315fae107Sandi * Convinience function for auth_aclcheck()
55415fae107Sandi *
55515fae107Sandi * This checks the permissions for the current user
55615fae107Sandi *
55715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
55815fae107Sandi *
5591698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
56015fae107Sandi * @return int          permission level
561f3f0262cSandi */
562f3f0262cSandifunction auth_quickaclcheck($id) {
563f3f0262cSandi    global $conf;
564f3f0262cSandi    global $USERINFO;
565585bf44eSChristopher Smith    /* @var Input $INPUT */
566585bf44eSChristopher Smith    global $INPUT;
567f3f0262cSandi    # if no ACL is used always return upload rights
568f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
569*3e9ae63dSPhy    return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : array());
570f3f0262cSandi}
571f3f0262cSandi
572f3f0262cSandi/**
573c17acc9fSAndreas Gohr * Returns the maximum rights a user has for the given ID or its namespace
57415fae107Sandi *
57515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
57642ea7f44SGerrit Uitslag *
577c17acc9fSAndreas Gohr * @triggers AUTH_ACL_CHECK
5781698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
57915fae107Sandi * @param  string       $user   Username
5803272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
58115fae107Sandi * @return int             permission level
582f3f0262cSandi */
583f3f0262cSandifunction auth_aclcheck($id, $user, $groups) {
584c17acc9fSAndreas Gohr    $data = array(
585c17acc9fSAndreas Gohr        'id'     => $id,
586c17acc9fSAndreas Gohr        'user'   => $user,
587c17acc9fSAndreas Gohr        'groups' => $groups
588c17acc9fSAndreas Gohr    );
589c17acc9fSAndreas Gohr
590cbb44eabSAndreas Gohr    return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
591c17acc9fSAndreas Gohr}
592c17acc9fSAndreas Gohr
593c17acc9fSAndreas Gohr/**
594c17acc9fSAndreas Gohr * default ACL check method
595c17acc9fSAndreas Gohr *
596c17acc9fSAndreas Gohr * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
597c17acc9fSAndreas Gohr *
598c17acc9fSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
59942ea7f44SGerrit Uitslag *
600c17acc9fSAndreas Gohr * @param  array $data event data
601c17acc9fSAndreas Gohr * @return int   permission level
602c17acc9fSAndreas Gohr */
603c17acc9fSAndreas Gohrfunction auth_aclcheck_cb($data) {
604c17acc9fSAndreas Gohr    $id     =& $data['id'];
605c17acc9fSAndreas Gohr    $user   =& $data['user'];
606c17acc9fSAndreas Gohr    $groups =& $data['groups'];
607c17acc9fSAndreas Gohr
608f3f0262cSandi    global $conf;
609f3f0262cSandi    global $AUTH_ACL;
610e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
611d752aedeSAndreas Gohr    global $auth;
612f3f0262cSandi
61385d03f68SAndreas Gohr    // if no ACL is used always return upload rights
614f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
615beca106aSAdrian Lang    if(!$auth) return AUTH_NONE;
616f3f0262cSandi
617074cf26bSandi    //make sure groups is an array
618074cf26bSandi    if(!is_array($groups)) $groups = array();
619074cf26bSandi
62085d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
621ab5d26daSAndreas Gohr    if(auth_isadmin($user, $groups)) {
622ab5d26daSAndreas Gohr        return AUTH_ADMIN;
623ab5d26daSAndreas Gohr    }
62485d03f68SAndreas Gohr
625eb3ce0d5SKazutaka Miyasaka    if(!$auth->isCaseSensitive()) {
6268cbc5ee8SAndreas Gohr        $user   = \dokuwiki\Utf8\PhpString::strtolower($user);
627eb3ce0d5SKazutaka Miyasaka        $groups = array_map('utf8_strtolower', $groups);
628eb3ce0d5SKazutaka Miyasaka    }
62937ff2261SSascha Klopp    $user   = auth_nameencode($auth->cleanUser($user));
630d752aedeSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
63185d03f68SAndreas Gohr
6326c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
63337ff2261SSascha Klopp    foreach($groups as &$group) {
63437ff2261SSascha Klopp        $group = '@'.auth_nameencode($group);
63510a76f6fSfrank    }
63610a76f6fSfrank
637f3f0262cSandi    $ns   = getNS($id);
638f3f0262cSandi    $perm = -1;
639f3f0262cSandi
640f3f0262cSandi    //add ALL group
641f3f0262cSandi    $groups[] = '@ALL';
64237ff2261SSascha Klopp
643f3f0262cSandi    //add User
64434aeb4afSAndreas Gohr    if($user) $groups[] = $user;
645f3f0262cSandi
646f3f0262cSandi    //check exact match first
64721c3090aSChristopher Smith    $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
648f3f0262cSandi    if(count($matches)) {
649f3f0262cSandi        foreach($matches as $match) {
650f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
65121c3090aSChristopher Smith            $acl   = preg_split('/[ \t]+/', $match);
652eb3ce0d5SKazutaka Miyasaka            if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
6538cbc5ee8SAndreas Gohr                $acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]);
654eb3ce0d5SKazutaka Miyasaka            }
65548d7b7a6SDominik Eckelmann            if(!in_array($acl[1], $groups)) {
65648d7b7a6SDominik Eckelmann                continue;
65748d7b7a6SDominik Eckelmann            }
6588ef6b7caSandi            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
659f3f0262cSandi            if($acl[2] > $perm) {
660f3f0262cSandi                $perm = $acl[2];
661f3f0262cSandi            }
662f3f0262cSandi        }
663f3f0262cSandi        if($perm > -1) {
664f3f0262cSandi            //we had a match - return it
665def492a2SGuillaume Turri            return (int) $perm;
666f3f0262cSandi        }
667f3f0262cSandi    }
668f3f0262cSandi
669f3f0262cSandi    //still here? do the namespace checks
670f3f0262cSandi    if($ns) {
6713e304b55SMichael Hamann        $path = $ns.':*';
672f3f0262cSandi    } else {
6733e304b55SMichael Hamann        $path = '*'; //root document
674f3f0262cSandi    }
675f3f0262cSandi
676f3f0262cSandi    do {
67721c3090aSChristopher Smith        $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
678f3f0262cSandi        if(count($matches)) {
679f3f0262cSandi            foreach($matches as $match) {
680f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
68121c3090aSChristopher Smith                $acl   = preg_split('/[ \t]+/', $match);
682eb3ce0d5SKazutaka Miyasaka                if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
6838cbc5ee8SAndreas Gohr                    $acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]);
684eb3ce0d5SKazutaka Miyasaka                }
68548d7b7a6SDominik Eckelmann                if(!in_array($acl[1], $groups)) {
68648d7b7a6SDominik Eckelmann                    continue;
68748d7b7a6SDominik Eckelmann                }
6888ef6b7caSandi                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
689f3f0262cSandi                if($acl[2] > $perm) {
690f3f0262cSandi                    $perm = $acl[2];
691f3f0262cSandi                }
692f3f0262cSandi            }
693f3f0262cSandi            //we had a match - return it
69448d7b7a6SDominik Eckelmann            if($perm != -1) {
695def492a2SGuillaume Turri                return (int) $perm;
696f3f0262cSandi            }
69748d7b7a6SDominik Eckelmann        }
698f3f0262cSandi        //get next higher namespace
699f3f0262cSandi        $ns = getNS($ns);
700f3f0262cSandi
7013e304b55SMichael Hamann        if($path != '*') {
7023e304b55SMichael Hamann            $path = $ns.':*';
7033e304b55SMichael Hamann            if($path == ':*') $path = '*';
704f3f0262cSandi        } else {
705f3f0262cSandi            //we did this already
706f3f0262cSandi            //looks like there is something wrong with the ACL
707f3f0262cSandi            //break here
708d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
709d5ce66f6SAndreas Gohr            return AUTH_NONE;
710f3f0262cSandi        }
711f3f0262cSandi    } while(1); //this should never loop endless
712ab5d26daSAndreas Gohr    return AUTH_NONE;
713f3f0262cSandi}
714f3f0262cSandi
715f3f0262cSandi/**
7166c2bb100SAndreas Gohr * Encode ASCII special chars
7176c2bb100SAndreas Gohr *
7186c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
7196c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
7206c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
7216c2bb100SAndreas Gohr * urlencoding!).
7226c2bb100SAndreas Gohr *
7236c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
7246c2bb100SAndreas Gohr *
7256c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
7266c2bb100SAndreas Gohr * @see rawurldecode()
72742ea7f44SGerrit Uitslag *
72842ea7f44SGerrit Uitslag * @param string $name
72942ea7f44SGerrit Uitslag * @param bool $skip_group
73042ea7f44SGerrit Uitslag * @return string
7316c2bb100SAndreas Gohr */
732e838fc2eSAndreas Gohrfunction auth_nameencode($name, $skip_group = false) {
733a424cd8eSchris    global $cache_authname;
734a424cd8eSchris    $cache =& $cache_authname;
73531784267SAndreas Gohr    $name  = (string) $name;
736a424cd8eSchris
73780601d26SAndreas Gohr    // never encode wildcard FS#1955
73880601d26SAndreas Gohr    if($name == '%USER%') return $name;
739b78bf706Sromain    if($name == '%GROUP%') return $name;
74080601d26SAndreas Gohr
741a424cd8eSchris    if(!isset($cache[$name][$skip_group])) {
7422401f18dSSyntaxseed        if($skip_group && $name[0] == '@') {
74330f6faf0SChristopher Smith            $cache[$name][$skip_group] = '@'.preg_replace_callback(
74430f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
74530f6faf0SChristopher Smith                'auth_nameencode_callback', substr($name, 1)
746ab5d26daSAndreas Gohr            );
747e838fc2eSAndreas Gohr        } else {
74830f6faf0SChristopher Smith            $cache[$name][$skip_group] = preg_replace_callback(
74930f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
75030f6faf0SChristopher Smith                'auth_nameencode_callback', $name
751ab5d26daSAndreas Gohr            );
752e838fc2eSAndreas Gohr        }
7536c2bb100SAndreas Gohr    }
7546c2bb100SAndreas Gohr
755a424cd8eSchris    return $cache[$name][$skip_group];
756a424cd8eSchris}
757a424cd8eSchris
75804d68ae4SGerrit Uitslag/**
75904d68ae4SGerrit Uitslag * callback encodes the matches
76004d68ae4SGerrit Uitslag *
76104d68ae4SGerrit Uitslag * @param array $matches first complete match, next matching subpatterms
76204d68ae4SGerrit Uitslag * @return string
76304d68ae4SGerrit Uitslag */
76430f6faf0SChristopher Smithfunction auth_nameencode_callback($matches) {
76530f6faf0SChristopher Smith    return '%'.dechex(ord(substr($matches[1],-1)));
76630f6faf0SChristopher Smith}
76730f6faf0SChristopher Smith
7686c2bb100SAndreas Gohr/**
769f3f0262cSandi * Create a pronouncable password
770f3f0262cSandi *
7718a285f7fSAndreas Gohr * The $foruser variable might be used by plugins to run additional password
7728a285f7fSAndreas Gohr * policy checks, but is not used by the default implementation
7738a285f7fSAndreas Gohr *
77415fae107Sandi * @author   Andreas Gohr <andi@splitbrain.org>
77515fae107Sandi * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
7768a285f7fSAndreas Gohr * @triggers AUTH_PASSWORD_GENERATE
77715fae107Sandi *
7788a285f7fSAndreas Gohr * @param  string $foruser username for which the password is generated
77915fae107Sandi * @return string  pronouncable password
780f3f0262cSandi */
7818a285f7fSAndreas Gohrfunction auth_pwgen($foruser = '') {
7828a285f7fSAndreas Gohr    $data = array(
783d628dcf3SAndreas Gohr        'password' => '',
784d628dcf3SAndreas Gohr        'foruser'  => $foruser
7858a285f7fSAndreas Gohr    );
7868a285f7fSAndreas Gohr
787e1d9dcc8SAndreas Gohr    $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
7888a285f7fSAndreas Gohr    if($evt->advise_before(true)) {
789f3f0262cSandi        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
790f3f0262cSandi        $v = 'aeiou'; //vowels
791f3f0262cSandi        $a = $c.$v; //both
792987c8d26SAndreas Gohr        $s = '!$%&?+*~#-_:.;,'; // specials
793f3f0262cSandi
794987c8d26SAndreas Gohr        //use thre syllables...
795987c8d26SAndreas Gohr        for($i = 0; $i < 3; $i++) {
796483b6238SMichael Hamann            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
797483b6238SMichael Hamann            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
798483b6238SMichael Hamann            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
799f3f0262cSandi        }
800987c8d26SAndreas Gohr        //... and add a nice number and special
80143f71e05Ssdavis80        $data['password'] .= $s[auth_random(0, strlen($s) - 1)].auth_random(10, 99);
8028a285f7fSAndreas Gohr    }
8038a285f7fSAndreas Gohr    $evt->advise_after();
804f3f0262cSandi
8058a285f7fSAndreas Gohr    return $data['password'];
806f3f0262cSandi}
807f3f0262cSandi
808f3f0262cSandi/**
809f3f0262cSandi * Sends a password to the given user
810f3f0262cSandi *
81115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
81242ea7f44SGerrit Uitslag *
813ab5d26daSAndreas Gohr * @param string $user Login name of the user
814ab5d26daSAndreas Gohr * @param string $password The new password in clear text
81515fae107Sandi * @return bool  true on success
816f3f0262cSandi */
817f3f0262cSandifunction auth_sendPassword($user, $password) {
818f3f0262cSandi    global $lang;
819e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
820cd52f92dSchris    global $auth;
821beca106aSAdrian Lang    if(!$auth) return false;
822cd52f92dSchris
823d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
8242dc9e900SChristopher Smith    $userinfo = $auth->getUserData($user, $requireGroups = false);
825f3f0262cSandi
82687ddda95Sandi    if(!$userinfo['mail']) return false;
827f3f0262cSandi
828f3f0262cSandi    $text = rawLocale('password');
829d7169d19SAndreas Gohr    $trep = array(
830d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
831d7169d19SAndreas Gohr        'LOGIN'    => $user,
832d7169d19SAndreas Gohr        'PASSWORD' => $password
833d7169d19SAndreas Gohr    );
834f3f0262cSandi
835d7169d19SAndreas Gohr    $mail = new Mailer();
836102cdbd7SLarsGit223    $mail->to($mail->getCleanName($userinfo['name']).' <'.$userinfo['mail'].'>');
837d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
838d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
839d7169d19SAndreas Gohr    return $mail->send();
840f3f0262cSandi}
841f3f0262cSandi
842f3f0262cSandi/**
84315fae107Sandi * Register a new user
844f3f0262cSandi *
84515fae107Sandi * This registers a new user - Data is read directly from $_POST
84615fae107Sandi *
84715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
84842ea7f44SGerrit Uitslag *
84915fae107Sandi * @return bool  true on success, false on any error
850f3f0262cSandi */
851f3f0262cSandifunction register() {
852f3f0262cSandi    global $lang;
853eb5d07e4Sjan    global $conf;
854e1d9dcc8SAndreas Gohr    /* @var \dokuwiki\Extension\AuthPlugin $auth */
855cd52f92dSchris    global $auth;
85664273335SAndreas Gohr    global $INPUT;
857f3f0262cSandi
85864273335SAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
8593a48618aSAnika Henke    if(!actionOK('register')) return false;
860640145a5Sandi
86164273335SAndreas Gohr    // gather input
86264273335SAndreas Gohr    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
86364273335SAndreas Gohr    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
86464273335SAndreas Gohr    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
86564273335SAndreas Gohr    $pass     = $INPUT->post->str('pass');
86664273335SAndreas Gohr    $passchk  = $INPUT->post->str('passchk');
867d752aedeSAndreas Gohr
86864273335SAndreas Gohr    if(empty($login) || empty($fullname) || empty($email)) {
869f3f0262cSandi        msg($lang['regmissing'], -1);
870f3f0262cSandi        return false;
871f3f0262cSandi    }
872f3f0262cSandi
873cab2716aSmatthias.grimm    if($conf['autopasswd']) {
8748a285f7fSAndreas Gohr        $pass = auth_pwgen($login); // automatically generate password
87564273335SAndreas Gohr    } elseif(empty($pass) || empty($passchk)) {
876bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
877cab2716aSmatthias.grimm        return false;
87864273335SAndreas Gohr    } elseif($pass != $passchk) {
879bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
880cab2716aSmatthias.grimm        return false;
881cab2716aSmatthias.grimm    }
882cab2716aSmatthias.grimm
883f3f0262cSandi    //check mail
88464273335SAndreas Gohr    if(!mail_isvalid($email)) {
885f3f0262cSandi        msg($lang['regbadmail'], -1);
886f3f0262cSandi        return false;
887f3f0262cSandi    }
888f3f0262cSandi
889f3f0262cSandi    //okay try to create the user
89064273335SAndreas Gohr    if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) {
891db9faf02SPatrick Brown        msg($lang['regfail'], -1);
892f3f0262cSandi        return false;
893f3f0262cSandi    }
894f3f0262cSandi
895790b7720SAndreas Gohr    // send notification about the new user
89675d66495SMichael Große    $subscription = new RegistrationSubscriptionSender();
89775d66495SMichael Große    $subscription->sendRegister($login, $fullname, $email);
89802a498e7Schris
899790b7720SAndreas Gohr    // are we done?
900cab2716aSmatthias.grimm    if(!$conf['autopasswd']) {
901cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
902cab2716aSmatthias.grimm        return true;
903cab2716aSmatthias.grimm    }
904cab2716aSmatthias.grimm
905790b7720SAndreas Gohr    // autogenerated password? then send password to user
90664273335SAndreas Gohr    if(auth_sendPassword($login, $pass)) {
907f3f0262cSandi        msg($lang['regsuccess'], 1);
908f3f0262cSandi        return true;
909f3f0262cSandi    } else {
910f3f0262cSandi        msg($lang['regmailfail'], -1);
911f3f0262cSandi        return false;
912f3f0262cSandi    }
913f3f0262cSandi}
914f3f0262cSandi
91510a76f6fSfrank/**
9168b06d178Schris * Update user profile
9178b06d178Schris *
9188b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
9198b06d178Schris */
9208b06d178Schrisfunction updateprofile() {
9218b06d178Schris    global $conf;
9228b06d178Schris    global $lang;
923e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
924cd52f92dSchris    global $auth;
925bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
926bcc94b2cSAndreas Gohr    global $INPUT;
9278b06d178Schris
928bcc94b2cSAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
9291b2a85e8SAndreas Gohr    if(!checkSecurityToken()) return false;
9308b06d178Schris
9313a48618aSAnika Henke    if(!actionOK('profile')) {
9328b06d178Schris        msg($lang['profna'], -1);
9338b06d178Schris        return false;
9348b06d178Schris    }
9358b06d178Schris
936bcc94b2cSAndreas Gohr    $changes         = array();
937bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
938bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
939bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
940bcc94b2cSAndreas Gohr
941bcc94b2cSAndreas Gohr    // check misspelled passwords
942bcc94b2cSAndreas Gohr    if($changes['pass'] != $INPUT->post->str('passchk')) {
943bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
9448b06d178Schris        return false;
9458b06d178Schris    }
9468b06d178Schris
9478b06d178Schris    // clean fullname and email
948bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
949bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
9508b06d178Schris
951bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
952bcc94b2cSAndreas Gohr    if((empty($changes['name']) && $auth->canDo('modName')) ||
953bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
954ab5d26daSAndreas Gohr    ) {
9558b06d178Schris        msg($lang['profnoempty'], -1);
9568b06d178Schris        return false;
9578b06d178Schris    }
958bcc94b2cSAndreas Gohr    if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
9598b06d178Schris        msg($lang['regbadmail'], -1);
9608b06d178Schris        return false;
9618b06d178Schris    }
9628b06d178Schris
963bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
9644c21b7eeSAndreas Gohr
965bcc94b2cSAndreas Gohr    // check for unavailable capabilities
966bcc94b2cSAndreas Gohr    if(!$auth->canDo('modName')) unset($changes['name']);
967bcc94b2cSAndreas Gohr    if(!$auth->canDo('modMail')) unset($changes['mail']);
968bcc94b2cSAndreas Gohr    if(!$auth->canDo('modPass')) unset($changes['pass']);
969bcc94b2cSAndreas Gohr
970bcc94b2cSAndreas Gohr    // anything to do?
9718b06d178Schris    if(!count($changes)) {
9728b06d178Schris        msg($lang['profnochange'], -1);
9738b06d178Schris        return false;
9748b06d178Schris    }
9758b06d178Schris
9768b06d178Schris    if($conf['profileconfirm']) {
977585bf44eSChristopher Smith        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
97871422fc8SChristopher Smith            msg($lang['badpassconfirm'], -1);
9798b06d178Schris            return false;
9808b06d178Schris        }
9818b06d178Schris    }
9828b06d178Schris
983e6c4392fSPatrick Brown    if(!$auth->triggerUserMod('modify', array($INPUT->server->str('REMOTE_USER'), &$changes))) {
984db9faf02SPatrick Brown        msg($lang['proffail'], -1);
985db9faf02SPatrick Brown        return false;
986db9faf02SPatrick Brown    }
987db9faf02SPatrick Brown
98832ed2b36SAndreas Gohr    if($changes['pass']) {
989c276e9e8SMarcel Pennewiss        // update cookie and session with the changed data
990ab5d26daSAndreas Gohr        list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
99104369c3eSMichael Hamann        $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
992585bf44eSChristopher Smith        auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
993c276e9e8SMarcel Pennewiss    } else {
994c276e9e8SMarcel Pennewiss        // make sure the session is writable
995c276e9e8SMarcel Pennewiss        @session_start();
996c276e9e8SMarcel Pennewiss        // invalidate session cache
997c276e9e8SMarcel Pennewiss        $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
998c276e9e8SMarcel Pennewiss        session_write_close();
99932ed2b36SAndreas Gohr    }
1000c276e9e8SMarcel Pennewiss
100125b2a98cSMichael Klier    return true;
1002a0b5b007SChris Smith}
1003ab5d26daSAndreas Gohr
100404d68ae4SGerrit Uitslag/**
100504d68ae4SGerrit Uitslag * Delete the current logged-in user
100604d68ae4SGerrit Uitslag *
100704d68ae4SGerrit Uitslag * @return bool true on success, false on any error
100804d68ae4SGerrit Uitslag */
10092a7abf2dSChristopher Smithfunction auth_deleteprofile(){
10102a7abf2dSChristopher Smith    global $conf;
10112a7abf2dSChristopher Smith    global $lang;
1012e1d9dcc8SAndreas Gohr    /* @var \dokuwiki\Extension\AuthPlugin $auth */
10132a7abf2dSChristopher Smith    global $auth;
10142a7abf2dSChristopher Smith    /* @var Input $INPUT */
10152a7abf2dSChristopher Smith    global $INPUT;
10162a7abf2dSChristopher Smith
10172a7abf2dSChristopher Smith    if(!$INPUT->post->bool('delete')) return false;
10182a7abf2dSChristopher Smith    if(!checkSecurityToken()) return false;
10192a7abf2dSChristopher Smith
10202a7abf2dSChristopher Smith    // action prevented or auth module disallows
10212a7abf2dSChristopher Smith    if(!actionOK('profile_delete') || !$auth->canDo('delUser')) {
10222a7abf2dSChristopher Smith        msg($lang['profnodelete'], -1);
10232a7abf2dSChristopher Smith        return false;
10242a7abf2dSChristopher Smith    }
10252a7abf2dSChristopher Smith
10262a7abf2dSChristopher Smith    if(!$INPUT->post->bool('confirm_delete')){
10272a7abf2dSChristopher Smith        msg($lang['profconfdeletemissing'], -1);
10282a7abf2dSChristopher Smith        return false;
10292a7abf2dSChristopher Smith    }
10302a7abf2dSChristopher Smith
10312a7abf2dSChristopher Smith    if($conf['profileconfirm']) {
1032585bf44eSChristopher Smith        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
10332a7abf2dSChristopher Smith            msg($lang['badpassconfirm'], -1);
10342a7abf2dSChristopher Smith            return false;
10352a7abf2dSChristopher Smith        }
10362a7abf2dSChristopher Smith    }
10372a7abf2dSChristopher Smith
103859bc3b48SGerrit Uitslag    $deleted = array();
1039585bf44eSChristopher Smith    $deleted[] = $INPUT->server->str('REMOTE_USER');
104073012efdSChristopher Smith    if($auth->triggerUserMod('delete', array($deleted))) {
10412a7abf2dSChristopher Smith        // force and immediate logout including removing the sticky cookie
10422a7abf2dSChristopher Smith        auth_logoff();
10432a7abf2dSChristopher Smith        return true;
10442a7abf2dSChristopher Smith    }
10452a7abf2dSChristopher Smith
10462a7abf2dSChristopher Smith    return false;
10472a7abf2dSChristopher Smith}
10482a7abf2dSChristopher Smith
10498b06d178Schris/**
10508b06d178Schris * Send a  new password
10518b06d178Schris *
10521d5856cfSAndreas Gohr * This function handles both phases of the password reset:
10531d5856cfSAndreas Gohr *
10541d5856cfSAndreas Gohr *   - handling the first request of password reset
10551d5856cfSAndreas Gohr *   - validating the password reset auth token
10561d5856cfSAndreas Gohr *
10578b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
10588b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
10591d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10608b06d178Schris *
10618b06d178Schris * @return bool true on success, false on any error
10628b06d178Schris */
10638b06d178Schrisfunction act_resendpwd() {
10648b06d178Schris    global $lang;
10658b06d178Schris    global $conf;
1066e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1067cd52f92dSchris    global $auth;
1068bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1069bcc94b2cSAndreas Gohr    global $INPUT;
10708b06d178Schris
10713a48618aSAnika Henke    if(!actionOK('resendpwd')) {
10728b06d178Schris        msg($lang['resendna'], -1);
10738b06d178Schris        return false;
10748b06d178Schris    }
10758b06d178Schris
1076bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
10778b06d178Schris
10781d5856cfSAndreas Gohr    if($token) {
1079cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
10801d5856cfSAndreas Gohr
10812401f18dSSyntaxseed        $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
108279e79377SAndreas Gohr        if(!file_exists($tfile)) {
10831d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1084bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
10851d5856cfSAndreas Gohr            return false;
10861d5856cfSAndreas Gohr        }
10878a9735e3SAndreas Gohr        // token is only valid for 3 days
10888a9735e3SAndreas Gohr        if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
10898a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1090bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
10911d5856cfSAndreas Gohr            @unlink($tfile);
10928a9735e3SAndreas Gohr            return false;
10938a9735e3SAndreas Gohr        }
10948a9735e3SAndreas Gohr
10958b06d178Schris        $user     = io_readfile($tfile);
10962dc9e900SChristopher Smith        $userinfo = $auth->getUserData($user, $requireGroups = false);
10978b06d178Schris        if(!$userinfo['mail']) {
10988b06d178Schris            msg($lang['resendpwdnouser'], -1);
10998b06d178Schris            return false;
11008b06d178Schris        }
11018b06d178Schris
1102cc204bbdSAndreas Gohr        if(!$conf['autopasswd']) { // we let the user choose a password
1103bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
1104bcc94b2cSAndreas Gohr
1105cc204bbdSAndreas Gohr            // password given correctly?
1106bcc94b2cSAndreas Gohr            if(!$pass) return false;
1107bcc94b2cSAndreas Gohr            if($pass != $INPUT->str('passchk')) {
1108451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
1109cc204bbdSAndreas Gohr                return false;
1110cc204bbdSAndreas Gohr            }
1111cc204bbdSAndreas Gohr
1112bcc94b2cSAndreas Gohr            // change it
1113cc204bbdSAndreas Gohr            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1114db9faf02SPatrick Brown                msg($lang['proffail'], -1);
1115cc204bbdSAndreas Gohr                return false;
1116cc204bbdSAndreas Gohr            }
1117cc204bbdSAndreas Gohr
1118cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
1119cc204bbdSAndreas Gohr
11208a285f7fSAndreas Gohr            $pass = auth_pwgen($user);
11217d3c8d42SGabriel Birke            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1122db9faf02SPatrick Brown                msg($lang['proffail'], -1);
11238b06d178Schris                return false;
11248b06d178Schris            }
11258b06d178Schris
11268b06d178Schris            if(auth_sendPassword($user, $pass)) {
11278b06d178Schris                msg($lang['resendpwdsuccess'], 1);
11288b06d178Schris            } else {
11298b06d178Schris                msg($lang['regmailfail'], -1);
11308b06d178Schris            }
1131cc204bbdSAndreas Gohr        }
1132cc204bbdSAndreas Gohr
1133cc204bbdSAndreas Gohr        @unlink($tfile);
11348b06d178Schris        return true;
11351d5856cfSAndreas Gohr
11361d5856cfSAndreas Gohr    } else {
11371d5856cfSAndreas Gohr        // we're in request phase
11381d5856cfSAndreas Gohr
1139bcc94b2cSAndreas Gohr        if(!$INPUT->post->bool('save')) return false;
11401d5856cfSAndreas Gohr
1141bcc94b2cSAndreas Gohr        if(!$INPUT->post->str('login')) {
11421d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
11431d5856cfSAndreas Gohr            return false;
11441d5856cfSAndreas Gohr        } else {
1145bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
11461d5856cfSAndreas Gohr        }
11471d5856cfSAndreas Gohr
11482dc9e900SChristopher Smith        $userinfo = $auth->getUserData($user, $requireGroups = false);
11491d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
11501d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
11511d5856cfSAndreas Gohr            return false;
11521d5856cfSAndreas Gohr        }
11531d5856cfSAndreas Gohr
11541d5856cfSAndreas Gohr        // generate auth token
1155483b6238SMichael Hamann        $token = md5(auth_randombytes(16)); // random secret
11562401f18dSSyntaxseed        $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
11571d5856cfSAndreas Gohr        $url   = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
11581d5856cfSAndreas Gohr
11591d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
11601d5856cfSAndreas Gohr
11611d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
1162d7169d19SAndreas Gohr        $trep = array(
1163d7169d19SAndreas Gohr            'FULLNAME' => $userinfo['name'],
1164d7169d19SAndreas Gohr            'LOGIN'    => $user,
1165d7169d19SAndreas Gohr            'CONFIRM'  => $url
1166d7169d19SAndreas Gohr        );
11671d5856cfSAndreas Gohr
1168d7169d19SAndreas Gohr        $mail = new Mailer();
1169d7169d19SAndreas Gohr        $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1170d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
1171d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
1172d7169d19SAndreas Gohr        if($mail->send()) {
11731d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
11741d5856cfSAndreas Gohr        } else {
11751d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
11761d5856cfSAndreas Gohr        }
11771d5856cfSAndreas Gohr        return true;
11781d5856cfSAndreas Gohr    }
1179ab5d26daSAndreas Gohr    // never reached
11808b06d178Schris}
11818b06d178Schris
11828b06d178Schris/**
1183b0855b11Sandi * Encrypts a password using the given method and salt
1184b0855b11Sandi *
1185b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1186b0855b11Sandi * is chosen.
1187b0855b11Sandi *
1188b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
118942ea7f44SGerrit Uitslag *
1190ab5d26daSAndreas Gohr * @param string $clear The clear text password
1191ab5d26daSAndreas Gohr * @param string $method The hashing method
1192ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1193b0855b11Sandi * @return  string  The crypted password
1194b0855b11Sandi */
1195577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null) {
1196b0855b11Sandi    global $conf;
1197b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
119810a76f6fSfrank
11993a0a2d05SAndreas Gohr    $pass = new PassHash();
12003a0a2d05SAndreas Gohr    $call = 'hash_'.$method;
1201b0855b11Sandi
12023a0a2d05SAndreas Gohr    if(!method_exists($pass, $call)) {
1203b0855b11Sandi        msg("Unsupported crypt method $method", -1);
12043a0a2d05SAndreas Gohr        return false;
1205b0855b11Sandi    }
12063a0a2d05SAndreas Gohr
12073a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1208b0855b11Sandi}
1209b0855b11Sandi
1210b0855b11Sandi/**
1211b0855b11Sandi * Verifies a cleartext password against a crypted hash
1212b0855b11Sandi *
1213b0855b11Sandi * @author Andreas Gohr <andi@splitbrain.org>
121442ea7f44SGerrit Uitslag *
1215ab5d26daSAndreas Gohr * @param  string $clear The clear text password
1216ab5d26daSAndreas Gohr * @param  string $crypt The hash to compare with
1217ab5d26daSAndreas Gohr * @return bool true if both match
1218b0855b11Sandi */
1219b0855b11Sandifunction auth_verifyPassword($clear, $crypt) {
12203a0a2d05SAndreas Gohr    $pass = new PassHash();
12213a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1222b0855b11Sandi}
1223340756e4Sandi
1224a0b5b007SChris Smith/**
1225a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1226a0b5b007SChris Smith *
1227a0b5b007SChris Smith * @param string  $user       username
1228a0b5b007SChris Smith * @param string  $pass       encrypted password
1229a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1230ab5d26daSAndreas Gohr * @return bool
1231a0b5b007SChris Smith */
1232a0b5b007SChris Smithfunction auth_setCookie($user, $pass, $sticky) {
1233a0b5b007SChris Smith    global $conf;
1234e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1235a0b5b007SChris Smith    global $auth;
123679d00841SOliver Geisen    global $USERINFO;
1237a0b5b007SChris Smith
1238beca106aSAdrian Lang    if(!$auth) return false;
1239a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1240a0b5b007SChris Smith
1241a0b5b007SChris Smith    // set cookie
1242645c0a36SAndreas Gohr    $cookie    = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
124373ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1244c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
124573ab87deSGabriel Birke    setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
124655a71a16SGerrit Uitslag
1247a0b5b007SChris Smith    // set session
1248a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1249234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1250a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1251a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1252a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1253ab5d26daSAndreas Gohr
1254ab5d26daSAndreas Gohr    return true;
1255a0b5b007SChris Smith}
1256a0b5b007SChris Smith
1257645c0a36SAndreas Gohr/**
1258645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1259645c0a36SAndreas Gohr *
1260645c0a36SAndreas Gohr * @returns array
1261645c0a36SAndreas Gohr */
1262645c0a36SAndreas Gohrfunction auth_getCookie() {
1263c66972f2SAdrian Lang    if(!isset($_COOKIE[DOKU_COOKIE])) {
1264c66972f2SAdrian Lang        return array(null, null, null);
1265c66972f2SAdrian Lang    }
1266645c0a36SAndreas Gohr    list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
1267645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1268645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1269645c0a36SAndreas Gohr    $user   = base64_decode($user);
1270645c0a36SAndreas Gohr    return array($user, $sticky, $pass);
1271645c0a36SAndreas Gohr}
1272645c0a36SAndreas Gohr
1273e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1274