xref: /dokuwiki/inc/auth.php (revision 7a33d2f8a8d3dc5633646a576e37dc7a830c2f89)
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
12fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.');
131c73890cSAndreas Gohr
14ebf97c8fSAndreas Gohr// some ACL level defines
15ebf97c8fSAndreas Gohrdefine('AUTH_NONE', 0);
16ebf97c8fSAndreas Gohrdefine('AUTH_READ', 1);
17ebf97c8fSAndreas Gohrdefine('AUTH_EDIT', 2);
18ebf97c8fSAndreas Gohrdefine('AUTH_CREATE', 4);
19ebf97c8fSAndreas Gohrdefine('AUTH_UPLOAD', 8);
20ebf97c8fSAndreas Gohrdefine('AUTH_DELETE', 16);
21ebf97c8fSAndreas Gohrdefine('AUTH_ADMIN', 255);
22ebf97c8fSAndreas Gohr
2316905344SAndreas Gohr/**
2416905344SAndreas Gohr * Initialize the auth system.
2516905344SAndreas Gohr *
2616905344SAndreas Gohr * This function is automatically called at the end of init.php
2716905344SAndreas Gohr *
2816905344SAndreas Gohr * This used to be the main() of the auth.php
2916905344SAndreas Gohr *
3016905344SAndreas Gohr * @todo backend loading maybe should be handled by the class autoloader
3116905344SAndreas Gohr * @todo maybe split into multiple functions at the XXX marked positions
32ab5d26daSAndreas Gohr * @triggers AUTH_LOGIN_CHECK
33ab5d26daSAndreas Gohr * @return bool
3416905344SAndreas Gohr */
3516905344SAndreas Gohrfunction auth_setup() {
36742c66f8Schris    global $conf;
3793a7873eSAndreas Gohr    /* @var DokuWiki_Auth_Plugin $auth */
3803c4aec3Schris    global $auth;
39bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
40bcc94b2cSAndreas Gohr    global $INPUT;
419a9714acSDominik Eckelmann    global $AUTH_ACL;
429a9714acSDominik Eckelmann    global $lang;
4327058a05SMichael Hamann    /* @var Doku_Plugin_Controller $plugin_controller */
449c29eea5SJan Schumann    global $plugin_controller;
459a9714acSDominik Eckelmann    $AUTH_ACL = array();
4603c4aec3Schris
4716905344SAndreas Gohr    if(!$conf['useacl']) return false;
4816905344SAndreas Gohr
499c29eea5SJan Schumann    // try to load auth backend from plugins
509c29eea5SJan Schumann    foreach ($plugin_controller->getList('auth') as $plugin) {
519c29eea5SJan Schumann        if ($conf['authtype'] === $plugin) {
52f4476bd9SJan Schumann            $auth = $plugin_controller->load('auth', $plugin);
539c29eea5SJan Schumann            break;
549c29eea5SJan Schumann        }
559c29eea5SJan Schumann    }
568b06d178Schris
576416b708SMichael Hamann    if(!isset($auth) || !$auth){
583094e817SAndreas Gohr        msg($lang['authtempfail'], -1);
593094e817SAndreas Gohr        return false;
603094e817SAndreas Gohr    }
618b06d178Schris
626416b708SMichael Hamann    if ($auth->success == false) {
630f4f4adfSAndreas Gohr        // degrade to unauthenticated user
64d2dde4ebSMatthias Grimm        unset($auth);
650f4f4adfSAndreas Gohr        auth_logoff();
66cd52f92dSchris        msg($lang['authtempfail'], -1);
676416b708SMichael Hamann        return false;
68d2dde4ebSMatthias Grimm    }
6916905344SAndreas Gohr
7016905344SAndreas Gohr    // do the login either by cookie or provided credentials XXX
71bcc94b2cSAndreas Gohr    $INPUT->set('http_credentials', false);
72bcc94b2cSAndreas Gohr    if(!$conf['rememberme']) $INPUT->set('r', false);
73bbbd6568SAndreas Gohr
74b2665af7SMichael Hamann    // handle renamed HTTP_AUTHORIZATION variable (can happen when a fix like
75b2665af7SMichael Hamann    // the one presented at
76b2665af7SMichael Hamann    // http://www.besthostratings.com/articles/http-auth-php-cgi.html is used
77b2665af7SMichael Hamann    // for enabling HTTP authentication with CGI/SuExec)
78b2665af7SMichael Hamann    if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
79b2665af7SMichael Hamann        $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
80528ddc7cSAndreas Gohr    // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
8106156f3cSAndreas Gohr    if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
82528ddc7cSAndreas Gohr        list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
83528ddc7cSAndreas Gohr            explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
84528ddc7cSAndreas Gohr    }
85528ddc7cSAndreas Gohr
861e8c9c90SAndreas Gohr    // if no credentials were given try to use HTTP auth (for SSO)
87bcc94b2cSAndreas Gohr    if(!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])) {
88bcc94b2cSAndreas Gohr        $INPUT->set('u', $_SERVER['PHP_AUTH_USER']);
89bcc94b2cSAndreas Gohr        $INPUT->set('p', $_SERVER['PHP_AUTH_PW']);
90bcc94b2cSAndreas Gohr        $INPUT->set('http_credentials', true);
911e8c9c90SAndreas Gohr    }
921e8c9c90SAndreas Gohr
93395c2f0fSAndreas Gohr    // apply cleaning (auth specific user names, remove control chars)
9493a7873eSAndreas Gohr    if (true === $auth->success) {
95395c2f0fSAndreas Gohr        $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
96395c2f0fSAndreas Gohr        $INPUT->set('p', stripctl($INPUT->str('p')));
97f4476bd9SJan Schumann    }
98191bb90aSAndreas Gohr
998eca974cSAndreas Gohr    if(!is_null($auth) && $auth->canDo('external')) {
100f13fa892SAndreas Gohr        // external trust mechanism in place
101bcc94b2cSAndreas Gohr        $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
102f5cb575dSAndreas Gohr    } else {
1036080c584SRobin Gareus        $evdata = array(
104bcc94b2cSAndreas Gohr            'user'     => $INPUT->str('u'),
105bcc94b2cSAndreas Gohr            'password' => $INPUT->str('p'),
106bcc94b2cSAndreas Gohr            'sticky'   => $INPUT->bool('r'),
107bcc94b2cSAndreas Gohr            'silent'   => $INPUT->bool('http_credentials')
1086080c584SRobin Gareus        );
109b5ee21aaSAdrian Lang        trigger_event('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
110f5cb575dSAndreas Gohr    }
111f5cb575dSAndreas Gohr
11216905344SAndreas Gohr    //load ACL into a global array XXX
11375c93b77SAndreas Gohr    $AUTH_ACL = auth_loadACL();
114ab5d26daSAndreas Gohr
115ab5d26daSAndreas Gohr    return true;
11675c93b77SAndreas Gohr}
11775c93b77SAndreas Gohr
11875c93b77SAndreas Gohr/**
11975c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards
12075c93b77SAndreas Gohr *
12175c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12242ea7f44SGerrit Uitslag *
123ab5d26daSAndreas Gohr * @return array
12475c93b77SAndreas Gohr */
12575c93b77SAndreas Gohrfunction auth_loadACL() {
12675c93b77SAndreas Gohr    global $config_cascade;
127b78bf706Sromain    global $USERINFO;
128585bf44eSChristopher Smith    /* @var Input $INPUT */
129585bf44eSChristopher Smith    global $INPUT;
13075c93b77SAndreas Gohr
13175c93b77SAndreas Gohr    if(!is_readable($config_cascade['acl']['default'])) return array();
13275c93b77SAndreas Gohr
13375c93b77SAndreas Gohr    $acl = file($config_cascade['acl']['default']);
13475c93b77SAndreas Gohr
13532e82180SAndreas Gohr    $out = array();
1369ce556d2SAndreas Gohr    foreach($acl as $line) {
1379ce556d2SAndreas Gohr        $line = trim($line);
138443e135dSChristopher Smith        if(empty($line) || ($line{0} == '#')) continue; // skip blank lines & comments
13921c3090aSChristopher Smith        list($id,$rest) = preg_split('/[ \t]+/',$line,2);
14032e82180SAndreas Gohr
141443e135dSChristopher Smith        // substitute user wildcard first (its 1:1)
142ad3d68d7SChristopher Smith        if(strstr($line, '%USER%')){
143ad3d68d7SChristopher Smith            // if user is not logged in, this ACL line is meaningless - skip it
144585bf44eSChristopher Smith            if (!$INPUT->server->has('REMOTE_USER')) continue;
145ad3d68d7SChristopher Smith
146585bf44eSChristopher Smith            $id   = str_replace('%USER%',cleanID($INPUT->server->str('REMOTE_USER')),$id);
147585bf44eSChristopher Smith            $rest = str_replace('%USER%',auth_nameencode($INPUT->server->str('REMOTE_USER')),$rest);
148ad3d68d7SChristopher Smith        }
149ad3d68d7SChristopher Smith
150ad3d68d7SChristopher Smith        // substitute group wildcard (its 1:m)
1519ce556d2SAndreas Gohr        if(strstr($line, '%GROUP%')){
152ad3d68d7SChristopher Smith            // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
1539ce556d2SAndreas Gohr            foreach((array) $USERINFO['grps'] as $grp){
154b78bf706Sromain                $nid   = str_replace('%GROUP%',cleanID($grp),$id);
15532e82180SAndreas Gohr                $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest);
15632e82180SAndreas Gohr                $out[] = "$nid\t$nrest";
157b78bf706Sromain            }
15832e82180SAndreas Gohr        } else {
15932e82180SAndreas Gohr            $out[] = "$id\t$rest";
160a8fe108bSGuy Brand        }
16111799630Sandi    }
1629ce556d2SAndreas Gohr
16332e82180SAndreas Gohr    return $out;
164f3f0262cSandi}
165f3f0262cSandi
166ab5d26daSAndreas Gohr/**
167ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK
168ab5d26daSAndreas Gohr *
16942ea7f44SGerrit Uitslag * @param array $evdata
170ab5d26daSAndreas Gohr * @return bool
171ab5d26daSAndreas Gohr */
172b5ee21aaSAdrian Langfunction auth_login_wrapper($evdata) {
173ab5d26daSAndreas Gohr    return auth_login(
174ab5d26daSAndreas Gohr        $evdata['user'],
175b5ee21aaSAdrian Lang        $evdata['password'],
176b5ee21aaSAdrian Lang        $evdata['sticky'],
177ab5d26daSAndreas Gohr        $evdata['silent']
178ab5d26daSAndreas Gohr    );
179b5ee21aaSAdrian Lang}
180b5ee21aaSAdrian Lang
181f3f0262cSandi/**
182f3f0262cSandi * This tries to login the user based on the sent auth credentials
183f3f0262cSandi *
184f3f0262cSandi * The authentication works like this: if a username was given
18515fae107Sandi * a new login is assumed and user/password are checked. If they
18615fae107Sandi * are correct the password is encrypted with blowfish and stored
18715fae107Sandi * together with the username in a cookie - the same info is stored
18815fae107Sandi * in the session, too. Additonally a browserID is stored in the
18915fae107Sandi * session.
19015fae107Sandi *
19115fae107Sandi * If no username was given the cookie is checked: if the username,
19215fae107Sandi * crypted password and browserID match between session and cookie
19315fae107Sandi * no further testing is done and the user is accepted
19415fae107Sandi *
19515fae107Sandi * If a cookie was found but no session info was availabe the
196136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
19715fae107Sandi * together with username rechecked by calling this function again.
198f3f0262cSandi *
199f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
200f3f0262cSandi * are set.
20115fae107Sandi *
20215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
20315fae107Sandi *
20415fae107Sandi * @param   string  $user    Username
20515fae107Sandi * @param   string  $pass    Cleartext Password
20615fae107Sandi * @param   bool    $sticky  Cookie should not expire
207f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
20815fae107Sandi * @return  bool             true on successful auth
209f3f0262cSandi */
210f112c2faSAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false) {
211f3f0262cSandi    global $USERINFO;
212f3f0262cSandi    global $conf;
213f3f0262cSandi    global $lang;
21427058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
215cd52f92dSchris    global $auth;
216585bf44eSChristopher Smith    /* @var Input $INPUT */
217585bf44eSChristopher Smith    global $INPUT;
218ab5d26daSAndreas Gohr
219132bdbfeSandi    $sticky ? $sticky = true : $sticky = false; //sanity check
220f3f0262cSandi
221beca106aSAdrian Lang    if(!$auth) return false;
222beca106aSAdrian Lang
223bbbd6568SAndreas Gohr    if(!empty($user)) {
224132bdbfeSandi        //usual login
2255e9e1054SAndreas Gohr        if(!empty($pass) && $auth->checkPass($user, $pass)) {
226132bdbfeSandi            // make logininfo globally available
227585bf44eSChristopher Smith            $INPUT->server->set('REMOTE_USER', $user);
22830d544a4SMichael Hamann            $secret                 = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
22904369c3eSMichael Hamann            auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
230132bdbfeSandi            return true;
231f3f0262cSandi        } else {
232f3f0262cSandi            //invalid credentials - log off
233f112c2faSAndreas Gohr            if(!$silent) msg($lang['badlogin'], -1);
234f3f0262cSandi            auth_logoff();
235132bdbfeSandi            return false;
236f3f0262cSandi        }
237f3f0262cSandi    } else {
238132bdbfeSandi        // read cookie information
239645c0a36SAndreas Gohr        list($user, $sticky, $pass) = auth_getCookie();
240132bdbfeSandi        if($user && $pass) {
241132bdbfeSandi            // we got a cookie - see if we can trust it
242fa7c70ffSAdrian Lang
243fa7c70ffSAdrian Lang            // get session info
244fa7c70ffSAdrian Lang            $session = $_SESSION[DOKU_COOKIE]['auth'];
245132bdbfeSandi            if(isset($session) &&
2467172dbc0SAndreas Gohr                $auth->useSessionCache($user) &&
2474c989037SChris Smith                ($session['time'] >= time() - $conf['auth_security_timeout']) &&
248132bdbfeSandi                ($session['user'] == $user) &&
249234ce57eSAndreas Gohr                ($session['pass'] == sha1($pass)) && //still crypted
250ab5d26daSAndreas Gohr                ($session['buid'] == auth_browseruid())
251ab5d26daSAndreas Gohr            ) {
252234ce57eSAndreas Gohr
253132bdbfeSandi                // he has session, cookie and browser right - let him in
254585bf44eSChristopher Smith                $INPUT->server->set('REMOTE_USER', $user);
255132bdbfeSandi                $USERINFO               = $session['info']; //FIXME move all references to session
256132bdbfeSandi                return true;
257132bdbfeSandi            }
258f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
25930d544a4SMichael Hamann            $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
26004369c3eSMichael Hamann            $pass   = auth_decrypt($pass, $secret);
261f112c2faSAndreas Gohr            return auth_login($user, $pass, $sticky, true);
262132bdbfeSandi        }
263132bdbfeSandi    }
264f3f0262cSandi    //just to be sure
265883179a4SAndreas Gohr    auth_logoff(true);
266132bdbfeSandi    return false;
267f3f0262cSandi}
268132bdbfeSandi
269132bdbfeSandi/**
270136ce040Sandi * Builds a pseudo UID from browser and IP data
271132bdbfeSandi *
272132bdbfeSandi * This is neither unique nor unfakable - still it adds some
273136ce040Sandi * security. Using the first part of the IP makes sure
27480b4f376SAndreas Gohr * proxy farms like AOLs are still okay.
27515fae107Sandi *
27615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
27715fae107Sandi *
27815fae107Sandi * @return  string  a MD5 sum of various browser headers
279132bdbfeSandi */
280132bdbfeSandifunction auth_browseruid() {
281585bf44eSChristopher Smith    /* @var Input $INPUT */
282585bf44eSChristopher Smith    global $INPUT;
283585bf44eSChristopher Smith
2842f9daf16SAndreas Gohr    $ip  = clientIP(true);
285132bdbfeSandi    $uid = '';
286585bf44eSChristopher Smith    $uid .= $INPUT->server->str('HTTP_USER_AGENT');
287585bf44eSChristopher Smith    $uid .= $INPUT->server->str('HTTP_ACCEPT_CHARSET');
2882f9daf16SAndreas Gohr    $uid .= substr($ip, 0, strpos($ip, '.'));
28980b4f376SAndreas Gohr    $uid = strtolower($uid);
290132bdbfeSandi    return md5($uid);
291132bdbfeSandi}
292132bdbfeSandi
293132bdbfeSandi/**
294132bdbfeSandi * Creates a random key to encrypt the password in cookies
29515fae107Sandi *
29615fae107Sandi * This function tries to read the password for encrypting
29798407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
29815fae107Sandi * if no such file is found a random key is created and
29915fae107Sandi * and stored in this file.
30015fae107Sandi *
30115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
30242ea7f44SGerrit Uitslag *
30332ed2b36SAndreas Gohr * @param   bool $addsession if true, the sessionid is added to the salt
30430d544a4SMichael Hamann * @param   bool $secure     if security is more important than keeping the old value
30515fae107Sandi * @return  string
306132bdbfeSandi */
30730d544a4SMichael Hamannfunction auth_cookiesalt($addsession = false, $secure = false) {
308132bdbfeSandi    global $conf;
30998407a7aSandi    $file = $conf['metadir'].'/_htcookiesalt';
31030d544a4SMichael Hamann    if ($secure || !file_exists($file)) {
31130d544a4SMichael Hamann        $file = $conf['metadir'].'/_htcookiesalt2';
31230d544a4SMichael Hamann    }
313132bdbfeSandi    $salt = io_readFile($file);
314132bdbfeSandi    if(empty($salt)) {
31530d544a4SMichael Hamann        $salt = bin2hex(auth_randombytes(64));
316132bdbfeSandi        io_saveFile($file, $salt);
317132bdbfeSandi    }
31832ed2b36SAndreas Gohr    if($addsession) {
31932ed2b36SAndreas Gohr        $salt .= session_id();
32032ed2b36SAndreas Gohr    }
321132bdbfeSandi    return $salt;
322f3f0262cSandi}
323f3f0262cSandi
324f3f0262cSandi/**
325*7a33d2f8SNiklas Keller * Return cryptographically secure random bytes.
326483b6238SMichael Hamann *
327*7a33d2f8SNiklas Keller * @author Niklas Keller <me@kelunik.com>
32842ea7f44SGerrit Uitslag *
329*7a33d2f8SNiklas Keller * @param int $length number of bytes
330*7a33d2f8SNiklas Keller * @return string cryptographically secure random bytes
331483b6238SMichael Hamann */
332483b6238SMichael Hamannfunction auth_randombytes($length) {
333*7a33d2f8SNiklas Keller    return random_bytes($length);
334483b6238SMichael Hamann}
335483b6238SMichael Hamann
336483b6238SMichael Hamann/**
337*7a33d2f8SNiklas Keller * Cryptographically secure random number generator.
338483b6238SMichael Hamann *
339*7a33d2f8SNiklas Keller * @author Niklas Keller <me@kelunik.com>
34042ea7f44SGerrit Uitslag *
341483b6238SMichael Hamann * @param int $min
342483b6238SMichael Hamann * @param int $max
343483b6238SMichael Hamann * @return int
344483b6238SMichael Hamann */
345483b6238SMichael Hamannfunction auth_random($min, $max) {
346*7a33d2f8SNiklas Keller    return random_int($min, $max);
347483b6238SMichael Hamann}
348483b6238SMichael Hamann
349483b6238SMichael Hamann/**
35004369c3eSMichael Hamann * Encrypt data using the given secret using AES
35104369c3eSMichael Hamann *
35204369c3eSMichael Hamann * The mode is CBC with a random initialization vector, the key is derived
35304369c3eSMichael Hamann * using pbkdf2.
35404369c3eSMichael Hamann *
35504369c3eSMichael Hamann * @param string $data   The data that shall be encrypted
35604369c3eSMichael Hamann * @param string $secret The secret/password that shall be used
35704369c3eSMichael Hamann * @return string The ciphertext
35804369c3eSMichael Hamann */
35904369c3eSMichael Hamannfunction auth_encrypt($data, $secret) {
36004369c3eSMichael Hamann    $iv     = auth_randombytes(16);
36104369c3eSMichael Hamann    $cipher = new Crypt_AES();
36204369c3eSMichael Hamann    $cipher->setPassword($secret);
36304369c3eSMichael Hamann
3647b650cefSMichael Hamann    /*
3657b650cefSMichael Hamann    this uses the encrypted IV as IV as suggested in
3667b650cefSMichael Hamann    http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
3677b650cefSMichael Hamann    for unique but necessarily random IVs. The resulting ciphertext is
3687b650cefSMichael Hamann    compatible to ciphertext that was created using a "normal" IV.
3697b650cefSMichael Hamann    */
37004369c3eSMichael Hamann    return $cipher->encrypt($iv.$data);
37104369c3eSMichael Hamann}
37204369c3eSMichael Hamann
37304369c3eSMichael Hamann/**
37404369c3eSMichael Hamann * Decrypt the given AES ciphertext
37504369c3eSMichael Hamann *
37604369c3eSMichael Hamann * The mode is CBC, the key is derived using pbkdf2
37704369c3eSMichael Hamann *
37804369c3eSMichael Hamann * @param string $ciphertext The encrypted data
37904369c3eSMichael Hamann * @param string $secret     The secret/password that shall be used
38004369c3eSMichael Hamann * @return string The decrypted data
38104369c3eSMichael Hamann */
38204369c3eSMichael Hamannfunction auth_decrypt($ciphertext, $secret) {
3837b650cefSMichael Hamann    $iv     = substr($ciphertext, 0, 16);
38404369c3eSMichael Hamann    $cipher = new Crypt_AES();
38504369c3eSMichael Hamann    $cipher->setPassword($secret);
3867b650cefSMichael Hamann    $cipher->setIV($iv);
38704369c3eSMichael Hamann
3887b650cefSMichael Hamann    return $cipher->decrypt(substr($ciphertext, 16));
38904369c3eSMichael Hamann}
39004369c3eSMichael Hamann
39104369c3eSMichael Hamann/**
392883179a4SAndreas Gohr * Log out the current user
393883179a4SAndreas Gohr *
394f3f0262cSandi * This clears all authentication data and thus log the user
395883179a4SAndreas Gohr * off. It also clears session data.
39615fae107Sandi *
39715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
39842ea7f44SGerrit Uitslag *
399883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
400f3f0262cSandi */
401883179a4SAndreas Gohrfunction auth_logoff($keepbc = false) {
402f3f0262cSandi    global $conf;
403f3f0262cSandi    global $USERINFO;
40427058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
4055298a619SAndreas Gohr    global $auth;
406585bf44eSChristopher Smith    /* @var Input $INPUT */
407585bf44eSChristopher Smith    global $INPUT;
40837065e65Sandi
409d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
410e9621d07SAndreas Gohr    @session_start();
411e9621d07SAndreas Gohr
412e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
413e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
414e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
415e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
416e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
417e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
418883179a4SAndreas Gohr    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
419e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
420585bf44eSChristopher Smith    $INPUT->server->remove('REMOTE_USER');
421132bdbfeSandi    $USERINFO = null; //FIXME
422f5c6743cSAndreas Gohr
42373ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
42473ab87deSGabriel Birke    setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
4255298a619SAndreas Gohr
426880f62faSAndreas Gohr    if($auth) $auth->logOff();
427f3f0262cSandi}
428f3f0262cSandi
429f3f0262cSandi/**
430f8cc712eSAndreas Gohr * Check if a user is a manager
431f8cc712eSAndreas Gohr *
432f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
433f8cc712eSAndreas Gohr * user.
434f8cc712eSAndreas Gohr *
435f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
436f8cc712eSAndreas Gohr *
437f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
438f8cc712eSAndreas Gohr * @see    auth_isadmin
43942ea7f44SGerrit Uitslag *
440ab5d26daSAndreas Gohr * @param  string $user       Username
441ab5d26daSAndreas Gohr * @param  array  $groups     List of groups the user is in
442ab5d26daSAndreas Gohr * @param  bool   $adminonly  when true checks if user is admin
443ab5d26daSAndreas Gohr * @return bool
444f8cc712eSAndreas Gohr */
445f8cc712eSAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false) {
446f8cc712eSAndreas Gohr    global $conf;
447f8cc712eSAndreas Gohr    global $USERINFO;
44827058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
449d752aedeSAndreas Gohr    global $auth;
450585bf44eSChristopher Smith    /* @var Input $INPUT */
451585bf44eSChristopher Smith    global $INPUT;
452585bf44eSChristopher Smith
453f8cc712eSAndreas Gohr
454beca106aSAdrian Lang    if(!$auth) return false;
455c66972f2SAdrian Lang    if(is_null($user)) {
456585bf44eSChristopher Smith        if(!$INPUT->server->has('REMOTE_USER')) {
457c66972f2SAdrian Lang            return false;
458c66972f2SAdrian Lang        } else {
459585bf44eSChristopher Smith            $user = $INPUT->server->str('REMOTE_USER');
460c66972f2SAdrian Lang        }
461c66972f2SAdrian Lang    }
462d6dc956fSAndreas Gohr    if(is_null($groups)) {
463d6dc956fSAndreas Gohr        $groups = (array) $USERINFO['grps'];
464e259aa79SAndreas Gohr    }
465e259aa79SAndreas Gohr
466d6dc956fSAndreas Gohr    // check superuser match
467d6dc956fSAndreas Gohr    if(auth_isMember($conf['superuser'], $user, $groups)) return true;
468d6dc956fSAndreas Gohr    if($adminonly) return false;
469e259aa79SAndreas Gohr    // check managers
470d6dc956fSAndreas Gohr    if(auth_isMember($conf['manager'], $user, $groups)) return true;
47100ce12daSChris Smith
472f8cc712eSAndreas Gohr    return false;
473f8cc712eSAndreas Gohr}
474f8cc712eSAndreas Gohr
475f8cc712eSAndreas Gohr/**
476f8cc712eSAndreas Gohr * Check if a user is admin
477f8cc712eSAndreas Gohr *
478f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
479f8cc712eSAndreas Gohr *
480f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
481f8cc712eSAndreas Gohr *
482f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
483ab5d26daSAndreas Gohr * @see auth_ismanager()
48442ea7f44SGerrit Uitslag *
485ab5d26daSAndreas Gohr * @param  string $user       Username
486ab5d26daSAndreas Gohr * @param  array  $groups     List of groups the user is in
487ab5d26daSAndreas Gohr * @return bool
488f8cc712eSAndreas Gohr */
489f8cc712eSAndreas Gohrfunction auth_isadmin($user = null, $groups = null) {
490f8cc712eSAndreas Gohr    return auth_ismanager($user, $groups, true);
491f8cc712eSAndreas Gohr}
492f8cc712eSAndreas Gohr
493d6dc956fSAndreas Gohr/**
494d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
495d6dc956fSAndreas Gohr * users and groups to determine membership status
496d6dc956fSAndreas Gohr *
497d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
498d6dc956fSAndreas Gohr *
49942ea7f44SGerrit Uitslag * @param string $memberlist commaseparated list of allowed users and groups
50042ea7f44SGerrit Uitslag * @param string $user       user to match against
50142ea7f44SGerrit Uitslag * @param array  $groups     groups the user is member of
5025446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
503d6dc956fSAndreas Gohr */
504d6dc956fSAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups) {
50527058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
506d6dc956fSAndreas Gohr    global $auth;
507d6dc956fSAndreas Gohr    if(!$auth) return false;
508d6dc956fSAndreas Gohr
509d6dc956fSAndreas Gohr    // clean user and groups
5104f56ecbfSAdrian Lang    if(!$auth->isCaseSensitive()) {
511d6dc956fSAndreas Gohr        $user   = utf8_strtolower($user);
512d6dc956fSAndreas Gohr        $groups = array_map('utf8_strtolower', $groups);
513d6dc956fSAndreas Gohr    }
514d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
515d6dc956fSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), $groups);
516d6dc956fSAndreas Gohr
517d6dc956fSAndreas Gohr    // extract the memberlist
518d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
519d6dc956fSAndreas Gohr    $members = array_map('trim', $members);
520d6dc956fSAndreas Gohr    $members = array_unique($members);
521d6dc956fSAndreas Gohr    $members = array_filter($members);
522d6dc956fSAndreas Gohr
523d6dc956fSAndreas Gohr    // compare cleaned values
524d6dc956fSAndreas Gohr    foreach($members as $member) {
525e5204a12SJurgen Hart        if($member == '@ALL' ) return true;
5264f56ecbfSAdrian Lang        if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member);
527d6dc956fSAndreas Gohr        if($member[0] == '@') {
528d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
529d6dc956fSAndreas Gohr            if(in_array($member, $groups)) return true;
530d6dc956fSAndreas Gohr        } else {
531d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
532d6dc956fSAndreas Gohr            if($member == $user) return true;
533d6dc956fSAndreas Gohr        }
534d6dc956fSAndreas Gohr    }
535d6dc956fSAndreas Gohr
536d6dc956fSAndreas Gohr    // still here? not a member!
537d6dc956fSAndreas Gohr    return false;
538d6dc956fSAndreas Gohr}
539d6dc956fSAndreas Gohr
540f8cc712eSAndreas Gohr/**
54115fae107Sandi * Convinience function for auth_aclcheck()
54215fae107Sandi *
54315fae107Sandi * This checks the permissions for the current user
54415fae107Sandi *
54515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
54615fae107Sandi *
5471698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
54815fae107Sandi * @return int          permission level
549f3f0262cSandi */
550f3f0262cSandifunction auth_quickaclcheck($id) {
551f3f0262cSandi    global $conf;
552f3f0262cSandi    global $USERINFO;
553585bf44eSChristopher Smith    /* @var Input $INPUT */
554585bf44eSChristopher Smith    global $INPUT;
555f3f0262cSandi    # if no ACL is used always return upload rights
556f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
557585bf44eSChristopher Smith    return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), $USERINFO['grps']);
558f3f0262cSandi}
559f3f0262cSandi
560f3f0262cSandi/**
561c17acc9fSAndreas Gohr * Returns the maximum rights a user has for the given ID or its namespace
56215fae107Sandi *
56315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
56442ea7f44SGerrit Uitslag *
565c17acc9fSAndreas Gohr * @triggers AUTH_ACL_CHECK
5661698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
56715fae107Sandi * @param  string       $user   Username
5683272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
56915fae107Sandi * @return int             permission level
570f3f0262cSandi */
571f3f0262cSandifunction auth_aclcheck($id, $user, $groups) {
572c17acc9fSAndreas Gohr    $data = array(
573c17acc9fSAndreas Gohr        'id'     => $id,
574c17acc9fSAndreas Gohr        'user'   => $user,
575c17acc9fSAndreas Gohr        'groups' => $groups
576c17acc9fSAndreas Gohr    );
577c17acc9fSAndreas Gohr
578c17acc9fSAndreas Gohr    return trigger_event('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
579c17acc9fSAndreas Gohr}
580c17acc9fSAndreas Gohr
581c17acc9fSAndreas Gohr/**
582c17acc9fSAndreas Gohr * default ACL check method
583c17acc9fSAndreas Gohr *
584c17acc9fSAndreas Gohr * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
585c17acc9fSAndreas Gohr *
586c17acc9fSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
58742ea7f44SGerrit Uitslag *
588c17acc9fSAndreas Gohr * @param  array $data event data
589c17acc9fSAndreas Gohr * @return int   permission level
590c17acc9fSAndreas Gohr */
591c17acc9fSAndreas Gohrfunction auth_aclcheck_cb($data) {
592c17acc9fSAndreas Gohr    $id     =& $data['id'];
593c17acc9fSAndreas Gohr    $user   =& $data['user'];
594c17acc9fSAndreas Gohr    $groups =& $data['groups'];
595c17acc9fSAndreas Gohr
596f3f0262cSandi    global $conf;
597f3f0262cSandi    global $AUTH_ACL;
59827058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
599d752aedeSAndreas Gohr    global $auth;
600f3f0262cSandi
60185d03f68SAndreas Gohr    // if no ACL is used always return upload rights
602f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
603beca106aSAdrian Lang    if(!$auth) return AUTH_NONE;
604f3f0262cSandi
605074cf26bSandi    //make sure groups is an array
606074cf26bSandi    if(!is_array($groups)) $groups = array();
607074cf26bSandi
60885d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
609ab5d26daSAndreas Gohr    if(auth_isadmin($user, $groups)) {
610ab5d26daSAndreas Gohr        return AUTH_ADMIN;
611ab5d26daSAndreas Gohr    }
61285d03f68SAndreas Gohr
613eb3ce0d5SKazutaka Miyasaka    if(!$auth->isCaseSensitive()) {
614eb3ce0d5SKazutaka Miyasaka        $user   = utf8_strtolower($user);
615eb3ce0d5SKazutaka Miyasaka        $groups = array_map('utf8_strtolower', $groups);
616eb3ce0d5SKazutaka Miyasaka    }
61737ff2261SSascha Klopp    $user   = auth_nameencode($auth->cleanUser($user));
618d752aedeSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
61985d03f68SAndreas Gohr
6206c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
62137ff2261SSascha Klopp    foreach($groups as &$group) {
62237ff2261SSascha Klopp        $group = '@'.auth_nameencode($group);
62310a76f6fSfrank    }
62410a76f6fSfrank
625f3f0262cSandi    $ns   = getNS($id);
626f3f0262cSandi    $perm = -1;
627f3f0262cSandi
628f3f0262cSandi    //add ALL group
629f3f0262cSandi    $groups[] = '@ALL';
63037ff2261SSascha Klopp
631f3f0262cSandi    //add User
63234aeb4afSAndreas Gohr    if($user) $groups[] = $user;
633f3f0262cSandi
634f3f0262cSandi    //check exact match first
63521c3090aSChristopher Smith    $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
636f3f0262cSandi    if(count($matches)) {
637f3f0262cSandi        foreach($matches as $match) {
638f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
63921c3090aSChristopher Smith            $acl   = preg_split('/[ \t]+/', $match);
640eb3ce0d5SKazutaka Miyasaka            if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
641eb3ce0d5SKazutaka Miyasaka                $acl[1] = utf8_strtolower($acl[1]);
642eb3ce0d5SKazutaka Miyasaka            }
64348d7b7a6SDominik Eckelmann            if(!in_array($acl[1], $groups)) {
64448d7b7a6SDominik Eckelmann                continue;
64548d7b7a6SDominik Eckelmann            }
6468ef6b7caSandi            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
647f3f0262cSandi            if($acl[2] > $perm) {
648f3f0262cSandi                $perm = $acl[2];
649f3f0262cSandi            }
650f3f0262cSandi        }
651f3f0262cSandi        if($perm > -1) {
652f3f0262cSandi            //we had a match - return it
653def492a2SGuillaume Turri            return (int) $perm;
654f3f0262cSandi        }
655f3f0262cSandi    }
656f3f0262cSandi
657f3f0262cSandi    //still here? do the namespace checks
658f3f0262cSandi    if($ns) {
6593e304b55SMichael Hamann        $path = $ns.':*';
660f3f0262cSandi    } else {
6613e304b55SMichael Hamann        $path = '*'; //root document
662f3f0262cSandi    }
663f3f0262cSandi
664f3f0262cSandi    do {
66521c3090aSChristopher Smith        $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
666f3f0262cSandi        if(count($matches)) {
667f3f0262cSandi            foreach($matches as $match) {
668f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
66921c3090aSChristopher Smith                $acl   = preg_split('/[ \t]+/', $match);
670eb3ce0d5SKazutaka Miyasaka                if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
671eb3ce0d5SKazutaka Miyasaka                    $acl[1] = utf8_strtolower($acl[1]);
672eb3ce0d5SKazutaka Miyasaka                }
67348d7b7a6SDominik Eckelmann                if(!in_array($acl[1], $groups)) {
67448d7b7a6SDominik Eckelmann                    continue;
67548d7b7a6SDominik Eckelmann                }
6768ef6b7caSandi                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
677f3f0262cSandi                if($acl[2] > $perm) {
678f3f0262cSandi                    $perm = $acl[2];
679f3f0262cSandi                }
680f3f0262cSandi            }
681f3f0262cSandi            //we had a match - return it
68248d7b7a6SDominik Eckelmann            if($perm != -1) {
683def492a2SGuillaume Turri                return (int) $perm;
684f3f0262cSandi            }
68548d7b7a6SDominik Eckelmann        }
686f3f0262cSandi        //get next higher namespace
687f3f0262cSandi        $ns = getNS($ns);
688f3f0262cSandi
6893e304b55SMichael Hamann        if($path != '*') {
6903e304b55SMichael Hamann            $path = $ns.':*';
6913e304b55SMichael Hamann            if($path == ':*') $path = '*';
692f3f0262cSandi        } else {
693f3f0262cSandi            //we did this already
694f3f0262cSandi            //looks like there is something wrong with the ACL
695f3f0262cSandi            //break here
696d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
697d5ce66f6SAndreas Gohr            return AUTH_NONE;
698f3f0262cSandi        }
699f3f0262cSandi    } while(1); //this should never loop endless
700ab5d26daSAndreas Gohr    return AUTH_NONE;
701f3f0262cSandi}
702f3f0262cSandi
703f3f0262cSandi/**
7046c2bb100SAndreas Gohr * Encode ASCII special chars
7056c2bb100SAndreas Gohr *
7066c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
7076c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
7086c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
7096c2bb100SAndreas Gohr * urlencoding!).
7106c2bb100SAndreas Gohr *
7116c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
7126c2bb100SAndreas Gohr *
7136c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
7146c2bb100SAndreas Gohr * @see rawurldecode()
71542ea7f44SGerrit Uitslag *
71642ea7f44SGerrit Uitslag * @param string $name
71742ea7f44SGerrit Uitslag * @param bool $skip_group
71842ea7f44SGerrit Uitslag * @return string
7196c2bb100SAndreas Gohr */
720e838fc2eSAndreas Gohrfunction auth_nameencode($name, $skip_group = false) {
721a424cd8eSchris    global $cache_authname;
722a424cd8eSchris    $cache =& $cache_authname;
72331784267SAndreas Gohr    $name  = (string) $name;
724a424cd8eSchris
72580601d26SAndreas Gohr    // never encode wildcard FS#1955
72680601d26SAndreas Gohr    if($name == '%USER%') return $name;
727b78bf706Sromain    if($name == '%GROUP%') return $name;
72880601d26SAndreas Gohr
729a424cd8eSchris    if(!isset($cache[$name][$skip_group])) {
730e838fc2eSAndreas Gohr        if($skip_group && $name{0} == '@') {
73130f6faf0SChristopher Smith            $cache[$name][$skip_group] = '@'.preg_replace_callback(
73230f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
73330f6faf0SChristopher Smith                'auth_nameencode_callback', substr($name, 1)
734ab5d26daSAndreas Gohr            );
735e838fc2eSAndreas Gohr        } else {
73630f6faf0SChristopher Smith            $cache[$name][$skip_group] = preg_replace_callback(
73730f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
73830f6faf0SChristopher Smith                'auth_nameencode_callback', $name
739ab5d26daSAndreas Gohr            );
740e838fc2eSAndreas Gohr        }
7416c2bb100SAndreas Gohr    }
7426c2bb100SAndreas Gohr
743a424cd8eSchris    return $cache[$name][$skip_group];
744a424cd8eSchris}
745a424cd8eSchris
74604d68ae4SGerrit Uitslag/**
74704d68ae4SGerrit Uitslag * callback encodes the matches
74804d68ae4SGerrit Uitslag *
74904d68ae4SGerrit Uitslag * @param array $matches first complete match, next matching subpatterms
75004d68ae4SGerrit Uitslag * @return string
75104d68ae4SGerrit Uitslag */
75230f6faf0SChristopher Smithfunction auth_nameencode_callback($matches) {
75330f6faf0SChristopher Smith    return '%'.dechex(ord(substr($matches[1],-1)));
75430f6faf0SChristopher Smith}
75530f6faf0SChristopher Smith
7566c2bb100SAndreas Gohr/**
757f3f0262cSandi * Create a pronouncable password
758f3f0262cSandi *
7598a285f7fSAndreas Gohr * The $foruser variable might be used by plugins to run additional password
7608a285f7fSAndreas Gohr * policy checks, but is not used by the default implementation
7618a285f7fSAndreas Gohr *
76215fae107Sandi * @author   Andreas Gohr <andi@splitbrain.org>
76315fae107Sandi * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
7648a285f7fSAndreas Gohr * @triggers AUTH_PASSWORD_GENERATE
76515fae107Sandi *
7668a285f7fSAndreas Gohr * @param  string $foruser username for which the password is generated
76715fae107Sandi * @return string  pronouncable password
768f3f0262cSandi */
7698a285f7fSAndreas Gohrfunction auth_pwgen($foruser = '') {
7708a285f7fSAndreas Gohr    $data = array(
771d628dcf3SAndreas Gohr        'password' => '',
772d628dcf3SAndreas Gohr        'foruser'  => $foruser
7738a285f7fSAndreas Gohr    );
7748a285f7fSAndreas Gohr
7758a285f7fSAndreas Gohr    $evt = new Doku_Event('AUTH_PASSWORD_GENERATE', $data);
7768a285f7fSAndreas Gohr    if($evt->advise_before(true)) {
777f3f0262cSandi        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
778f3f0262cSandi        $v = 'aeiou'; //vowels
779f3f0262cSandi        $a = $c.$v; //both
780987c8d26SAndreas Gohr        $s = '!$%&?+*~#-_:.;,'; // specials
781f3f0262cSandi
782987c8d26SAndreas Gohr        //use thre syllables...
783987c8d26SAndreas Gohr        for($i = 0; $i < 3; $i++) {
784483b6238SMichael Hamann            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
785483b6238SMichael Hamann            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
786483b6238SMichael Hamann            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
787f3f0262cSandi        }
788987c8d26SAndreas Gohr        //... and add a nice number and special
789483b6238SMichael Hamann        $data['password'] .= auth_random(10, 99).$s[auth_random(0, strlen($s) - 1)];
7908a285f7fSAndreas Gohr    }
7918a285f7fSAndreas Gohr    $evt->advise_after();
792f3f0262cSandi
7938a285f7fSAndreas Gohr    return $data['password'];
794f3f0262cSandi}
795f3f0262cSandi
796f3f0262cSandi/**
797f3f0262cSandi * Sends a password to the given user
798f3f0262cSandi *
79915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
80042ea7f44SGerrit Uitslag *
801ab5d26daSAndreas Gohr * @param string $user Login name of the user
802ab5d26daSAndreas Gohr * @param string $password The new password in clear text
80315fae107Sandi * @return bool  true on success
804f3f0262cSandi */
805f3f0262cSandifunction auth_sendPassword($user, $password) {
806f3f0262cSandi    global $lang;
80727058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
808cd52f92dSchris    global $auth;
809beca106aSAdrian Lang    if(!$auth) return false;
810cd52f92dSchris
811d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
8122dc9e900SChristopher Smith    $userinfo = $auth->getUserData($user, $requireGroups = false);
813f3f0262cSandi
81487ddda95Sandi    if(!$userinfo['mail']) return false;
815f3f0262cSandi
816f3f0262cSandi    $text = rawLocale('password');
817d7169d19SAndreas Gohr    $trep = array(
818d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
819d7169d19SAndreas Gohr        'LOGIN'    => $user,
820d7169d19SAndreas Gohr        'PASSWORD' => $password
821d7169d19SAndreas Gohr    );
822f3f0262cSandi
823d7169d19SAndreas Gohr    $mail = new Mailer();
824d7169d19SAndreas Gohr    $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
825d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
826d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
827d7169d19SAndreas Gohr    return $mail->send();
828f3f0262cSandi}
829f3f0262cSandi
830f3f0262cSandi/**
83115fae107Sandi * Register a new user
832f3f0262cSandi *
83315fae107Sandi * This registers a new user - Data is read directly from $_POST
83415fae107Sandi *
83515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
83642ea7f44SGerrit Uitslag *
83715fae107Sandi * @return bool  true on success, false on any error
838f3f0262cSandi */
839f3f0262cSandifunction register() {
840f3f0262cSandi    global $lang;
841eb5d07e4Sjan    global $conf;
84227058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
843cd52f92dSchris    global $auth;
84464273335SAndreas Gohr    global $INPUT;
845f3f0262cSandi
84664273335SAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
8473a48618aSAnika Henke    if(!actionOK('register')) return false;
848640145a5Sandi
84964273335SAndreas Gohr    // gather input
85064273335SAndreas Gohr    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
85164273335SAndreas Gohr    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
85264273335SAndreas Gohr    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
85364273335SAndreas Gohr    $pass     = $INPUT->post->str('pass');
85464273335SAndreas Gohr    $passchk  = $INPUT->post->str('passchk');
855d752aedeSAndreas Gohr
85664273335SAndreas Gohr    if(empty($login) || empty($fullname) || empty($email)) {
857f3f0262cSandi        msg($lang['regmissing'], -1);
858f3f0262cSandi        return false;
859f3f0262cSandi    }
860f3f0262cSandi
861cab2716aSmatthias.grimm    if($conf['autopasswd']) {
8628a285f7fSAndreas Gohr        $pass = auth_pwgen($login); // automatically generate password
86364273335SAndreas Gohr    } elseif(empty($pass) || empty($passchk)) {
864bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
865cab2716aSmatthias.grimm        return false;
86664273335SAndreas Gohr    } elseif($pass != $passchk) {
867bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
868cab2716aSmatthias.grimm        return false;
869cab2716aSmatthias.grimm    }
870cab2716aSmatthias.grimm
871f3f0262cSandi    //check mail
87264273335SAndreas Gohr    if(!mail_isvalid($email)) {
873f3f0262cSandi        msg($lang['regbadmail'], -1);
874f3f0262cSandi        return false;
875f3f0262cSandi    }
876f3f0262cSandi
877f3f0262cSandi    //okay try to create the user
87864273335SAndreas Gohr    if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) {
879db9faf02SPatrick Brown        msg($lang['regfail'], -1);
880f3f0262cSandi        return false;
881f3f0262cSandi    }
882f3f0262cSandi
883790b7720SAndreas Gohr    // send notification about the new user
884790b7720SAndreas Gohr    $subscription = new Subscription();
885790b7720SAndreas Gohr    $subscription->send_register($login, $fullname, $email);
88602a498e7Schris
887790b7720SAndreas Gohr    // are we done?
888cab2716aSmatthias.grimm    if(!$conf['autopasswd']) {
889cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
890cab2716aSmatthias.grimm        return true;
891cab2716aSmatthias.grimm    }
892cab2716aSmatthias.grimm
893790b7720SAndreas Gohr    // autogenerated password? then send password to user
89464273335SAndreas Gohr    if(auth_sendPassword($login, $pass)) {
895f3f0262cSandi        msg($lang['regsuccess'], 1);
896f3f0262cSandi        return true;
897f3f0262cSandi    } else {
898f3f0262cSandi        msg($lang['regmailfail'], -1);
899f3f0262cSandi        return false;
900f3f0262cSandi    }
901f3f0262cSandi}
902f3f0262cSandi
90310a76f6fSfrank/**
9048b06d178Schris * Update user profile
9058b06d178Schris *
9068b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
9078b06d178Schris */
9088b06d178Schrisfunction updateprofile() {
9098b06d178Schris    global $conf;
9108b06d178Schris    global $lang;
91127058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
912cd52f92dSchris    global $auth;
913bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
914bcc94b2cSAndreas Gohr    global $INPUT;
9158b06d178Schris
916bcc94b2cSAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
9171b2a85e8SAndreas Gohr    if(!checkSecurityToken()) return false;
9188b06d178Schris
9193a48618aSAnika Henke    if(!actionOK('profile')) {
9208b06d178Schris        msg($lang['profna'], -1);
9218b06d178Schris        return false;
9228b06d178Schris    }
9238b06d178Schris
924bcc94b2cSAndreas Gohr    $changes         = array();
925bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
926bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
927bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
928bcc94b2cSAndreas Gohr
929bcc94b2cSAndreas Gohr    // check misspelled passwords
930bcc94b2cSAndreas Gohr    if($changes['pass'] != $INPUT->post->str('passchk')) {
931bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
9328b06d178Schris        return false;
9338b06d178Schris    }
9348b06d178Schris
9358b06d178Schris    // clean fullname and email
936bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
937bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
9388b06d178Schris
939bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
940bcc94b2cSAndreas Gohr    if((empty($changes['name']) && $auth->canDo('modName')) ||
941bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
942ab5d26daSAndreas Gohr    ) {
9438b06d178Schris        msg($lang['profnoempty'], -1);
9448b06d178Schris        return false;
9458b06d178Schris    }
946bcc94b2cSAndreas Gohr    if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
9478b06d178Schris        msg($lang['regbadmail'], -1);
9488b06d178Schris        return false;
9498b06d178Schris    }
9508b06d178Schris
951bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
9524c21b7eeSAndreas Gohr
953bcc94b2cSAndreas Gohr    // check for unavailable capabilities
954bcc94b2cSAndreas Gohr    if(!$auth->canDo('modName')) unset($changes['name']);
955bcc94b2cSAndreas Gohr    if(!$auth->canDo('modMail')) unset($changes['mail']);
956bcc94b2cSAndreas Gohr    if(!$auth->canDo('modPass')) unset($changes['pass']);
957bcc94b2cSAndreas Gohr
958bcc94b2cSAndreas Gohr    // anything to do?
9598b06d178Schris    if(!count($changes)) {
9608b06d178Schris        msg($lang['profnochange'], -1);
9618b06d178Schris        return false;
9628b06d178Schris    }
9638b06d178Schris
9648b06d178Schris    if($conf['profileconfirm']) {
965585bf44eSChristopher Smith        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
96671422fc8SChristopher Smith            msg($lang['badpassconfirm'], -1);
9678b06d178Schris            return false;
9688b06d178Schris        }
9698b06d178Schris    }
9708b06d178Schris
971e6c4392fSPatrick Brown    if(!$auth->triggerUserMod('modify', array($INPUT->server->str('REMOTE_USER'), &$changes))) {
972db9faf02SPatrick Brown        msg($lang['proffail'], -1);
973db9faf02SPatrick Brown        return false;
974db9faf02SPatrick Brown    }
975db9faf02SPatrick Brown
97632ed2b36SAndreas Gohr    if($changes['pass']) {
977c276e9e8SMarcel Pennewiss        // update cookie and session with the changed data
978ab5d26daSAndreas Gohr        list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
97904369c3eSMichael Hamann        $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
980585bf44eSChristopher Smith        auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
981c276e9e8SMarcel Pennewiss    } else {
982c276e9e8SMarcel Pennewiss        // make sure the session is writable
983c276e9e8SMarcel Pennewiss        @session_start();
984c276e9e8SMarcel Pennewiss        // invalidate session cache
985c276e9e8SMarcel Pennewiss        $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
986c276e9e8SMarcel Pennewiss        session_write_close();
98732ed2b36SAndreas Gohr    }
988c276e9e8SMarcel Pennewiss
98925b2a98cSMichael Klier    return true;
990a0b5b007SChris Smith}
991ab5d26daSAndreas Gohr
99204d68ae4SGerrit Uitslag/**
99304d68ae4SGerrit Uitslag * Delete the current logged-in user
99404d68ae4SGerrit Uitslag *
99504d68ae4SGerrit Uitslag * @return bool true on success, false on any error
99604d68ae4SGerrit Uitslag */
9972a7abf2dSChristopher Smithfunction auth_deleteprofile(){
9982a7abf2dSChristopher Smith    global $conf;
9992a7abf2dSChristopher Smith    global $lang;
100073012efdSChristopher Smith    /* @var DokuWiki_Auth_Plugin $auth */
10012a7abf2dSChristopher Smith    global $auth;
10022a7abf2dSChristopher Smith    /* @var Input $INPUT */
10032a7abf2dSChristopher Smith    global $INPUT;
10042a7abf2dSChristopher Smith
10052a7abf2dSChristopher Smith    if(!$INPUT->post->bool('delete')) return false;
10062a7abf2dSChristopher Smith    if(!checkSecurityToken()) return false;
10072a7abf2dSChristopher Smith
10082a7abf2dSChristopher Smith    // action prevented or auth module disallows
10092a7abf2dSChristopher Smith    if(!actionOK('profile_delete') || !$auth->canDo('delUser')) {
10102a7abf2dSChristopher Smith        msg($lang['profnodelete'], -1);
10112a7abf2dSChristopher Smith        return false;
10122a7abf2dSChristopher Smith    }
10132a7abf2dSChristopher Smith
10142a7abf2dSChristopher Smith    if(!$INPUT->post->bool('confirm_delete')){
10152a7abf2dSChristopher Smith        msg($lang['profconfdeletemissing'], -1);
10162a7abf2dSChristopher Smith        return false;
10172a7abf2dSChristopher Smith    }
10182a7abf2dSChristopher Smith
10192a7abf2dSChristopher Smith    if($conf['profileconfirm']) {
1020585bf44eSChristopher Smith        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
10212a7abf2dSChristopher Smith            msg($lang['badpassconfirm'], -1);
10222a7abf2dSChristopher Smith            return false;
10232a7abf2dSChristopher Smith        }
10242a7abf2dSChristopher Smith    }
10252a7abf2dSChristopher Smith
102659bc3b48SGerrit Uitslag    $deleted = array();
1027585bf44eSChristopher Smith    $deleted[] = $INPUT->server->str('REMOTE_USER');
102873012efdSChristopher Smith    if($auth->triggerUserMod('delete', array($deleted))) {
10292a7abf2dSChristopher Smith        // force and immediate logout including removing the sticky cookie
10302a7abf2dSChristopher Smith        auth_logoff();
10312a7abf2dSChristopher Smith        return true;
10322a7abf2dSChristopher Smith    }
10332a7abf2dSChristopher Smith
10342a7abf2dSChristopher Smith    return false;
10352a7abf2dSChristopher Smith}
10362a7abf2dSChristopher Smith
10378b06d178Schris/**
10388b06d178Schris * Send a  new password
10398b06d178Schris *
10401d5856cfSAndreas Gohr * This function handles both phases of the password reset:
10411d5856cfSAndreas Gohr *
10421d5856cfSAndreas Gohr *   - handling the first request of password reset
10431d5856cfSAndreas Gohr *   - validating the password reset auth token
10441d5856cfSAndreas Gohr *
10458b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
10468b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
10471d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10488b06d178Schris *
10498b06d178Schris * @return bool true on success, false on any error
10508b06d178Schris */
10518b06d178Schrisfunction act_resendpwd() {
10528b06d178Schris    global $lang;
10538b06d178Schris    global $conf;
105427058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
1055cd52f92dSchris    global $auth;
1056bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1057bcc94b2cSAndreas Gohr    global $INPUT;
10588b06d178Schris
10593a48618aSAnika Henke    if(!actionOK('resendpwd')) {
10608b06d178Schris        msg($lang['resendna'], -1);
10618b06d178Schris        return false;
10628b06d178Schris    }
10638b06d178Schris
1064bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
10658b06d178Schris
10661d5856cfSAndreas Gohr    if($token) {
1067cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
10681d5856cfSAndreas Gohr
10691d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
107079e79377SAndreas Gohr        if(!file_exists($tfile)) {
10711d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1072bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
10731d5856cfSAndreas Gohr            return false;
10741d5856cfSAndreas Gohr        }
10758a9735e3SAndreas Gohr        // token is only valid for 3 days
10768a9735e3SAndreas Gohr        if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
10778a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1078bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
10791d5856cfSAndreas Gohr            @unlink($tfile);
10808a9735e3SAndreas Gohr            return false;
10818a9735e3SAndreas Gohr        }
10828a9735e3SAndreas Gohr
10838b06d178Schris        $user     = io_readfile($tfile);
10842dc9e900SChristopher Smith        $userinfo = $auth->getUserData($user, $requireGroups = false);
10858b06d178Schris        if(!$userinfo['mail']) {
10868b06d178Schris            msg($lang['resendpwdnouser'], -1);
10878b06d178Schris            return false;
10888b06d178Schris        }
10898b06d178Schris
1090cc204bbdSAndreas Gohr        if(!$conf['autopasswd']) { // we let the user choose a password
1091bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
1092bcc94b2cSAndreas Gohr
1093cc204bbdSAndreas Gohr            // password given correctly?
1094bcc94b2cSAndreas Gohr            if(!$pass) return false;
1095bcc94b2cSAndreas Gohr            if($pass != $INPUT->str('passchk')) {
1096451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
1097cc204bbdSAndreas Gohr                return false;
1098cc204bbdSAndreas Gohr            }
1099cc204bbdSAndreas Gohr
1100bcc94b2cSAndreas Gohr            // change it
1101cc204bbdSAndreas Gohr            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1102db9faf02SPatrick Brown                msg($lang['proffail'], -1);
1103cc204bbdSAndreas Gohr                return false;
1104cc204bbdSAndreas Gohr            }
1105cc204bbdSAndreas Gohr
1106cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
1107cc204bbdSAndreas Gohr
11088a285f7fSAndreas Gohr            $pass = auth_pwgen($user);
11097d3c8d42SGabriel Birke            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1110db9faf02SPatrick Brown                msg($lang['proffail'], -1);
11118b06d178Schris                return false;
11128b06d178Schris            }
11138b06d178Schris
11148b06d178Schris            if(auth_sendPassword($user, $pass)) {
11158b06d178Schris                msg($lang['resendpwdsuccess'], 1);
11168b06d178Schris            } else {
11178b06d178Schris                msg($lang['regmailfail'], -1);
11188b06d178Schris            }
1119cc204bbdSAndreas Gohr        }
1120cc204bbdSAndreas Gohr
1121cc204bbdSAndreas Gohr        @unlink($tfile);
11228b06d178Schris        return true;
11231d5856cfSAndreas Gohr
11241d5856cfSAndreas Gohr    } else {
11251d5856cfSAndreas Gohr        // we're in request phase
11261d5856cfSAndreas Gohr
1127bcc94b2cSAndreas Gohr        if(!$INPUT->post->bool('save')) return false;
11281d5856cfSAndreas Gohr
1129bcc94b2cSAndreas Gohr        if(!$INPUT->post->str('login')) {
11301d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
11311d5856cfSAndreas Gohr            return false;
11321d5856cfSAndreas Gohr        } else {
1133bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
11341d5856cfSAndreas Gohr        }
11351d5856cfSAndreas Gohr
11362dc9e900SChristopher Smith        $userinfo = $auth->getUserData($user, $requireGroups = false);
11371d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
11381d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
11391d5856cfSAndreas Gohr            return false;
11401d5856cfSAndreas Gohr        }
11411d5856cfSAndreas Gohr
11421d5856cfSAndreas Gohr        // generate auth token
1143483b6238SMichael Hamann        $token = md5(auth_randombytes(16)); // random secret
11441d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
11451d5856cfSAndreas Gohr        $url   = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
11461d5856cfSAndreas Gohr
11471d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
11481d5856cfSAndreas Gohr
11491d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
1150d7169d19SAndreas Gohr        $trep = array(
1151d7169d19SAndreas Gohr            'FULLNAME' => $userinfo['name'],
1152d7169d19SAndreas Gohr            'LOGIN'    => $user,
1153d7169d19SAndreas Gohr            'CONFIRM'  => $url
1154d7169d19SAndreas Gohr        );
11551d5856cfSAndreas Gohr
1156d7169d19SAndreas Gohr        $mail = new Mailer();
1157d7169d19SAndreas Gohr        $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1158d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
1159d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
1160d7169d19SAndreas Gohr        if($mail->send()) {
11611d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
11621d5856cfSAndreas Gohr        } else {
11631d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
11641d5856cfSAndreas Gohr        }
11651d5856cfSAndreas Gohr        return true;
11661d5856cfSAndreas Gohr    }
1167ab5d26daSAndreas Gohr    // never reached
11688b06d178Schris}
11698b06d178Schris
11708b06d178Schris/**
1171b0855b11Sandi * Encrypts a password using the given method and salt
1172b0855b11Sandi *
1173b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1174b0855b11Sandi * is chosen.
1175b0855b11Sandi *
1176b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
117742ea7f44SGerrit Uitslag *
1178ab5d26daSAndreas Gohr * @param string $clear The clear text password
1179ab5d26daSAndreas Gohr * @param string $method The hashing method
1180ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1181b0855b11Sandi * @return  string  The crypted password
1182b0855b11Sandi */
1183577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null) {
1184b0855b11Sandi    global $conf;
1185b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
118610a76f6fSfrank
11873a0a2d05SAndreas Gohr    $pass = new PassHash();
11883a0a2d05SAndreas Gohr    $call = 'hash_'.$method;
1189b0855b11Sandi
11903a0a2d05SAndreas Gohr    if(!method_exists($pass, $call)) {
1191b0855b11Sandi        msg("Unsupported crypt method $method", -1);
11923a0a2d05SAndreas Gohr        return false;
1193b0855b11Sandi    }
11943a0a2d05SAndreas Gohr
11953a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1196b0855b11Sandi}
1197b0855b11Sandi
1198b0855b11Sandi/**
1199b0855b11Sandi * Verifies a cleartext password against a crypted hash
1200b0855b11Sandi *
1201b0855b11Sandi * @author Andreas Gohr <andi@splitbrain.org>
120242ea7f44SGerrit Uitslag *
1203ab5d26daSAndreas Gohr * @param  string $clear The clear text password
1204ab5d26daSAndreas Gohr * @param  string $crypt The hash to compare with
1205ab5d26daSAndreas Gohr * @return bool true if both match
1206b0855b11Sandi */
1207b0855b11Sandifunction auth_verifyPassword($clear, $crypt) {
12083a0a2d05SAndreas Gohr    $pass = new PassHash();
12093a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1210b0855b11Sandi}
1211340756e4Sandi
1212a0b5b007SChris Smith/**
1213a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1214a0b5b007SChris Smith *
1215a0b5b007SChris Smith * @param string  $user       username
1216a0b5b007SChris Smith * @param string  $pass       encrypted password
1217a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1218ab5d26daSAndreas Gohr * @return bool
1219a0b5b007SChris Smith */
1220a0b5b007SChris Smithfunction auth_setCookie($user, $pass, $sticky) {
1221a0b5b007SChris Smith    global $conf;
122227058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
1223a0b5b007SChris Smith    global $auth;
122479d00841SOliver Geisen    global $USERINFO;
1225a0b5b007SChris Smith
1226beca106aSAdrian Lang    if(!$auth) return false;
1227a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1228a0b5b007SChris Smith
1229a0b5b007SChris Smith    // set cookie
1230645c0a36SAndreas Gohr    $cookie    = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
123173ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1232c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
123373ab87deSGabriel Birke    setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
123455a71a16SGerrit Uitslag
1235a0b5b007SChris Smith    // set session
1236a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1237234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1238a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1239a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1240a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1241ab5d26daSAndreas Gohr
1242ab5d26daSAndreas Gohr    return true;
1243a0b5b007SChris Smith}
1244a0b5b007SChris Smith
1245645c0a36SAndreas Gohr/**
1246645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1247645c0a36SAndreas Gohr *
1248645c0a36SAndreas Gohr * @returns array
1249645c0a36SAndreas Gohr */
1250645c0a36SAndreas Gohrfunction auth_getCookie() {
1251c66972f2SAdrian Lang    if(!isset($_COOKIE[DOKU_COOKIE])) {
1252c66972f2SAdrian Lang        return array(null, null, null);
1253c66972f2SAdrian Lang    }
1254645c0a36SAndreas Gohr    list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
1255645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1256645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1257645c0a36SAndreas Gohr    $user   = base64_decode($user);
1258645c0a36SAndreas Gohr    return array($user, $sticky, $pass);
1259645c0a36SAndreas Gohr}
1260645c0a36SAndreas Gohr
1261e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1262