xref: /dokuwiki/inc/auth.php (revision e1d9dcc8b460b6f029ac9c8d5d3b8d23b6e73402)
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;
14*e1d9dcc8SAndreas Gohruse dokuwiki\Extension\AuthPlugin;
15*e1d9dcc8SAndreas Gohruse dokuwiki\Extension\Event;
16c3cc6e05SAndreas Gohr
17ebf97c8fSAndreas Gohrdefine('AUTH_NONE', 0);
18ebf97c8fSAndreas Gohrdefine('AUTH_READ', 1);
19ebf97c8fSAndreas Gohrdefine('AUTH_EDIT', 2);
20ebf97c8fSAndreas Gohrdefine('AUTH_CREATE', 4);
21ebf97c8fSAndreas Gohrdefine('AUTH_UPLOAD', 8);
22ebf97c8fSAndreas Gohrdefine('AUTH_DELETE', 16);
23ebf97c8fSAndreas Gohrdefine('AUTH_ADMIN', 255);
24ebf97c8fSAndreas Gohr
2516905344SAndreas Gohr/**
2616905344SAndreas Gohr * Initialize the auth system.
2716905344SAndreas Gohr *
2816905344SAndreas Gohr * This function is automatically called at the end of init.php
2916905344SAndreas Gohr *
3016905344SAndreas Gohr * This used to be the main() of the auth.php
3116905344SAndreas Gohr *
3216905344SAndreas Gohr * @todo backend loading maybe should be handled by the class autoloader
3316905344SAndreas Gohr * @todo maybe split into multiple functions at the XXX marked positions
34ab5d26daSAndreas Gohr * @triggers AUTH_LOGIN_CHECK
35ab5d26daSAndreas Gohr * @return bool
3616905344SAndreas Gohr */
3716905344SAndreas Gohrfunction auth_setup() {
38742c66f8Schris    global $conf;
39*e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
4003c4aec3Schris    global $auth;
41bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
42bcc94b2cSAndreas Gohr    global $INPUT;
439a9714acSDominik Eckelmann    global $AUTH_ACL;
449a9714acSDominik Eckelmann    global $lang;
4527058a05SMichael Hamann    /* @var Doku_Plugin_Controller $plugin_controller */
469c29eea5SJan Schumann    global $plugin_controller;
479a9714acSDominik Eckelmann    $AUTH_ACL = array();
4803c4aec3Schris
4916905344SAndreas Gohr    if(!$conf['useacl']) return false;
5016905344SAndreas Gohr
519c29eea5SJan Schumann    // try to load auth backend from plugins
529c29eea5SJan Schumann    foreach ($plugin_controller->getList('auth') as $plugin) {
539c29eea5SJan Schumann        if ($conf['authtype'] === $plugin) {
54f4476bd9SJan Schumann            $auth = $plugin_controller->load('auth', $plugin);
559c29eea5SJan Schumann            break;
569c29eea5SJan Schumann        }
579c29eea5SJan Schumann    }
588b06d178Schris
596416b708SMichael Hamann    if(!isset($auth) || !$auth){
603094e817SAndreas Gohr        msg($lang['authtempfail'], -1);
613094e817SAndreas Gohr        return false;
623094e817SAndreas Gohr    }
638b06d178Schris
646416b708SMichael Hamann    if ($auth->success == false) {
650f4f4adfSAndreas Gohr        // degrade to unauthenticated user
66d2dde4ebSMatthias Grimm        unset($auth);
670f4f4adfSAndreas Gohr        auth_logoff();
68cd52f92dSchris        msg($lang['authtempfail'], -1);
696416b708SMichael Hamann        return false;
70d2dde4ebSMatthias Grimm    }
7116905344SAndreas Gohr
7216905344SAndreas Gohr    // do the login either by cookie or provided credentials XXX
73bcc94b2cSAndreas Gohr    $INPUT->set('http_credentials', false);
74bcc94b2cSAndreas Gohr    if(!$conf['rememberme']) $INPUT->set('r', false);
75bbbd6568SAndreas Gohr
76b2665af7SMichael Hamann    // handle renamed HTTP_AUTHORIZATION variable (can happen when a fix like
77b2665af7SMichael Hamann    // the one presented at
78b2665af7SMichael Hamann    // http://www.besthostratings.com/articles/http-auth-php-cgi.html is used
79b2665af7SMichael Hamann    // for enabling HTTP authentication with CGI/SuExec)
80b2665af7SMichael Hamann    if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
81b2665af7SMichael Hamann        $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
82528ddc7cSAndreas Gohr    // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
8306156f3cSAndreas Gohr    if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
84528ddc7cSAndreas Gohr        list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
85528ddc7cSAndreas Gohr            explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
86528ddc7cSAndreas Gohr    }
87528ddc7cSAndreas Gohr
881e8c9c90SAndreas Gohr    // if no credentials were given try to use HTTP auth (for SSO)
89bcc94b2cSAndreas Gohr    if(!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])) {
90bcc94b2cSAndreas Gohr        $INPUT->set('u', $_SERVER['PHP_AUTH_USER']);
91bcc94b2cSAndreas Gohr        $INPUT->set('p', $_SERVER['PHP_AUTH_PW']);
92bcc94b2cSAndreas Gohr        $INPUT->set('http_credentials', true);
931e8c9c90SAndreas Gohr    }
941e8c9c90SAndreas Gohr
95395c2f0fSAndreas Gohr    // apply cleaning (auth specific user names, remove control chars)
9693a7873eSAndreas Gohr    if (true === $auth->success) {
97395c2f0fSAndreas Gohr        $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
98395c2f0fSAndreas Gohr        $INPUT->set('p', stripctl($INPUT->str('p')));
99f4476bd9SJan Schumann    }
100191bb90aSAndreas Gohr
1018eca974cSAndreas Gohr    if(!is_null($auth) && $auth->canDo('external')) {
102f13fa892SAndreas Gohr        // external trust mechanism in place
103bcc94b2cSAndreas Gohr        $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
104f5cb575dSAndreas Gohr    } else {
1056080c584SRobin Gareus        $evdata = array(
106bcc94b2cSAndreas Gohr            'user'     => $INPUT->str('u'),
107bcc94b2cSAndreas Gohr            'password' => $INPUT->str('p'),
108bcc94b2cSAndreas Gohr            'sticky'   => $INPUT->bool('r'),
109bcc94b2cSAndreas Gohr            'silent'   => $INPUT->bool('http_credentials')
1106080c584SRobin Gareus        );
111b5ee21aaSAdrian Lang        trigger_event('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
112f5cb575dSAndreas Gohr    }
113f5cb575dSAndreas Gohr
11416905344SAndreas Gohr    //load ACL into a global array XXX
11575c93b77SAndreas Gohr    $AUTH_ACL = auth_loadACL();
116ab5d26daSAndreas Gohr
117ab5d26daSAndreas Gohr    return true;
11875c93b77SAndreas Gohr}
11975c93b77SAndreas Gohr
12075c93b77SAndreas Gohr/**
12175c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards
12275c93b77SAndreas Gohr *
12375c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12442ea7f44SGerrit Uitslag *
125ab5d26daSAndreas Gohr * @return array
12675c93b77SAndreas Gohr */
12775c93b77SAndreas Gohrfunction auth_loadACL() {
12875c93b77SAndreas Gohr    global $config_cascade;
129b78bf706Sromain    global $USERINFO;
130585bf44eSChristopher Smith    /* @var Input $INPUT */
131585bf44eSChristopher Smith    global $INPUT;
13275c93b77SAndreas Gohr
13375c93b77SAndreas Gohr    if(!is_readable($config_cascade['acl']['default'])) return array();
13475c93b77SAndreas Gohr
13575c93b77SAndreas Gohr    $acl = file($config_cascade['acl']['default']);
13675c93b77SAndreas Gohr
13732e82180SAndreas Gohr    $out = array();
1389ce556d2SAndreas Gohr    foreach($acl as $line) {
1399ce556d2SAndreas Gohr        $line = trim($line);
140443e135dSChristopher Smith        if(empty($line) || ($line{0} == '#')) continue; // skip blank lines & comments
14121c3090aSChristopher Smith        list($id,$rest) = preg_split('/[ \t]+/',$line,2);
14232e82180SAndreas Gohr
143443e135dSChristopher Smith        // substitute user wildcard first (its 1:1)
144ad3d68d7SChristopher Smith        if(strstr($line, '%USER%')){
145ad3d68d7SChristopher Smith            // if user is not logged in, this ACL line is meaningless - skip it
146585bf44eSChristopher Smith            if (!$INPUT->server->has('REMOTE_USER')) continue;
147ad3d68d7SChristopher Smith
148585bf44eSChristopher Smith            $id   = str_replace('%USER%',cleanID($INPUT->server->str('REMOTE_USER')),$id);
149585bf44eSChristopher Smith            $rest = str_replace('%USER%',auth_nameencode($INPUT->server->str('REMOTE_USER')),$rest);
150ad3d68d7SChristopher Smith        }
151ad3d68d7SChristopher Smith
152ad3d68d7SChristopher Smith        // substitute group wildcard (its 1:m)
1539ce556d2SAndreas Gohr        if(strstr($line, '%GROUP%')){
154ad3d68d7SChristopher Smith            // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
1559ce556d2SAndreas Gohr            foreach((array) $USERINFO['grps'] as $grp){
156b78bf706Sromain                $nid   = str_replace('%GROUP%',cleanID($grp),$id);
15732e82180SAndreas Gohr                $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest);
15832e82180SAndreas Gohr                $out[] = "$nid\t$nrest";
159b78bf706Sromain            }
16032e82180SAndreas Gohr        } else {
16132e82180SAndreas Gohr            $out[] = "$id\t$rest";
162a8fe108bSGuy Brand        }
16311799630Sandi    }
1649ce556d2SAndreas Gohr
16532e82180SAndreas Gohr    return $out;
166f3f0262cSandi}
167f3f0262cSandi
168ab5d26daSAndreas Gohr/**
169ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK
170ab5d26daSAndreas Gohr *
17142ea7f44SGerrit Uitslag * @param array $evdata
172ab5d26daSAndreas Gohr * @return bool
173ab5d26daSAndreas Gohr */
174b5ee21aaSAdrian Langfunction auth_login_wrapper($evdata) {
175ab5d26daSAndreas Gohr    return auth_login(
176ab5d26daSAndreas Gohr        $evdata['user'],
177b5ee21aaSAdrian Lang        $evdata['password'],
178b5ee21aaSAdrian Lang        $evdata['sticky'],
179ab5d26daSAndreas Gohr        $evdata['silent']
180ab5d26daSAndreas Gohr    );
181b5ee21aaSAdrian Lang}
182b5ee21aaSAdrian Lang
183f3f0262cSandi/**
184f3f0262cSandi * This tries to login the user based on the sent auth credentials
185f3f0262cSandi *
186f3f0262cSandi * The authentication works like this: if a username was given
18715fae107Sandi * a new login is assumed and user/password are checked. If they
18815fae107Sandi * are correct the password is encrypted with blowfish and stored
18915fae107Sandi * together with the username in a cookie - the same info is stored
19015fae107Sandi * in the session, too. Additonally a browserID is stored in the
19115fae107Sandi * session.
19215fae107Sandi *
19315fae107Sandi * If no username was given the cookie is checked: if the username,
19415fae107Sandi * crypted password and browserID match between session and cookie
19515fae107Sandi * no further testing is done and the user is accepted
19615fae107Sandi *
19715fae107Sandi * If a cookie was found but no session info was availabe the
198136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
19915fae107Sandi * together with username rechecked by calling this function again.
200f3f0262cSandi *
201f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
202f3f0262cSandi * are set.
20315fae107Sandi *
20415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
20515fae107Sandi *
20615fae107Sandi * @param   string  $user    Username
20715fae107Sandi * @param   string  $pass    Cleartext Password
20815fae107Sandi * @param   bool    $sticky  Cookie should not expire
209f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
21015fae107Sandi * @return  bool             true on successful auth
211f3f0262cSandi */
212f112c2faSAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false) {
213f3f0262cSandi    global $USERINFO;
214f3f0262cSandi    global $conf;
215f3f0262cSandi    global $lang;
216*e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
217cd52f92dSchris    global $auth;
218585bf44eSChristopher Smith    /* @var Input $INPUT */
219585bf44eSChristopher Smith    global $INPUT;
220ab5d26daSAndreas Gohr
221132bdbfeSandi    $sticky ? $sticky = true : $sticky = false; //sanity check
222f3f0262cSandi
223beca106aSAdrian Lang    if(!$auth) return false;
224beca106aSAdrian Lang
225bbbd6568SAndreas Gohr    if(!empty($user)) {
226132bdbfeSandi        //usual login
2275e9e1054SAndreas Gohr        if(!empty($pass) && $auth->checkPass($user, $pass)) {
228132bdbfeSandi            // make logininfo globally available
229585bf44eSChristopher Smith            $INPUT->server->set('REMOTE_USER', $user);
23030d544a4SMichael Hamann            $secret                 = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
23104369c3eSMichael Hamann            auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
232132bdbfeSandi            return true;
233f3f0262cSandi        } else {
234f3f0262cSandi            //invalid credentials - log off
235f8b1e4e7SAndreas Gohr            if(!$silent) {
236f8b1e4e7SAndreas Gohr                http_status(403, 'Login failed');
237f8b1e4e7SAndreas Gohr                msg($lang['badlogin'], -1);
238f8b1e4e7SAndreas Gohr            }
239f3f0262cSandi            auth_logoff();
240132bdbfeSandi            return false;
241f3f0262cSandi        }
242f3f0262cSandi    } else {
243132bdbfeSandi        // read cookie information
244645c0a36SAndreas Gohr        list($user, $sticky, $pass) = auth_getCookie();
245132bdbfeSandi        if($user && $pass) {
246132bdbfeSandi            // we got a cookie - see if we can trust it
247fa7c70ffSAdrian Lang
248fa7c70ffSAdrian Lang            // get session info
249fa7c70ffSAdrian Lang            $session = $_SESSION[DOKU_COOKIE]['auth'];
250132bdbfeSandi            if(isset($session) &&
2517172dbc0SAndreas Gohr                $auth->useSessionCache($user) &&
2524c989037SChris Smith                ($session['time'] >= time() - $conf['auth_security_timeout']) &&
253132bdbfeSandi                ($session['user'] == $user) &&
254234ce57eSAndreas Gohr                ($session['pass'] == sha1($pass)) && //still crypted
255ab5d26daSAndreas Gohr                ($session['buid'] == auth_browseruid())
256ab5d26daSAndreas Gohr            ) {
257234ce57eSAndreas Gohr
258132bdbfeSandi                // he has session, cookie and browser right - let him in
259585bf44eSChristopher Smith                $INPUT->server->set('REMOTE_USER', $user);
260132bdbfeSandi                $USERINFO               = $session['info']; //FIXME move all references to session
261132bdbfeSandi                return true;
262132bdbfeSandi            }
263f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
26430d544a4SMichael Hamann            $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
26504369c3eSMichael Hamann            $pass   = auth_decrypt($pass, $secret);
266f112c2faSAndreas Gohr            return auth_login($user, $pass, $sticky, true);
267132bdbfeSandi        }
268132bdbfeSandi    }
269f3f0262cSandi    //just to be sure
270883179a4SAndreas Gohr    auth_logoff(true);
271132bdbfeSandi    return false;
272f3f0262cSandi}
273132bdbfeSandi
274132bdbfeSandi/**
275136ce040Sandi * Builds a pseudo UID from browser and IP data
276132bdbfeSandi *
277132bdbfeSandi * This is neither unique nor unfakable - still it adds some
278136ce040Sandi * security. Using the first part of the IP makes sure
27980b4f376SAndreas Gohr * proxy farms like AOLs are still okay.
28015fae107Sandi *
28115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
28215fae107Sandi *
28315fae107Sandi * @return  string  a MD5 sum of various browser headers
284132bdbfeSandi */
285132bdbfeSandifunction auth_browseruid() {
286585bf44eSChristopher Smith    /* @var Input $INPUT */
287585bf44eSChristopher Smith    global $INPUT;
288585bf44eSChristopher Smith
2892f9daf16SAndreas Gohr    $ip  = clientIP(true);
290132bdbfeSandi    $uid = '';
291585bf44eSChristopher Smith    $uid .= $INPUT->server->str('HTTP_USER_AGENT');
292585bf44eSChristopher Smith    $uid .= $INPUT->server->str('HTTP_ACCEPT_CHARSET');
2932f9daf16SAndreas Gohr    $uid .= substr($ip, 0, strpos($ip, '.'));
29480b4f376SAndreas Gohr    $uid = strtolower($uid);
295132bdbfeSandi    return md5($uid);
296132bdbfeSandi}
297132bdbfeSandi
298132bdbfeSandi/**
299132bdbfeSandi * Creates a random key to encrypt the password in cookies
30015fae107Sandi *
30115fae107Sandi * This function tries to read the password for encrypting
30298407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
30315fae107Sandi * if no such file is found a random key is created and
30415fae107Sandi * and stored in this file.
30515fae107Sandi *
30615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
30742ea7f44SGerrit Uitslag *
30832ed2b36SAndreas Gohr * @param   bool $addsession if true, the sessionid is added to the salt
30930d544a4SMichael Hamann * @param   bool $secure     if security is more important than keeping the old value
31015fae107Sandi * @return  string
311132bdbfeSandi */
31230d544a4SMichael Hamannfunction auth_cookiesalt($addsession = false, $secure = false) {
313a1fe3c9cSMichael Große    if (defined('SIMPLE_TEST')) {
314fe745becSMichael Große        return 'test';
315a1fe3c9cSMichael Große    }
316132bdbfeSandi    global $conf;
31798407a7aSandi    $file = $conf['metadir'].'/_htcookiesalt';
31830d544a4SMichael Hamann    if ($secure || !file_exists($file)) {
31930d544a4SMichael Hamann        $file = $conf['metadir'].'/_htcookiesalt2';
32030d544a4SMichael Hamann    }
321132bdbfeSandi    $salt = io_readFile($file);
322132bdbfeSandi    if(empty($salt)) {
32330d544a4SMichael Hamann        $salt = bin2hex(auth_randombytes(64));
324132bdbfeSandi        io_saveFile($file, $salt);
325132bdbfeSandi    }
32632ed2b36SAndreas Gohr    if($addsession) {
32732ed2b36SAndreas Gohr        $salt .= session_id();
32832ed2b36SAndreas Gohr    }
329132bdbfeSandi    return $salt;
330f3f0262cSandi}
331f3f0262cSandi
332f3f0262cSandi/**
3337a33d2f8SNiklas Keller * Return cryptographically secure random bytes.
334483b6238SMichael Hamann *
3357a33d2f8SNiklas Keller * @author Niklas Keller <me@kelunik.com>
33642ea7f44SGerrit Uitslag *
3377a33d2f8SNiklas Keller * @param int $length number of bytes
3387a33d2f8SNiklas Keller * @return string cryptographically secure random bytes
339483b6238SMichael Hamann */
340483b6238SMichael Hamannfunction auth_randombytes($length) {
3417a33d2f8SNiklas Keller    return random_bytes($length);
342483b6238SMichael Hamann}
343483b6238SMichael Hamann
344483b6238SMichael Hamann/**
3457a33d2f8SNiklas Keller * Cryptographically secure random number generator.
346483b6238SMichael Hamann *
3477a33d2f8SNiklas Keller * @author Niklas Keller <me@kelunik.com>
34842ea7f44SGerrit Uitslag *
349483b6238SMichael Hamann * @param int $min
350483b6238SMichael Hamann * @param int $max
351483b6238SMichael Hamann * @return int
352483b6238SMichael Hamann */
353483b6238SMichael Hamannfunction auth_random($min, $max) {
3547a33d2f8SNiklas Keller    return random_int($min, $max);
355483b6238SMichael Hamann}
356483b6238SMichael Hamann
357483b6238SMichael Hamann/**
35804369c3eSMichael Hamann * Encrypt data using the given secret using AES
35904369c3eSMichael Hamann *
36004369c3eSMichael Hamann * The mode is CBC with a random initialization vector, the key is derived
36104369c3eSMichael Hamann * using pbkdf2.
36204369c3eSMichael Hamann *
36304369c3eSMichael Hamann * @param string $data   The data that shall be encrypted
36404369c3eSMichael Hamann * @param string $secret The secret/password that shall be used
36504369c3eSMichael Hamann * @return string The ciphertext
36604369c3eSMichael Hamann */
36704369c3eSMichael Hamannfunction auth_encrypt($data, $secret) {
36804369c3eSMichael Hamann    $iv     = auth_randombytes(16);
3691af2f135SAndreas Gohr    $cipher = new \phpseclib\Crypt\AES();
37004369c3eSMichael Hamann    $cipher->setPassword($secret);
37104369c3eSMichael Hamann
3727b650cefSMichael Hamann    /*
3737b650cefSMichael Hamann    this uses the encrypted IV as IV as suggested in
3747b650cefSMichael Hamann    http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
3757b650cefSMichael Hamann    for unique but necessarily random IVs. The resulting ciphertext is
3767b650cefSMichael Hamann    compatible to ciphertext that was created using a "normal" IV.
3777b650cefSMichael Hamann    */
37804369c3eSMichael Hamann    return $cipher->encrypt($iv.$data);
37904369c3eSMichael Hamann}
38004369c3eSMichael Hamann
38104369c3eSMichael Hamann/**
38204369c3eSMichael Hamann * Decrypt the given AES ciphertext
38304369c3eSMichael Hamann *
38404369c3eSMichael Hamann * The mode is CBC, the key is derived using pbkdf2
38504369c3eSMichael Hamann *
38604369c3eSMichael Hamann * @param string $ciphertext The encrypted data
38704369c3eSMichael Hamann * @param string $secret     The secret/password that shall be used
38804369c3eSMichael Hamann * @return string The decrypted data
38904369c3eSMichael Hamann */
39004369c3eSMichael Hamannfunction auth_decrypt($ciphertext, $secret) {
3917b650cefSMichael Hamann    $iv     = substr($ciphertext, 0, 16);
3921af2f135SAndreas Gohr    $cipher = new \phpseclib\Crypt\AES();
39304369c3eSMichael Hamann    $cipher->setPassword($secret);
3947b650cefSMichael Hamann    $cipher->setIV($iv);
39504369c3eSMichael Hamann
3967b650cefSMichael Hamann    return $cipher->decrypt(substr($ciphertext, 16));
39704369c3eSMichael Hamann}
39804369c3eSMichael Hamann
39904369c3eSMichael Hamann/**
400883179a4SAndreas Gohr * Log out the current user
401883179a4SAndreas Gohr *
402f3f0262cSandi * This clears all authentication data and thus log the user
403883179a4SAndreas Gohr * off. It also clears session data.
40415fae107Sandi *
40515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
40642ea7f44SGerrit Uitslag *
407883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
408f3f0262cSandi */
409883179a4SAndreas Gohrfunction auth_logoff($keepbc = false) {
410f3f0262cSandi    global $conf;
411f3f0262cSandi    global $USERINFO;
412*e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
4135298a619SAndreas Gohr    global $auth;
414585bf44eSChristopher Smith    /* @var Input $INPUT */
415585bf44eSChristopher Smith    global $INPUT;
41637065e65Sandi
417d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
418e9621d07SAndreas Gohr    @session_start();
419e9621d07SAndreas Gohr
420e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
421e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
422e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
423e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
424e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
425e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
426883179a4SAndreas Gohr    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
427e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
428585bf44eSChristopher Smith    $INPUT->server->remove('REMOTE_USER');
429132bdbfeSandi    $USERINFO = null; //FIXME
430f5c6743cSAndreas Gohr
43173ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
43273ab87deSGabriel Birke    setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
4335298a619SAndreas Gohr
434880f62faSAndreas Gohr    if($auth) $auth->logOff();
435f3f0262cSandi}
436f3f0262cSandi
437f3f0262cSandi/**
438f8cc712eSAndreas Gohr * Check if a user is a manager
439f8cc712eSAndreas Gohr *
440f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
441f8cc712eSAndreas Gohr * user.
442f8cc712eSAndreas Gohr *
443f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
444f8cc712eSAndreas Gohr *
445f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
446f8cc712eSAndreas Gohr * @see    auth_isadmin
44742ea7f44SGerrit Uitslag *
448ab5d26daSAndreas Gohr * @param  string $user       Username
449ab5d26daSAndreas Gohr * @param  array  $groups     List of groups the user is in
450ab5d26daSAndreas Gohr * @param  bool   $adminonly  when true checks if user is admin
451ab5d26daSAndreas Gohr * @return bool
452f8cc712eSAndreas Gohr */
453f8cc712eSAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false) {
454f8cc712eSAndreas Gohr    global $conf;
455f8cc712eSAndreas Gohr    global $USERINFO;
456*e1d9dcc8SAndreas 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)) {
471d6dc956fSAndreas Gohr        $groups = (array) $USERINFO['grps'];
472e259aa79SAndreas Gohr    }
473e259aa79SAndreas Gohr
474d6dc956fSAndreas Gohr    // check superuser match
475d6dc956fSAndreas Gohr    if(auth_isMember($conf['superuser'], $user, $groups)) return true;
476d6dc956fSAndreas Gohr    if($adminonly) return false;
477e259aa79SAndreas Gohr    // check managers
478d6dc956fSAndreas Gohr    if(auth_isMember($conf['manager'], $user, $groups)) return true;
47900ce12daSChris Smith
480f8cc712eSAndreas Gohr    return false;
481f8cc712eSAndreas Gohr}
482f8cc712eSAndreas Gohr
483f8cc712eSAndreas Gohr/**
484f8cc712eSAndreas Gohr * Check if a user is admin
485f8cc712eSAndreas Gohr *
486f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
487f8cc712eSAndreas Gohr *
488f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
489f8cc712eSAndreas Gohr *
490f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
491ab5d26daSAndreas Gohr * @see auth_ismanager()
49242ea7f44SGerrit Uitslag *
493ab5d26daSAndreas Gohr * @param  string $user       Username
494ab5d26daSAndreas Gohr * @param  array  $groups     List of groups the user is in
495ab5d26daSAndreas Gohr * @return bool
496f8cc712eSAndreas Gohr */
497f8cc712eSAndreas Gohrfunction auth_isadmin($user = null, $groups = null) {
498f8cc712eSAndreas Gohr    return auth_ismanager($user, $groups, true);
499f8cc712eSAndreas Gohr}
500f8cc712eSAndreas Gohr
501d6dc956fSAndreas Gohr/**
502d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
503d6dc956fSAndreas Gohr * users and groups to determine membership status
504d6dc956fSAndreas Gohr *
505d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
506d6dc956fSAndreas Gohr *
50742ea7f44SGerrit Uitslag * @param string $memberlist commaseparated list of allowed users and groups
50842ea7f44SGerrit Uitslag * @param string $user       user to match against
50942ea7f44SGerrit Uitslag * @param array  $groups     groups the user is member of
5105446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
511d6dc956fSAndreas Gohr */
512d6dc956fSAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups) {
513*e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
514d6dc956fSAndreas Gohr    global $auth;
515d6dc956fSAndreas Gohr    if(!$auth) return false;
516d6dc956fSAndreas Gohr
517d6dc956fSAndreas Gohr    // clean user and groups
5184f56ecbfSAdrian Lang    if(!$auth->isCaseSensitive()) {
519d6dc956fSAndreas Gohr        $user   = utf8_strtolower($user);
520d6dc956fSAndreas Gohr        $groups = array_map('utf8_strtolower', $groups);
521d6dc956fSAndreas Gohr    }
522d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
523d6dc956fSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), $groups);
524d6dc956fSAndreas Gohr
525d6dc956fSAndreas Gohr    // extract the memberlist
526d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
527d6dc956fSAndreas Gohr    $members = array_map('trim', $members);
528d6dc956fSAndreas Gohr    $members = array_unique($members);
529d6dc956fSAndreas Gohr    $members = array_filter($members);
530d6dc956fSAndreas Gohr
531d6dc956fSAndreas Gohr    // compare cleaned values
532d6dc956fSAndreas Gohr    foreach($members as $member) {
533e5204a12SJurgen Hart        if($member == '@ALL' ) return true;
5344f56ecbfSAdrian Lang        if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member);
535d6dc956fSAndreas Gohr        if($member[0] == '@') {
536d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
537d6dc956fSAndreas Gohr            if(in_array($member, $groups)) return true;
538d6dc956fSAndreas Gohr        } else {
539d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
540d6dc956fSAndreas Gohr            if($member == $user) return true;
541d6dc956fSAndreas Gohr        }
542d6dc956fSAndreas Gohr    }
543d6dc956fSAndreas Gohr
544d6dc956fSAndreas Gohr    // still here? not a member!
545d6dc956fSAndreas Gohr    return false;
546d6dc956fSAndreas Gohr}
547d6dc956fSAndreas Gohr
548f8cc712eSAndreas Gohr/**
54915fae107Sandi * Convinience function for auth_aclcheck()
55015fae107Sandi *
55115fae107Sandi * This checks the permissions for the current user
55215fae107Sandi *
55315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
55415fae107Sandi *
5551698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
55615fae107Sandi * @return int          permission level
557f3f0262cSandi */
558f3f0262cSandifunction auth_quickaclcheck($id) {
559f3f0262cSandi    global $conf;
560f3f0262cSandi    global $USERINFO;
561585bf44eSChristopher Smith    /* @var Input $INPUT */
562585bf44eSChristopher Smith    global $INPUT;
563f3f0262cSandi    # if no ACL is used always return upload rights
564f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
565585bf44eSChristopher Smith    return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), $USERINFO['grps']);
566f3f0262cSandi}
567f3f0262cSandi
568f3f0262cSandi/**
569c17acc9fSAndreas Gohr * Returns the maximum rights a user has for the given ID or its namespace
57015fae107Sandi *
57115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
57242ea7f44SGerrit Uitslag *
573c17acc9fSAndreas Gohr * @triggers AUTH_ACL_CHECK
5741698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
57515fae107Sandi * @param  string       $user   Username
5763272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
57715fae107Sandi * @return int             permission level
578f3f0262cSandi */
579f3f0262cSandifunction auth_aclcheck($id, $user, $groups) {
580c17acc9fSAndreas Gohr    $data = array(
581c17acc9fSAndreas Gohr        'id'     => $id,
582c17acc9fSAndreas Gohr        'user'   => $user,
583c17acc9fSAndreas Gohr        'groups' => $groups
584c17acc9fSAndreas Gohr    );
585c17acc9fSAndreas Gohr
586c17acc9fSAndreas Gohr    return trigger_event('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
587c17acc9fSAndreas Gohr}
588c17acc9fSAndreas Gohr
589c17acc9fSAndreas Gohr/**
590c17acc9fSAndreas Gohr * default ACL check method
591c17acc9fSAndreas Gohr *
592c17acc9fSAndreas Gohr * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
593c17acc9fSAndreas Gohr *
594c17acc9fSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
59542ea7f44SGerrit Uitslag *
596c17acc9fSAndreas Gohr * @param  array $data event data
597c17acc9fSAndreas Gohr * @return int   permission level
598c17acc9fSAndreas Gohr */
599c17acc9fSAndreas Gohrfunction auth_aclcheck_cb($data) {
600c17acc9fSAndreas Gohr    $id     =& $data['id'];
601c17acc9fSAndreas Gohr    $user   =& $data['user'];
602c17acc9fSAndreas Gohr    $groups =& $data['groups'];
603c17acc9fSAndreas Gohr
604f3f0262cSandi    global $conf;
605f3f0262cSandi    global $AUTH_ACL;
606*e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
607d752aedeSAndreas Gohr    global $auth;
608f3f0262cSandi
60985d03f68SAndreas Gohr    // if no ACL is used always return upload rights
610f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
611beca106aSAdrian Lang    if(!$auth) return AUTH_NONE;
612f3f0262cSandi
613074cf26bSandi    //make sure groups is an array
614074cf26bSandi    if(!is_array($groups)) $groups = array();
615074cf26bSandi
61685d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
617ab5d26daSAndreas Gohr    if(auth_isadmin($user, $groups)) {
618ab5d26daSAndreas Gohr        return AUTH_ADMIN;
619ab5d26daSAndreas Gohr    }
62085d03f68SAndreas Gohr
621eb3ce0d5SKazutaka Miyasaka    if(!$auth->isCaseSensitive()) {
622eb3ce0d5SKazutaka Miyasaka        $user   = utf8_strtolower($user);
623eb3ce0d5SKazutaka Miyasaka        $groups = array_map('utf8_strtolower', $groups);
624eb3ce0d5SKazutaka Miyasaka    }
62537ff2261SSascha Klopp    $user   = auth_nameencode($auth->cleanUser($user));
626d752aedeSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
62785d03f68SAndreas Gohr
6286c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
62937ff2261SSascha Klopp    foreach($groups as &$group) {
63037ff2261SSascha Klopp        $group = '@'.auth_nameencode($group);
63110a76f6fSfrank    }
63210a76f6fSfrank
633f3f0262cSandi    $ns   = getNS($id);
634f3f0262cSandi    $perm = -1;
635f3f0262cSandi
636f3f0262cSandi    //add ALL group
637f3f0262cSandi    $groups[] = '@ALL';
63837ff2261SSascha Klopp
639f3f0262cSandi    //add User
64034aeb4afSAndreas Gohr    if($user) $groups[] = $user;
641f3f0262cSandi
642f3f0262cSandi    //check exact match first
64321c3090aSChristopher Smith    $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
644f3f0262cSandi    if(count($matches)) {
645f3f0262cSandi        foreach($matches as $match) {
646f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
64721c3090aSChristopher Smith            $acl   = preg_split('/[ \t]+/', $match);
648eb3ce0d5SKazutaka Miyasaka            if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
649eb3ce0d5SKazutaka Miyasaka                $acl[1] = utf8_strtolower($acl[1]);
650eb3ce0d5SKazutaka Miyasaka            }
65148d7b7a6SDominik Eckelmann            if(!in_array($acl[1], $groups)) {
65248d7b7a6SDominik Eckelmann                continue;
65348d7b7a6SDominik Eckelmann            }
6548ef6b7caSandi            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
655f3f0262cSandi            if($acl[2] > $perm) {
656f3f0262cSandi                $perm = $acl[2];
657f3f0262cSandi            }
658f3f0262cSandi        }
659f3f0262cSandi        if($perm > -1) {
660f3f0262cSandi            //we had a match - return it
661def492a2SGuillaume Turri            return (int) $perm;
662f3f0262cSandi        }
663f3f0262cSandi    }
664f3f0262cSandi
665f3f0262cSandi    //still here? do the namespace checks
666f3f0262cSandi    if($ns) {
6673e304b55SMichael Hamann        $path = $ns.':*';
668f3f0262cSandi    } else {
6693e304b55SMichael Hamann        $path = '*'; //root document
670f3f0262cSandi    }
671f3f0262cSandi
672f3f0262cSandi    do {
67321c3090aSChristopher Smith        $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
674f3f0262cSandi        if(count($matches)) {
675f3f0262cSandi            foreach($matches as $match) {
676f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
67721c3090aSChristopher Smith                $acl   = preg_split('/[ \t]+/', $match);
678eb3ce0d5SKazutaka Miyasaka                if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
679eb3ce0d5SKazutaka Miyasaka                    $acl[1] = utf8_strtolower($acl[1]);
680eb3ce0d5SKazutaka Miyasaka                }
68148d7b7a6SDominik Eckelmann                if(!in_array($acl[1], $groups)) {
68248d7b7a6SDominik Eckelmann                    continue;
68348d7b7a6SDominik Eckelmann                }
6848ef6b7caSandi                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
685f3f0262cSandi                if($acl[2] > $perm) {
686f3f0262cSandi                    $perm = $acl[2];
687f3f0262cSandi                }
688f3f0262cSandi            }
689f3f0262cSandi            //we had a match - return it
69048d7b7a6SDominik Eckelmann            if($perm != -1) {
691def492a2SGuillaume Turri                return (int) $perm;
692f3f0262cSandi            }
69348d7b7a6SDominik Eckelmann        }
694f3f0262cSandi        //get next higher namespace
695f3f0262cSandi        $ns = getNS($ns);
696f3f0262cSandi
6973e304b55SMichael Hamann        if($path != '*') {
6983e304b55SMichael Hamann            $path = $ns.':*';
6993e304b55SMichael Hamann            if($path == ':*') $path = '*';
700f3f0262cSandi        } else {
701f3f0262cSandi            //we did this already
702f3f0262cSandi            //looks like there is something wrong with the ACL
703f3f0262cSandi            //break here
704d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
705d5ce66f6SAndreas Gohr            return AUTH_NONE;
706f3f0262cSandi        }
707f3f0262cSandi    } while(1); //this should never loop endless
708ab5d26daSAndreas Gohr    return AUTH_NONE;
709f3f0262cSandi}
710f3f0262cSandi
711f3f0262cSandi/**
7126c2bb100SAndreas Gohr * Encode ASCII special chars
7136c2bb100SAndreas Gohr *
7146c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
7156c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
7166c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
7176c2bb100SAndreas Gohr * urlencoding!).
7186c2bb100SAndreas Gohr *
7196c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
7206c2bb100SAndreas Gohr *
7216c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
7226c2bb100SAndreas Gohr * @see rawurldecode()
72342ea7f44SGerrit Uitslag *
72442ea7f44SGerrit Uitslag * @param string $name
72542ea7f44SGerrit Uitslag * @param bool $skip_group
72642ea7f44SGerrit Uitslag * @return string
7276c2bb100SAndreas Gohr */
728e838fc2eSAndreas Gohrfunction auth_nameencode($name, $skip_group = false) {
729a424cd8eSchris    global $cache_authname;
730a424cd8eSchris    $cache =& $cache_authname;
73131784267SAndreas Gohr    $name  = (string) $name;
732a424cd8eSchris
73380601d26SAndreas Gohr    // never encode wildcard FS#1955
73480601d26SAndreas Gohr    if($name == '%USER%') return $name;
735b78bf706Sromain    if($name == '%GROUP%') return $name;
73680601d26SAndreas Gohr
737a424cd8eSchris    if(!isset($cache[$name][$skip_group])) {
738e838fc2eSAndreas Gohr        if($skip_group && $name{0} == '@') {
73930f6faf0SChristopher Smith            $cache[$name][$skip_group] = '@'.preg_replace_callback(
74030f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
74130f6faf0SChristopher Smith                'auth_nameencode_callback', substr($name, 1)
742ab5d26daSAndreas Gohr            );
743e838fc2eSAndreas Gohr        } else {
74430f6faf0SChristopher Smith            $cache[$name][$skip_group] = preg_replace_callback(
74530f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
74630f6faf0SChristopher Smith                'auth_nameencode_callback', $name
747ab5d26daSAndreas Gohr            );
748e838fc2eSAndreas Gohr        }
7496c2bb100SAndreas Gohr    }
7506c2bb100SAndreas Gohr
751a424cd8eSchris    return $cache[$name][$skip_group];
752a424cd8eSchris}
753a424cd8eSchris
75404d68ae4SGerrit Uitslag/**
75504d68ae4SGerrit Uitslag * callback encodes the matches
75604d68ae4SGerrit Uitslag *
75704d68ae4SGerrit Uitslag * @param array $matches first complete match, next matching subpatterms
75804d68ae4SGerrit Uitslag * @return string
75904d68ae4SGerrit Uitslag */
76030f6faf0SChristopher Smithfunction auth_nameencode_callback($matches) {
76130f6faf0SChristopher Smith    return '%'.dechex(ord(substr($matches[1],-1)));
76230f6faf0SChristopher Smith}
76330f6faf0SChristopher Smith
7646c2bb100SAndreas Gohr/**
765f3f0262cSandi * Create a pronouncable password
766f3f0262cSandi *
7678a285f7fSAndreas Gohr * The $foruser variable might be used by plugins to run additional password
7688a285f7fSAndreas Gohr * policy checks, but is not used by the default implementation
7698a285f7fSAndreas Gohr *
77015fae107Sandi * @author   Andreas Gohr <andi@splitbrain.org>
77115fae107Sandi * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
7728a285f7fSAndreas Gohr * @triggers AUTH_PASSWORD_GENERATE
77315fae107Sandi *
7748a285f7fSAndreas Gohr * @param  string $foruser username for which the password is generated
77515fae107Sandi * @return string  pronouncable password
776f3f0262cSandi */
7778a285f7fSAndreas Gohrfunction auth_pwgen($foruser = '') {
7788a285f7fSAndreas Gohr    $data = array(
779d628dcf3SAndreas Gohr        'password' => '',
780d628dcf3SAndreas Gohr        'foruser'  => $foruser
7818a285f7fSAndreas Gohr    );
7828a285f7fSAndreas Gohr
783*e1d9dcc8SAndreas Gohr    $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
7848a285f7fSAndreas Gohr    if($evt->advise_before(true)) {
785f3f0262cSandi        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
786f3f0262cSandi        $v = 'aeiou'; //vowels
787f3f0262cSandi        $a = $c.$v; //both
788987c8d26SAndreas Gohr        $s = '!$%&?+*~#-_:.;,'; // specials
789f3f0262cSandi
790987c8d26SAndreas Gohr        //use thre syllables...
791987c8d26SAndreas Gohr        for($i = 0; $i < 3; $i++) {
792483b6238SMichael Hamann            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
793483b6238SMichael Hamann            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
794483b6238SMichael Hamann            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
795f3f0262cSandi        }
796987c8d26SAndreas Gohr        //... and add a nice number and special
797483b6238SMichael Hamann        $data['password'] .= auth_random(10, 99).$s[auth_random(0, strlen($s) - 1)];
7988a285f7fSAndreas Gohr    }
7998a285f7fSAndreas Gohr    $evt->advise_after();
800f3f0262cSandi
8018a285f7fSAndreas Gohr    return $data['password'];
802f3f0262cSandi}
803f3f0262cSandi
804f3f0262cSandi/**
805f3f0262cSandi * Sends a password to the given user
806f3f0262cSandi *
80715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
80842ea7f44SGerrit Uitslag *
809ab5d26daSAndreas Gohr * @param string $user Login name of the user
810ab5d26daSAndreas Gohr * @param string $password The new password in clear text
81115fae107Sandi * @return bool  true on success
812f3f0262cSandi */
813f3f0262cSandifunction auth_sendPassword($user, $password) {
814f3f0262cSandi    global $lang;
815*e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
816cd52f92dSchris    global $auth;
817beca106aSAdrian Lang    if(!$auth) return false;
818cd52f92dSchris
819d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
8202dc9e900SChristopher Smith    $userinfo = $auth->getUserData($user, $requireGroups = false);
821f3f0262cSandi
82287ddda95Sandi    if(!$userinfo['mail']) return false;
823f3f0262cSandi
824f3f0262cSandi    $text = rawLocale('password');
825d7169d19SAndreas Gohr    $trep = array(
826d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
827d7169d19SAndreas Gohr        'LOGIN'    => $user,
828d7169d19SAndreas Gohr        'PASSWORD' => $password
829d7169d19SAndreas Gohr    );
830f3f0262cSandi
831d7169d19SAndreas Gohr    $mail = new Mailer();
832d7169d19SAndreas Gohr    $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
833d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
834d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
835d7169d19SAndreas Gohr    return $mail->send();
836f3f0262cSandi}
837f3f0262cSandi
838f3f0262cSandi/**
83915fae107Sandi * Register a new user
840f3f0262cSandi *
84115fae107Sandi * This registers a new user - Data is read directly from $_POST
84215fae107Sandi *
84315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
84442ea7f44SGerrit Uitslag *
84515fae107Sandi * @return bool  true on success, false on any error
846f3f0262cSandi */
847f3f0262cSandifunction register() {
848f3f0262cSandi    global $lang;
849eb5d07e4Sjan    global $conf;
850*e1d9dcc8SAndreas Gohr    /* @var \dokuwiki\Extension\AuthPlugin $auth */
851cd52f92dSchris    global $auth;
85264273335SAndreas Gohr    global $INPUT;
853f3f0262cSandi
85464273335SAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
8553a48618aSAnika Henke    if(!actionOK('register')) return false;
856640145a5Sandi
85764273335SAndreas Gohr    // gather input
85864273335SAndreas Gohr    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
85964273335SAndreas Gohr    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
86064273335SAndreas Gohr    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
86164273335SAndreas Gohr    $pass     = $INPUT->post->str('pass');
86264273335SAndreas Gohr    $passchk  = $INPUT->post->str('passchk');
863d752aedeSAndreas Gohr
86464273335SAndreas Gohr    if(empty($login) || empty($fullname) || empty($email)) {
865f3f0262cSandi        msg($lang['regmissing'], -1);
866f3f0262cSandi        return false;
867f3f0262cSandi    }
868f3f0262cSandi
869cab2716aSmatthias.grimm    if($conf['autopasswd']) {
8708a285f7fSAndreas Gohr        $pass = auth_pwgen($login); // automatically generate password
87164273335SAndreas Gohr    } elseif(empty($pass) || empty($passchk)) {
872bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
873cab2716aSmatthias.grimm        return false;
87464273335SAndreas Gohr    } elseif($pass != $passchk) {
875bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
876cab2716aSmatthias.grimm        return false;
877cab2716aSmatthias.grimm    }
878cab2716aSmatthias.grimm
879f3f0262cSandi    //check mail
88064273335SAndreas Gohr    if(!mail_isvalid($email)) {
881f3f0262cSandi        msg($lang['regbadmail'], -1);
882f3f0262cSandi        return false;
883f3f0262cSandi    }
884f3f0262cSandi
885f3f0262cSandi    //okay try to create the user
88664273335SAndreas Gohr    if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) {
887db9faf02SPatrick Brown        msg($lang['regfail'], -1);
888f3f0262cSandi        return false;
889f3f0262cSandi    }
890f3f0262cSandi
891790b7720SAndreas Gohr    // send notification about the new user
892790b7720SAndreas Gohr    $subscription = new Subscription();
893790b7720SAndreas Gohr    $subscription->send_register($login, $fullname, $email);
89402a498e7Schris
895790b7720SAndreas Gohr    // are we done?
896cab2716aSmatthias.grimm    if(!$conf['autopasswd']) {
897cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
898cab2716aSmatthias.grimm        return true;
899cab2716aSmatthias.grimm    }
900cab2716aSmatthias.grimm
901790b7720SAndreas Gohr    // autogenerated password? then send password to user
90264273335SAndreas Gohr    if(auth_sendPassword($login, $pass)) {
903f3f0262cSandi        msg($lang['regsuccess'], 1);
904f3f0262cSandi        return true;
905f3f0262cSandi    } else {
906f3f0262cSandi        msg($lang['regmailfail'], -1);
907f3f0262cSandi        return false;
908f3f0262cSandi    }
909f3f0262cSandi}
910f3f0262cSandi
91110a76f6fSfrank/**
9128b06d178Schris * Update user profile
9138b06d178Schris *
9148b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
9158b06d178Schris */
9168b06d178Schrisfunction updateprofile() {
9178b06d178Schris    global $conf;
9188b06d178Schris    global $lang;
919*e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
920cd52f92dSchris    global $auth;
921bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
922bcc94b2cSAndreas Gohr    global $INPUT;
9238b06d178Schris
924bcc94b2cSAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
9251b2a85e8SAndreas Gohr    if(!checkSecurityToken()) return false;
9268b06d178Schris
9273a48618aSAnika Henke    if(!actionOK('profile')) {
9288b06d178Schris        msg($lang['profna'], -1);
9298b06d178Schris        return false;
9308b06d178Schris    }
9318b06d178Schris
932bcc94b2cSAndreas Gohr    $changes         = array();
933bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
934bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
935bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
936bcc94b2cSAndreas Gohr
937bcc94b2cSAndreas Gohr    // check misspelled passwords
938bcc94b2cSAndreas Gohr    if($changes['pass'] != $INPUT->post->str('passchk')) {
939bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
9408b06d178Schris        return false;
9418b06d178Schris    }
9428b06d178Schris
9438b06d178Schris    // clean fullname and email
944bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
945bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
9468b06d178Schris
947bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
948bcc94b2cSAndreas Gohr    if((empty($changes['name']) && $auth->canDo('modName')) ||
949bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
950ab5d26daSAndreas Gohr    ) {
9518b06d178Schris        msg($lang['profnoempty'], -1);
9528b06d178Schris        return false;
9538b06d178Schris    }
954bcc94b2cSAndreas Gohr    if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
9558b06d178Schris        msg($lang['regbadmail'], -1);
9568b06d178Schris        return false;
9578b06d178Schris    }
9588b06d178Schris
959bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
9604c21b7eeSAndreas Gohr
961bcc94b2cSAndreas Gohr    // check for unavailable capabilities
962bcc94b2cSAndreas Gohr    if(!$auth->canDo('modName')) unset($changes['name']);
963bcc94b2cSAndreas Gohr    if(!$auth->canDo('modMail')) unset($changes['mail']);
964bcc94b2cSAndreas Gohr    if(!$auth->canDo('modPass')) unset($changes['pass']);
965bcc94b2cSAndreas Gohr
966bcc94b2cSAndreas Gohr    // anything to do?
9678b06d178Schris    if(!count($changes)) {
9688b06d178Schris        msg($lang['profnochange'], -1);
9698b06d178Schris        return false;
9708b06d178Schris    }
9718b06d178Schris
9728b06d178Schris    if($conf['profileconfirm']) {
973585bf44eSChristopher Smith        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
97471422fc8SChristopher Smith            msg($lang['badpassconfirm'], -1);
9758b06d178Schris            return false;
9768b06d178Schris        }
9778b06d178Schris    }
9788b06d178Schris
979e6c4392fSPatrick Brown    if(!$auth->triggerUserMod('modify', array($INPUT->server->str('REMOTE_USER'), &$changes))) {
980db9faf02SPatrick Brown        msg($lang['proffail'], -1);
981db9faf02SPatrick Brown        return false;
982db9faf02SPatrick Brown    }
983db9faf02SPatrick Brown
98432ed2b36SAndreas Gohr    if($changes['pass']) {
985c276e9e8SMarcel Pennewiss        // update cookie and session with the changed data
986ab5d26daSAndreas Gohr        list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
98704369c3eSMichael Hamann        $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
988585bf44eSChristopher Smith        auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
989c276e9e8SMarcel Pennewiss    } else {
990c276e9e8SMarcel Pennewiss        // make sure the session is writable
991c276e9e8SMarcel Pennewiss        @session_start();
992c276e9e8SMarcel Pennewiss        // invalidate session cache
993c276e9e8SMarcel Pennewiss        $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
994c276e9e8SMarcel Pennewiss        session_write_close();
99532ed2b36SAndreas Gohr    }
996c276e9e8SMarcel Pennewiss
99725b2a98cSMichael Klier    return true;
998a0b5b007SChris Smith}
999ab5d26daSAndreas Gohr
100004d68ae4SGerrit Uitslag/**
100104d68ae4SGerrit Uitslag * Delete the current logged-in user
100204d68ae4SGerrit Uitslag *
100304d68ae4SGerrit Uitslag * @return bool true on success, false on any error
100404d68ae4SGerrit Uitslag */
10052a7abf2dSChristopher Smithfunction auth_deleteprofile(){
10062a7abf2dSChristopher Smith    global $conf;
10072a7abf2dSChristopher Smith    global $lang;
1008*e1d9dcc8SAndreas Gohr    /* @var \dokuwiki\Extension\AuthPlugin $auth */
10092a7abf2dSChristopher Smith    global $auth;
10102a7abf2dSChristopher Smith    /* @var Input $INPUT */
10112a7abf2dSChristopher Smith    global $INPUT;
10122a7abf2dSChristopher Smith
10132a7abf2dSChristopher Smith    if(!$INPUT->post->bool('delete')) return false;
10142a7abf2dSChristopher Smith    if(!checkSecurityToken()) return false;
10152a7abf2dSChristopher Smith
10162a7abf2dSChristopher Smith    // action prevented or auth module disallows
10172a7abf2dSChristopher Smith    if(!actionOK('profile_delete') || !$auth->canDo('delUser')) {
10182a7abf2dSChristopher Smith        msg($lang['profnodelete'], -1);
10192a7abf2dSChristopher Smith        return false;
10202a7abf2dSChristopher Smith    }
10212a7abf2dSChristopher Smith
10222a7abf2dSChristopher Smith    if(!$INPUT->post->bool('confirm_delete')){
10232a7abf2dSChristopher Smith        msg($lang['profconfdeletemissing'], -1);
10242a7abf2dSChristopher Smith        return false;
10252a7abf2dSChristopher Smith    }
10262a7abf2dSChristopher Smith
10272a7abf2dSChristopher Smith    if($conf['profileconfirm']) {
1028585bf44eSChristopher Smith        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
10292a7abf2dSChristopher Smith            msg($lang['badpassconfirm'], -1);
10302a7abf2dSChristopher Smith            return false;
10312a7abf2dSChristopher Smith        }
10322a7abf2dSChristopher Smith    }
10332a7abf2dSChristopher Smith
103459bc3b48SGerrit Uitslag    $deleted = array();
1035585bf44eSChristopher Smith    $deleted[] = $INPUT->server->str('REMOTE_USER');
103673012efdSChristopher Smith    if($auth->triggerUserMod('delete', array($deleted))) {
10372a7abf2dSChristopher Smith        // force and immediate logout including removing the sticky cookie
10382a7abf2dSChristopher Smith        auth_logoff();
10392a7abf2dSChristopher Smith        return true;
10402a7abf2dSChristopher Smith    }
10412a7abf2dSChristopher Smith
10422a7abf2dSChristopher Smith    return false;
10432a7abf2dSChristopher Smith}
10442a7abf2dSChristopher Smith
10458b06d178Schris/**
10468b06d178Schris * Send a  new password
10478b06d178Schris *
10481d5856cfSAndreas Gohr * This function handles both phases of the password reset:
10491d5856cfSAndreas Gohr *
10501d5856cfSAndreas Gohr *   - handling the first request of password reset
10511d5856cfSAndreas Gohr *   - validating the password reset auth token
10521d5856cfSAndreas Gohr *
10538b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
10548b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
10551d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10568b06d178Schris *
10578b06d178Schris * @return bool true on success, false on any error
10588b06d178Schris */
10598b06d178Schrisfunction act_resendpwd() {
10608b06d178Schris    global $lang;
10618b06d178Schris    global $conf;
1062*e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1063cd52f92dSchris    global $auth;
1064bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1065bcc94b2cSAndreas Gohr    global $INPUT;
10668b06d178Schris
10673a48618aSAnika Henke    if(!actionOK('resendpwd')) {
10688b06d178Schris        msg($lang['resendna'], -1);
10698b06d178Schris        return false;
10708b06d178Schris    }
10718b06d178Schris
1072bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
10738b06d178Schris
10741d5856cfSAndreas Gohr    if($token) {
1075cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
10761d5856cfSAndreas Gohr
10771d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
107879e79377SAndreas Gohr        if(!file_exists($tfile)) {
10791d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1080bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
10811d5856cfSAndreas Gohr            return false;
10821d5856cfSAndreas Gohr        }
10838a9735e3SAndreas Gohr        // token is only valid for 3 days
10848a9735e3SAndreas Gohr        if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
10858a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1086bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
10871d5856cfSAndreas Gohr            @unlink($tfile);
10888a9735e3SAndreas Gohr            return false;
10898a9735e3SAndreas Gohr        }
10908a9735e3SAndreas Gohr
10918b06d178Schris        $user     = io_readfile($tfile);
10922dc9e900SChristopher Smith        $userinfo = $auth->getUserData($user, $requireGroups = false);
10938b06d178Schris        if(!$userinfo['mail']) {
10948b06d178Schris            msg($lang['resendpwdnouser'], -1);
10958b06d178Schris            return false;
10968b06d178Schris        }
10978b06d178Schris
1098cc204bbdSAndreas Gohr        if(!$conf['autopasswd']) { // we let the user choose a password
1099bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
1100bcc94b2cSAndreas Gohr
1101cc204bbdSAndreas Gohr            // password given correctly?
1102bcc94b2cSAndreas Gohr            if(!$pass) return false;
1103bcc94b2cSAndreas Gohr            if($pass != $INPUT->str('passchk')) {
1104451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
1105cc204bbdSAndreas Gohr                return false;
1106cc204bbdSAndreas Gohr            }
1107cc204bbdSAndreas Gohr
1108bcc94b2cSAndreas Gohr            // change it
1109cc204bbdSAndreas Gohr            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1110db9faf02SPatrick Brown                msg($lang['proffail'], -1);
1111cc204bbdSAndreas Gohr                return false;
1112cc204bbdSAndreas Gohr            }
1113cc204bbdSAndreas Gohr
1114cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
1115cc204bbdSAndreas Gohr
11168a285f7fSAndreas Gohr            $pass = auth_pwgen($user);
11177d3c8d42SGabriel Birke            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1118db9faf02SPatrick Brown                msg($lang['proffail'], -1);
11198b06d178Schris                return false;
11208b06d178Schris            }
11218b06d178Schris
11228b06d178Schris            if(auth_sendPassword($user, $pass)) {
11238b06d178Schris                msg($lang['resendpwdsuccess'], 1);
11248b06d178Schris            } else {
11258b06d178Schris                msg($lang['regmailfail'], -1);
11268b06d178Schris            }
1127cc204bbdSAndreas Gohr        }
1128cc204bbdSAndreas Gohr
1129cc204bbdSAndreas Gohr        @unlink($tfile);
11308b06d178Schris        return true;
11311d5856cfSAndreas Gohr
11321d5856cfSAndreas Gohr    } else {
11331d5856cfSAndreas Gohr        // we're in request phase
11341d5856cfSAndreas Gohr
1135bcc94b2cSAndreas Gohr        if(!$INPUT->post->bool('save')) return false;
11361d5856cfSAndreas Gohr
1137bcc94b2cSAndreas Gohr        if(!$INPUT->post->str('login')) {
11381d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
11391d5856cfSAndreas Gohr            return false;
11401d5856cfSAndreas Gohr        } else {
1141bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
11421d5856cfSAndreas Gohr        }
11431d5856cfSAndreas Gohr
11442dc9e900SChristopher Smith        $userinfo = $auth->getUserData($user, $requireGroups = false);
11451d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
11461d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
11471d5856cfSAndreas Gohr            return false;
11481d5856cfSAndreas Gohr        }
11491d5856cfSAndreas Gohr
11501d5856cfSAndreas Gohr        // generate auth token
1151483b6238SMichael Hamann        $token = md5(auth_randombytes(16)); // random secret
11521d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
11531d5856cfSAndreas Gohr        $url   = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
11541d5856cfSAndreas Gohr
11551d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
11561d5856cfSAndreas Gohr
11571d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
1158d7169d19SAndreas Gohr        $trep = array(
1159d7169d19SAndreas Gohr            'FULLNAME' => $userinfo['name'],
1160d7169d19SAndreas Gohr            'LOGIN'    => $user,
1161d7169d19SAndreas Gohr            'CONFIRM'  => $url
1162d7169d19SAndreas Gohr        );
11631d5856cfSAndreas Gohr
1164d7169d19SAndreas Gohr        $mail = new Mailer();
1165d7169d19SAndreas Gohr        $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1166d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
1167d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
1168d7169d19SAndreas Gohr        if($mail->send()) {
11691d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
11701d5856cfSAndreas Gohr        } else {
11711d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
11721d5856cfSAndreas Gohr        }
11731d5856cfSAndreas Gohr        return true;
11741d5856cfSAndreas Gohr    }
1175ab5d26daSAndreas Gohr    // never reached
11768b06d178Schris}
11778b06d178Schris
11788b06d178Schris/**
1179b0855b11Sandi * Encrypts a password using the given method and salt
1180b0855b11Sandi *
1181b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1182b0855b11Sandi * is chosen.
1183b0855b11Sandi *
1184b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
118542ea7f44SGerrit Uitslag *
1186ab5d26daSAndreas Gohr * @param string $clear The clear text password
1187ab5d26daSAndreas Gohr * @param string $method The hashing method
1188ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1189b0855b11Sandi * @return  string  The crypted password
1190b0855b11Sandi */
1191577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null) {
1192b0855b11Sandi    global $conf;
1193b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
119410a76f6fSfrank
11953a0a2d05SAndreas Gohr    $pass = new PassHash();
11963a0a2d05SAndreas Gohr    $call = 'hash_'.$method;
1197b0855b11Sandi
11983a0a2d05SAndreas Gohr    if(!method_exists($pass, $call)) {
1199b0855b11Sandi        msg("Unsupported crypt method $method", -1);
12003a0a2d05SAndreas Gohr        return false;
1201b0855b11Sandi    }
12023a0a2d05SAndreas Gohr
12033a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1204b0855b11Sandi}
1205b0855b11Sandi
1206b0855b11Sandi/**
1207b0855b11Sandi * Verifies a cleartext password against a crypted hash
1208b0855b11Sandi *
1209b0855b11Sandi * @author Andreas Gohr <andi@splitbrain.org>
121042ea7f44SGerrit Uitslag *
1211ab5d26daSAndreas Gohr * @param  string $clear The clear text password
1212ab5d26daSAndreas Gohr * @param  string $crypt The hash to compare with
1213ab5d26daSAndreas Gohr * @return bool true if both match
1214b0855b11Sandi */
1215b0855b11Sandifunction auth_verifyPassword($clear, $crypt) {
12163a0a2d05SAndreas Gohr    $pass = new PassHash();
12173a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1218b0855b11Sandi}
1219340756e4Sandi
1220a0b5b007SChris Smith/**
1221a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1222a0b5b007SChris Smith *
1223a0b5b007SChris Smith * @param string  $user       username
1224a0b5b007SChris Smith * @param string  $pass       encrypted password
1225a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1226ab5d26daSAndreas Gohr * @return bool
1227a0b5b007SChris Smith */
1228a0b5b007SChris Smithfunction auth_setCookie($user, $pass, $sticky) {
1229a0b5b007SChris Smith    global $conf;
1230*e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1231a0b5b007SChris Smith    global $auth;
123279d00841SOliver Geisen    global $USERINFO;
1233a0b5b007SChris Smith
1234beca106aSAdrian Lang    if(!$auth) return false;
1235a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1236a0b5b007SChris Smith
1237a0b5b007SChris Smith    // set cookie
1238645c0a36SAndreas Gohr    $cookie    = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
123973ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1240c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
124173ab87deSGabriel Birke    setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
124255a71a16SGerrit Uitslag
1243a0b5b007SChris Smith    // set session
1244a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1245234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1246a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1247a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1248a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1249ab5d26daSAndreas Gohr
1250ab5d26daSAndreas Gohr    return true;
1251a0b5b007SChris Smith}
1252a0b5b007SChris Smith
1253645c0a36SAndreas Gohr/**
1254645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1255645c0a36SAndreas Gohr *
1256645c0a36SAndreas Gohr * @returns array
1257645c0a36SAndreas Gohr */
1258645c0a36SAndreas Gohrfunction auth_getCookie() {
1259c66972f2SAdrian Lang    if(!isset($_COOKIE[DOKU_COOKIE])) {
1260c66972f2SAdrian Lang        return array(null, null, null);
1261c66972f2SAdrian Lang    }
1262645c0a36SAndreas Gohr    list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
1263645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1264645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1265645c0a36SAndreas Gohr    $user   = base64_decode($user);
1266645c0a36SAndreas Gohr    return array($user, $sticky, $pass);
1267645c0a36SAndreas Gohr}
1268645c0a36SAndreas Gohr
1269e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1270