xref: /dokuwiki/inc/auth.php (revision f8b1e4e7e79751a01ea748240628d024fc380b07)
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
233*f8b1e4e7SAndreas Gohr            if(!$silent) {
234*f8b1e4e7SAndreas Gohr                http_status(403, 'Login failed');
235*f8b1e4e7SAndreas Gohr                msg($lang['badlogin'], -1);
236*f8b1e4e7SAndreas Gohr            }
237f3f0262cSandi            auth_logoff();
238132bdbfeSandi            return false;
239f3f0262cSandi        }
240f3f0262cSandi    } else {
241132bdbfeSandi        // read cookie information
242645c0a36SAndreas Gohr        list($user, $sticky, $pass) = auth_getCookie();
243132bdbfeSandi        if($user && $pass) {
244132bdbfeSandi            // we got a cookie - see if we can trust it
245fa7c70ffSAdrian Lang
246fa7c70ffSAdrian Lang            // get session info
247fa7c70ffSAdrian Lang            $session = $_SESSION[DOKU_COOKIE]['auth'];
248132bdbfeSandi            if(isset($session) &&
2497172dbc0SAndreas Gohr                $auth->useSessionCache($user) &&
2504c989037SChris Smith                ($session['time'] >= time() - $conf['auth_security_timeout']) &&
251132bdbfeSandi                ($session['user'] == $user) &&
252234ce57eSAndreas Gohr                ($session['pass'] == sha1($pass)) && //still crypted
253ab5d26daSAndreas Gohr                ($session['buid'] == auth_browseruid())
254ab5d26daSAndreas Gohr            ) {
255234ce57eSAndreas Gohr
256132bdbfeSandi                // he has session, cookie and browser right - let him in
257585bf44eSChristopher Smith                $INPUT->server->set('REMOTE_USER', $user);
258132bdbfeSandi                $USERINFO               = $session['info']; //FIXME move all references to session
259132bdbfeSandi                return true;
260132bdbfeSandi            }
261f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
26230d544a4SMichael Hamann            $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
26304369c3eSMichael Hamann            $pass   = auth_decrypt($pass, $secret);
264f112c2faSAndreas Gohr            return auth_login($user, $pass, $sticky, true);
265132bdbfeSandi        }
266132bdbfeSandi    }
267f3f0262cSandi    //just to be sure
268883179a4SAndreas Gohr    auth_logoff(true);
269132bdbfeSandi    return false;
270f3f0262cSandi}
271132bdbfeSandi
272132bdbfeSandi/**
273136ce040Sandi * Builds a pseudo UID from browser and IP data
274132bdbfeSandi *
275132bdbfeSandi * This is neither unique nor unfakable - still it adds some
276136ce040Sandi * security. Using the first part of the IP makes sure
27780b4f376SAndreas Gohr * proxy farms like AOLs are still okay.
27815fae107Sandi *
27915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
28015fae107Sandi *
28115fae107Sandi * @return  string  a MD5 sum of various browser headers
282132bdbfeSandi */
283132bdbfeSandifunction auth_browseruid() {
284585bf44eSChristopher Smith    /* @var Input $INPUT */
285585bf44eSChristopher Smith    global $INPUT;
286585bf44eSChristopher Smith
2872f9daf16SAndreas Gohr    $ip  = clientIP(true);
288132bdbfeSandi    $uid = '';
289585bf44eSChristopher Smith    $uid .= $INPUT->server->str('HTTP_USER_AGENT');
290585bf44eSChristopher Smith    $uid .= $INPUT->server->str('HTTP_ACCEPT_CHARSET');
2912f9daf16SAndreas Gohr    $uid .= substr($ip, 0, strpos($ip, '.'));
29280b4f376SAndreas Gohr    $uid = strtolower($uid);
293132bdbfeSandi    return md5($uid);
294132bdbfeSandi}
295132bdbfeSandi
296132bdbfeSandi/**
297132bdbfeSandi * Creates a random key to encrypt the password in cookies
29815fae107Sandi *
29915fae107Sandi * This function tries to read the password for encrypting
30098407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
30115fae107Sandi * if no such file is found a random key is created and
30215fae107Sandi * and stored in this file.
30315fae107Sandi *
30415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
30542ea7f44SGerrit Uitslag *
30632ed2b36SAndreas Gohr * @param   bool $addsession if true, the sessionid is added to the salt
30730d544a4SMichael Hamann * @param   bool $secure     if security is more important than keeping the old value
30815fae107Sandi * @return  string
309132bdbfeSandi */
31030d544a4SMichael Hamannfunction auth_cookiesalt($addsession = false, $secure = false) {
311132bdbfeSandi    global $conf;
31298407a7aSandi    $file = $conf['metadir'].'/_htcookiesalt';
31330d544a4SMichael Hamann    if ($secure || !file_exists($file)) {
31430d544a4SMichael Hamann        $file = $conf['metadir'].'/_htcookiesalt2';
31530d544a4SMichael Hamann    }
316132bdbfeSandi    $salt = io_readFile($file);
317132bdbfeSandi    if(empty($salt)) {
31830d544a4SMichael Hamann        $salt = bin2hex(auth_randombytes(64));
319132bdbfeSandi        io_saveFile($file, $salt);
320132bdbfeSandi    }
32132ed2b36SAndreas Gohr    if($addsession) {
32232ed2b36SAndreas Gohr        $salt .= session_id();
32332ed2b36SAndreas Gohr    }
324132bdbfeSandi    return $salt;
325f3f0262cSandi}
326f3f0262cSandi
327f3f0262cSandi/**
3287a33d2f8SNiklas Keller * Return cryptographically secure random bytes.
329483b6238SMichael Hamann *
3307a33d2f8SNiklas Keller * @author Niklas Keller <me@kelunik.com>
33142ea7f44SGerrit Uitslag *
3327a33d2f8SNiklas Keller * @param int $length number of bytes
3337a33d2f8SNiklas Keller * @return string cryptographically secure random bytes
334483b6238SMichael Hamann */
335483b6238SMichael Hamannfunction auth_randombytes($length) {
3367a33d2f8SNiklas Keller    return random_bytes($length);
337483b6238SMichael Hamann}
338483b6238SMichael Hamann
339483b6238SMichael Hamann/**
3407a33d2f8SNiklas Keller * Cryptographically secure random number generator.
341483b6238SMichael Hamann *
3427a33d2f8SNiklas Keller * @author Niklas Keller <me@kelunik.com>
34342ea7f44SGerrit Uitslag *
344483b6238SMichael Hamann * @param int $min
345483b6238SMichael Hamann * @param int $max
346483b6238SMichael Hamann * @return int
347483b6238SMichael Hamann */
348483b6238SMichael Hamannfunction auth_random($min, $max) {
3497a33d2f8SNiklas Keller    return random_int($min, $max);
350483b6238SMichael Hamann}
351483b6238SMichael Hamann
352483b6238SMichael Hamann/**
35304369c3eSMichael Hamann * Encrypt data using the given secret using AES
35404369c3eSMichael Hamann *
35504369c3eSMichael Hamann * The mode is CBC with a random initialization vector, the key is derived
35604369c3eSMichael Hamann * using pbkdf2.
35704369c3eSMichael Hamann *
35804369c3eSMichael Hamann * @param string $data   The data that shall be encrypted
35904369c3eSMichael Hamann * @param string $secret The secret/password that shall be used
36004369c3eSMichael Hamann * @return string The ciphertext
36104369c3eSMichael Hamann */
36204369c3eSMichael Hamannfunction auth_encrypt($data, $secret) {
36304369c3eSMichael Hamann    $iv     = auth_randombytes(16);
3641af2f135SAndreas Gohr    $cipher = new \phpseclib\Crypt\AES();
36504369c3eSMichael Hamann    $cipher->setPassword($secret);
36604369c3eSMichael Hamann
3677b650cefSMichael Hamann    /*
3687b650cefSMichael Hamann    this uses the encrypted IV as IV as suggested in
3697b650cefSMichael Hamann    http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
3707b650cefSMichael Hamann    for unique but necessarily random IVs. The resulting ciphertext is
3717b650cefSMichael Hamann    compatible to ciphertext that was created using a "normal" IV.
3727b650cefSMichael Hamann    */
37304369c3eSMichael Hamann    return $cipher->encrypt($iv.$data);
37404369c3eSMichael Hamann}
37504369c3eSMichael Hamann
37604369c3eSMichael Hamann/**
37704369c3eSMichael Hamann * Decrypt the given AES ciphertext
37804369c3eSMichael Hamann *
37904369c3eSMichael Hamann * The mode is CBC, the key is derived using pbkdf2
38004369c3eSMichael Hamann *
38104369c3eSMichael Hamann * @param string $ciphertext The encrypted data
38204369c3eSMichael Hamann * @param string $secret     The secret/password that shall be used
38304369c3eSMichael Hamann * @return string The decrypted data
38404369c3eSMichael Hamann */
38504369c3eSMichael Hamannfunction auth_decrypt($ciphertext, $secret) {
3867b650cefSMichael Hamann    $iv     = substr($ciphertext, 0, 16);
3871af2f135SAndreas Gohr    $cipher = new \phpseclib\Crypt\AES();
38804369c3eSMichael Hamann    $cipher->setPassword($secret);
3897b650cefSMichael Hamann    $cipher->setIV($iv);
39004369c3eSMichael Hamann
3917b650cefSMichael Hamann    return $cipher->decrypt(substr($ciphertext, 16));
39204369c3eSMichael Hamann}
39304369c3eSMichael Hamann
39404369c3eSMichael Hamann/**
395883179a4SAndreas Gohr * Log out the current user
396883179a4SAndreas Gohr *
397f3f0262cSandi * This clears all authentication data and thus log the user
398883179a4SAndreas Gohr * off. It also clears session data.
39915fae107Sandi *
40015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
40142ea7f44SGerrit Uitslag *
402883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
403f3f0262cSandi */
404883179a4SAndreas Gohrfunction auth_logoff($keepbc = false) {
405f3f0262cSandi    global $conf;
406f3f0262cSandi    global $USERINFO;
40727058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
4085298a619SAndreas Gohr    global $auth;
409585bf44eSChristopher Smith    /* @var Input $INPUT */
410585bf44eSChristopher Smith    global $INPUT;
41137065e65Sandi
412d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
413e9621d07SAndreas Gohr    @session_start();
414e9621d07SAndreas Gohr
415e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
416e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
417e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
418e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
419e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
420e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
421883179a4SAndreas Gohr    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
422e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
423585bf44eSChristopher Smith    $INPUT->server->remove('REMOTE_USER');
424132bdbfeSandi    $USERINFO = null; //FIXME
425f5c6743cSAndreas Gohr
42673ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
42773ab87deSGabriel Birke    setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
4285298a619SAndreas Gohr
429880f62faSAndreas Gohr    if($auth) $auth->logOff();
430f3f0262cSandi}
431f3f0262cSandi
432f3f0262cSandi/**
433f8cc712eSAndreas Gohr * Check if a user is a manager
434f8cc712eSAndreas Gohr *
435f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
436f8cc712eSAndreas Gohr * user.
437f8cc712eSAndreas Gohr *
438f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
439f8cc712eSAndreas Gohr *
440f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
441f8cc712eSAndreas Gohr * @see    auth_isadmin
44242ea7f44SGerrit Uitslag *
443ab5d26daSAndreas Gohr * @param  string $user       Username
444ab5d26daSAndreas Gohr * @param  array  $groups     List of groups the user is in
445ab5d26daSAndreas Gohr * @param  bool   $adminonly  when true checks if user is admin
446ab5d26daSAndreas Gohr * @return bool
447f8cc712eSAndreas Gohr */
448f8cc712eSAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false) {
449f8cc712eSAndreas Gohr    global $conf;
450f8cc712eSAndreas Gohr    global $USERINFO;
45127058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
452d752aedeSAndreas Gohr    global $auth;
453585bf44eSChristopher Smith    /* @var Input $INPUT */
454585bf44eSChristopher Smith    global $INPUT;
455585bf44eSChristopher Smith
456f8cc712eSAndreas Gohr
457beca106aSAdrian Lang    if(!$auth) return false;
458c66972f2SAdrian Lang    if(is_null($user)) {
459585bf44eSChristopher Smith        if(!$INPUT->server->has('REMOTE_USER')) {
460c66972f2SAdrian Lang            return false;
461c66972f2SAdrian Lang        } else {
462585bf44eSChristopher Smith            $user = $INPUT->server->str('REMOTE_USER');
463c66972f2SAdrian Lang        }
464c66972f2SAdrian Lang    }
465d6dc956fSAndreas Gohr    if(is_null($groups)) {
466d6dc956fSAndreas Gohr        $groups = (array) $USERINFO['grps'];
467e259aa79SAndreas Gohr    }
468e259aa79SAndreas Gohr
469d6dc956fSAndreas Gohr    // check superuser match
470d6dc956fSAndreas Gohr    if(auth_isMember($conf['superuser'], $user, $groups)) return true;
471d6dc956fSAndreas Gohr    if($adminonly) return false;
472e259aa79SAndreas Gohr    // check managers
473d6dc956fSAndreas Gohr    if(auth_isMember($conf['manager'], $user, $groups)) return true;
47400ce12daSChris Smith
475f8cc712eSAndreas Gohr    return false;
476f8cc712eSAndreas Gohr}
477f8cc712eSAndreas Gohr
478f8cc712eSAndreas Gohr/**
479f8cc712eSAndreas Gohr * Check if a user is admin
480f8cc712eSAndreas Gohr *
481f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
482f8cc712eSAndreas Gohr *
483f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
484f8cc712eSAndreas Gohr *
485f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
486ab5d26daSAndreas Gohr * @see auth_ismanager()
48742ea7f44SGerrit Uitslag *
488ab5d26daSAndreas Gohr * @param  string $user       Username
489ab5d26daSAndreas Gohr * @param  array  $groups     List of groups the user is in
490ab5d26daSAndreas Gohr * @return bool
491f8cc712eSAndreas Gohr */
492f8cc712eSAndreas Gohrfunction auth_isadmin($user = null, $groups = null) {
493f8cc712eSAndreas Gohr    return auth_ismanager($user, $groups, true);
494f8cc712eSAndreas Gohr}
495f8cc712eSAndreas Gohr
496d6dc956fSAndreas Gohr/**
497d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
498d6dc956fSAndreas Gohr * users and groups to determine membership status
499d6dc956fSAndreas Gohr *
500d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
501d6dc956fSAndreas Gohr *
50242ea7f44SGerrit Uitslag * @param string $memberlist commaseparated list of allowed users and groups
50342ea7f44SGerrit Uitslag * @param string $user       user to match against
50442ea7f44SGerrit Uitslag * @param array  $groups     groups the user is member of
5055446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
506d6dc956fSAndreas Gohr */
507d6dc956fSAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups) {
50827058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
509d6dc956fSAndreas Gohr    global $auth;
510d6dc956fSAndreas Gohr    if(!$auth) return false;
511d6dc956fSAndreas Gohr
512d6dc956fSAndreas Gohr    // clean user and groups
5134f56ecbfSAdrian Lang    if(!$auth->isCaseSensitive()) {
514d6dc956fSAndreas Gohr        $user   = utf8_strtolower($user);
515d6dc956fSAndreas Gohr        $groups = array_map('utf8_strtolower', $groups);
516d6dc956fSAndreas Gohr    }
517d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
518d6dc956fSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), $groups);
519d6dc956fSAndreas Gohr
520d6dc956fSAndreas Gohr    // extract the memberlist
521d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
522d6dc956fSAndreas Gohr    $members = array_map('trim', $members);
523d6dc956fSAndreas Gohr    $members = array_unique($members);
524d6dc956fSAndreas Gohr    $members = array_filter($members);
525d6dc956fSAndreas Gohr
526d6dc956fSAndreas Gohr    // compare cleaned values
527d6dc956fSAndreas Gohr    foreach($members as $member) {
528e5204a12SJurgen Hart        if($member == '@ALL' ) return true;
5294f56ecbfSAdrian Lang        if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member);
530d6dc956fSAndreas Gohr        if($member[0] == '@') {
531d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
532d6dc956fSAndreas Gohr            if(in_array($member, $groups)) return true;
533d6dc956fSAndreas Gohr        } else {
534d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
535d6dc956fSAndreas Gohr            if($member == $user) return true;
536d6dc956fSAndreas Gohr        }
537d6dc956fSAndreas Gohr    }
538d6dc956fSAndreas Gohr
539d6dc956fSAndreas Gohr    // still here? not a member!
540d6dc956fSAndreas Gohr    return false;
541d6dc956fSAndreas Gohr}
542d6dc956fSAndreas Gohr
543f8cc712eSAndreas Gohr/**
54415fae107Sandi * Convinience function for auth_aclcheck()
54515fae107Sandi *
54615fae107Sandi * This checks the permissions for the current user
54715fae107Sandi *
54815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
54915fae107Sandi *
5501698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
55115fae107Sandi * @return int          permission level
552f3f0262cSandi */
553f3f0262cSandifunction auth_quickaclcheck($id) {
554f3f0262cSandi    global $conf;
555f3f0262cSandi    global $USERINFO;
556585bf44eSChristopher Smith    /* @var Input $INPUT */
557585bf44eSChristopher Smith    global $INPUT;
558f3f0262cSandi    # if no ACL is used always return upload rights
559f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
560585bf44eSChristopher Smith    return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), $USERINFO['grps']);
561f3f0262cSandi}
562f3f0262cSandi
563f3f0262cSandi/**
564c17acc9fSAndreas Gohr * Returns the maximum rights a user has for the given ID or its namespace
56515fae107Sandi *
56615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
56742ea7f44SGerrit Uitslag *
568c17acc9fSAndreas Gohr * @triggers AUTH_ACL_CHECK
5691698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
57015fae107Sandi * @param  string       $user   Username
5713272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
57215fae107Sandi * @return int             permission level
573f3f0262cSandi */
574f3f0262cSandifunction auth_aclcheck($id, $user, $groups) {
575c17acc9fSAndreas Gohr    $data = array(
576c17acc9fSAndreas Gohr        'id'     => $id,
577c17acc9fSAndreas Gohr        'user'   => $user,
578c17acc9fSAndreas Gohr        'groups' => $groups
579c17acc9fSAndreas Gohr    );
580c17acc9fSAndreas Gohr
581c17acc9fSAndreas Gohr    return trigger_event('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
582c17acc9fSAndreas Gohr}
583c17acc9fSAndreas Gohr
584c17acc9fSAndreas Gohr/**
585c17acc9fSAndreas Gohr * default ACL check method
586c17acc9fSAndreas Gohr *
587c17acc9fSAndreas Gohr * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
588c17acc9fSAndreas Gohr *
589c17acc9fSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
59042ea7f44SGerrit Uitslag *
591c17acc9fSAndreas Gohr * @param  array $data event data
592c17acc9fSAndreas Gohr * @return int   permission level
593c17acc9fSAndreas Gohr */
594c17acc9fSAndreas Gohrfunction auth_aclcheck_cb($data) {
595c17acc9fSAndreas Gohr    $id     =& $data['id'];
596c17acc9fSAndreas Gohr    $user   =& $data['user'];
597c17acc9fSAndreas Gohr    $groups =& $data['groups'];
598c17acc9fSAndreas Gohr
599f3f0262cSandi    global $conf;
600f3f0262cSandi    global $AUTH_ACL;
60127058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
602d752aedeSAndreas Gohr    global $auth;
603f3f0262cSandi
60485d03f68SAndreas Gohr    // if no ACL is used always return upload rights
605f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
606beca106aSAdrian Lang    if(!$auth) return AUTH_NONE;
607f3f0262cSandi
608074cf26bSandi    //make sure groups is an array
609074cf26bSandi    if(!is_array($groups)) $groups = array();
610074cf26bSandi
61185d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
612ab5d26daSAndreas Gohr    if(auth_isadmin($user, $groups)) {
613ab5d26daSAndreas Gohr        return AUTH_ADMIN;
614ab5d26daSAndreas Gohr    }
61585d03f68SAndreas Gohr
616eb3ce0d5SKazutaka Miyasaka    if(!$auth->isCaseSensitive()) {
617eb3ce0d5SKazutaka Miyasaka        $user   = utf8_strtolower($user);
618eb3ce0d5SKazutaka Miyasaka        $groups = array_map('utf8_strtolower', $groups);
619eb3ce0d5SKazutaka Miyasaka    }
62037ff2261SSascha Klopp    $user   = auth_nameencode($auth->cleanUser($user));
621d752aedeSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
62285d03f68SAndreas Gohr
6236c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
62437ff2261SSascha Klopp    foreach($groups as &$group) {
62537ff2261SSascha Klopp        $group = '@'.auth_nameencode($group);
62610a76f6fSfrank    }
62710a76f6fSfrank
628f3f0262cSandi    $ns   = getNS($id);
629f3f0262cSandi    $perm = -1;
630f3f0262cSandi
631f3f0262cSandi    //add ALL group
632f3f0262cSandi    $groups[] = '@ALL';
63337ff2261SSascha Klopp
634f3f0262cSandi    //add User
63534aeb4afSAndreas Gohr    if($user) $groups[] = $user;
636f3f0262cSandi
637f3f0262cSandi    //check exact match first
63821c3090aSChristopher Smith    $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
639f3f0262cSandi    if(count($matches)) {
640f3f0262cSandi        foreach($matches as $match) {
641f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
64221c3090aSChristopher Smith            $acl   = preg_split('/[ \t]+/', $match);
643eb3ce0d5SKazutaka Miyasaka            if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
644eb3ce0d5SKazutaka Miyasaka                $acl[1] = utf8_strtolower($acl[1]);
645eb3ce0d5SKazutaka Miyasaka            }
64648d7b7a6SDominik Eckelmann            if(!in_array($acl[1], $groups)) {
64748d7b7a6SDominik Eckelmann                continue;
64848d7b7a6SDominik Eckelmann            }
6498ef6b7caSandi            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
650f3f0262cSandi            if($acl[2] > $perm) {
651f3f0262cSandi                $perm = $acl[2];
652f3f0262cSandi            }
653f3f0262cSandi        }
654f3f0262cSandi        if($perm > -1) {
655f3f0262cSandi            //we had a match - return it
656def492a2SGuillaume Turri            return (int) $perm;
657f3f0262cSandi        }
658f3f0262cSandi    }
659f3f0262cSandi
660f3f0262cSandi    //still here? do the namespace checks
661f3f0262cSandi    if($ns) {
6623e304b55SMichael Hamann        $path = $ns.':*';
663f3f0262cSandi    } else {
6643e304b55SMichael Hamann        $path = '*'; //root document
665f3f0262cSandi    }
666f3f0262cSandi
667f3f0262cSandi    do {
66821c3090aSChristopher Smith        $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
669f3f0262cSandi        if(count($matches)) {
670f3f0262cSandi            foreach($matches as $match) {
671f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
67221c3090aSChristopher Smith                $acl   = preg_split('/[ \t]+/', $match);
673eb3ce0d5SKazutaka Miyasaka                if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
674eb3ce0d5SKazutaka Miyasaka                    $acl[1] = utf8_strtolower($acl[1]);
675eb3ce0d5SKazutaka Miyasaka                }
67648d7b7a6SDominik Eckelmann                if(!in_array($acl[1], $groups)) {
67748d7b7a6SDominik Eckelmann                    continue;
67848d7b7a6SDominik Eckelmann                }
6798ef6b7caSandi                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
680f3f0262cSandi                if($acl[2] > $perm) {
681f3f0262cSandi                    $perm = $acl[2];
682f3f0262cSandi                }
683f3f0262cSandi            }
684f3f0262cSandi            //we had a match - return it
68548d7b7a6SDominik Eckelmann            if($perm != -1) {
686def492a2SGuillaume Turri                return (int) $perm;
687f3f0262cSandi            }
68848d7b7a6SDominik Eckelmann        }
689f3f0262cSandi        //get next higher namespace
690f3f0262cSandi        $ns = getNS($ns);
691f3f0262cSandi
6923e304b55SMichael Hamann        if($path != '*') {
6933e304b55SMichael Hamann            $path = $ns.':*';
6943e304b55SMichael Hamann            if($path == ':*') $path = '*';
695f3f0262cSandi        } else {
696f3f0262cSandi            //we did this already
697f3f0262cSandi            //looks like there is something wrong with the ACL
698f3f0262cSandi            //break here
699d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
700d5ce66f6SAndreas Gohr            return AUTH_NONE;
701f3f0262cSandi        }
702f3f0262cSandi    } while(1); //this should never loop endless
703ab5d26daSAndreas Gohr    return AUTH_NONE;
704f3f0262cSandi}
705f3f0262cSandi
706f3f0262cSandi/**
7076c2bb100SAndreas Gohr * Encode ASCII special chars
7086c2bb100SAndreas Gohr *
7096c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
7106c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
7116c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
7126c2bb100SAndreas Gohr * urlencoding!).
7136c2bb100SAndreas Gohr *
7146c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
7156c2bb100SAndreas Gohr *
7166c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
7176c2bb100SAndreas Gohr * @see rawurldecode()
71842ea7f44SGerrit Uitslag *
71942ea7f44SGerrit Uitslag * @param string $name
72042ea7f44SGerrit Uitslag * @param bool $skip_group
72142ea7f44SGerrit Uitslag * @return string
7226c2bb100SAndreas Gohr */
723e838fc2eSAndreas Gohrfunction auth_nameencode($name, $skip_group = false) {
724a424cd8eSchris    global $cache_authname;
725a424cd8eSchris    $cache =& $cache_authname;
72631784267SAndreas Gohr    $name  = (string) $name;
727a424cd8eSchris
72880601d26SAndreas Gohr    // never encode wildcard FS#1955
72980601d26SAndreas Gohr    if($name == '%USER%') return $name;
730b78bf706Sromain    if($name == '%GROUP%') return $name;
73180601d26SAndreas Gohr
732a424cd8eSchris    if(!isset($cache[$name][$skip_group])) {
733e838fc2eSAndreas Gohr        if($skip_group && $name{0} == '@') {
73430f6faf0SChristopher Smith            $cache[$name][$skip_group] = '@'.preg_replace_callback(
73530f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
73630f6faf0SChristopher Smith                'auth_nameencode_callback', substr($name, 1)
737ab5d26daSAndreas Gohr            );
738e838fc2eSAndreas Gohr        } else {
73930f6faf0SChristopher Smith            $cache[$name][$skip_group] = preg_replace_callback(
74030f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
74130f6faf0SChristopher Smith                'auth_nameencode_callback', $name
742ab5d26daSAndreas Gohr            );
743e838fc2eSAndreas Gohr        }
7446c2bb100SAndreas Gohr    }
7456c2bb100SAndreas Gohr
746a424cd8eSchris    return $cache[$name][$skip_group];
747a424cd8eSchris}
748a424cd8eSchris
74904d68ae4SGerrit Uitslag/**
75004d68ae4SGerrit Uitslag * callback encodes the matches
75104d68ae4SGerrit Uitslag *
75204d68ae4SGerrit Uitslag * @param array $matches first complete match, next matching subpatterms
75304d68ae4SGerrit Uitslag * @return string
75404d68ae4SGerrit Uitslag */
75530f6faf0SChristopher Smithfunction auth_nameencode_callback($matches) {
75630f6faf0SChristopher Smith    return '%'.dechex(ord(substr($matches[1],-1)));
75730f6faf0SChristopher Smith}
75830f6faf0SChristopher Smith
7596c2bb100SAndreas Gohr/**
760f3f0262cSandi * Create a pronouncable password
761f3f0262cSandi *
7628a285f7fSAndreas Gohr * The $foruser variable might be used by plugins to run additional password
7638a285f7fSAndreas Gohr * policy checks, but is not used by the default implementation
7648a285f7fSAndreas Gohr *
76515fae107Sandi * @author   Andreas Gohr <andi@splitbrain.org>
76615fae107Sandi * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
7678a285f7fSAndreas Gohr * @triggers AUTH_PASSWORD_GENERATE
76815fae107Sandi *
7698a285f7fSAndreas Gohr * @param  string $foruser username for which the password is generated
77015fae107Sandi * @return string  pronouncable password
771f3f0262cSandi */
7728a285f7fSAndreas Gohrfunction auth_pwgen($foruser = '') {
7738a285f7fSAndreas Gohr    $data = array(
774d628dcf3SAndreas Gohr        'password' => '',
775d628dcf3SAndreas Gohr        'foruser'  => $foruser
7768a285f7fSAndreas Gohr    );
7778a285f7fSAndreas Gohr
7788a285f7fSAndreas Gohr    $evt = new Doku_Event('AUTH_PASSWORD_GENERATE', $data);
7798a285f7fSAndreas Gohr    if($evt->advise_before(true)) {
780f3f0262cSandi        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
781f3f0262cSandi        $v = 'aeiou'; //vowels
782f3f0262cSandi        $a = $c.$v; //both
783987c8d26SAndreas Gohr        $s = '!$%&?+*~#-_:.;,'; // specials
784f3f0262cSandi
785987c8d26SAndreas Gohr        //use thre syllables...
786987c8d26SAndreas Gohr        for($i = 0; $i < 3; $i++) {
787483b6238SMichael Hamann            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
788483b6238SMichael Hamann            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
789483b6238SMichael Hamann            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
790f3f0262cSandi        }
791987c8d26SAndreas Gohr        //... and add a nice number and special
792483b6238SMichael Hamann        $data['password'] .= auth_random(10, 99).$s[auth_random(0, strlen($s) - 1)];
7938a285f7fSAndreas Gohr    }
7948a285f7fSAndreas Gohr    $evt->advise_after();
795f3f0262cSandi
7968a285f7fSAndreas Gohr    return $data['password'];
797f3f0262cSandi}
798f3f0262cSandi
799f3f0262cSandi/**
800f3f0262cSandi * Sends a password to the given user
801f3f0262cSandi *
80215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
80342ea7f44SGerrit Uitslag *
804ab5d26daSAndreas Gohr * @param string $user Login name of the user
805ab5d26daSAndreas Gohr * @param string $password The new password in clear text
80615fae107Sandi * @return bool  true on success
807f3f0262cSandi */
808f3f0262cSandifunction auth_sendPassword($user, $password) {
809f3f0262cSandi    global $lang;
81027058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
811cd52f92dSchris    global $auth;
812beca106aSAdrian Lang    if(!$auth) return false;
813cd52f92dSchris
814d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
8152dc9e900SChristopher Smith    $userinfo = $auth->getUserData($user, $requireGroups = false);
816f3f0262cSandi
81787ddda95Sandi    if(!$userinfo['mail']) return false;
818f3f0262cSandi
819f3f0262cSandi    $text = rawLocale('password');
820d7169d19SAndreas Gohr    $trep = array(
821d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
822d7169d19SAndreas Gohr        'LOGIN'    => $user,
823d7169d19SAndreas Gohr        'PASSWORD' => $password
824d7169d19SAndreas Gohr    );
825f3f0262cSandi
826d7169d19SAndreas Gohr    $mail = new Mailer();
827d7169d19SAndreas Gohr    $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
828d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
829d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
830d7169d19SAndreas Gohr    return $mail->send();
831f3f0262cSandi}
832f3f0262cSandi
833f3f0262cSandi/**
83415fae107Sandi * Register a new user
835f3f0262cSandi *
83615fae107Sandi * This registers a new user - Data is read directly from $_POST
83715fae107Sandi *
83815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
83942ea7f44SGerrit Uitslag *
84015fae107Sandi * @return bool  true on success, false on any error
841f3f0262cSandi */
842f3f0262cSandifunction register() {
843f3f0262cSandi    global $lang;
844eb5d07e4Sjan    global $conf;
84527058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
846cd52f92dSchris    global $auth;
84764273335SAndreas Gohr    global $INPUT;
848f3f0262cSandi
84964273335SAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
8503a48618aSAnika Henke    if(!actionOK('register')) return false;
851640145a5Sandi
85264273335SAndreas Gohr    // gather input
85364273335SAndreas Gohr    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
85464273335SAndreas Gohr    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
85564273335SAndreas Gohr    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
85664273335SAndreas Gohr    $pass     = $INPUT->post->str('pass');
85764273335SAndreas Gohr    $passchk  = $INPUT->post->str('passchk');
858d752aedeSAndreas Gohr
85964273335SAndreas Gohr    if(empty($login) || empty($fullname) || empty($email)) {
860f3f0262cSandi        msg($lang['regmissing'], -1);
861f3f0262cSandi        return false;
862f3f0262cSandi    }
863f3f0262cSandi
864cab2716aSmatthias.grimm    if($conf['autopasswd']) {
8658a285f7fSAndreas Gohr        $pass = auth_pwgen($login); // automatically generate password
86664273335SAndreas Gohr    } elseif(empty($pass) || empty($passchk)) {
867bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
868cab2716aSmatthias.grimm        return false;
86964273335SAndreas Gohr    } elseif($pass != $passchk) {
870bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
871cab2716aSmatthias.grimm        return false;
872cab2716aSmatthias.grimm    }
873cab2716aSmatthias.grimm
874f3f0262cSandi    //check mail
87564273335SAndreas Gohr    if(!mail_isvalid($email)) {
876f3f0262cSandi        msg($lang['regbadmail'], -1);
877f3f0262cSandi        return false;
878f3f0262cSandi    }
879f3f0262cSandi
880f3f0262cSandi    //okay try to create the user
88164273335SAndreas Gohr    if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) {
882db9faf02SPatrick Brown        msg($lang['regfail'], -1);
883f3f0262cSandi        return false;
884f3f0262cSandi    }
885f3f0262cSandi
886790b7720SAndreas Gohr    // send notification about the new user
887790b7720SAndreas Gohr    $subscription = new Subscription();
888790b7720SAndreas Gohr    $subscription->send_register($login, $fullname, $email);
88902a498e7Schris
890790b7720SAndreas Gohr    // are we done?
891cab2716aSmatthias.grimm    if(!$conf['autopasswd']) {
892cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
893cab2716aSmatthias.grimm        return true;
894cab2716aSmatthias.grimm    }
895cab2716aSmatthias.grimm
896790b7720SAndreas Gohr    // autogenerated password? then send password to user
89764273335SAndreas Gohr    if(auth_sendPassword($login, $pass)) {
898f3f0262cSandi        msg($lang['regsuccess'], 1);
899f3f0262cSandi        return true;
900f3f0262cSandi    } else {
901f3f0262cSandi        msg($lang['regmailfail'], -1);
902f3f0262cSandi        return false;
903f3f0262cSandi    }
904f3f0262cSandi}
905f3f0262cSandi
90610a76f6fSfrank/**
9078b06d178Schris * Update user profile
9088b06d178Schris *
9098b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
9108b06d178Schris */
9118b06d178Schrisfunction updateprofile() {
9128b06d178Schris    global $conf;
9138b06d178Schris    global $lang;
91427058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
915cd52f92dSchris    global $auth;
916bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
917bcc94b2cSAndreas Gohr    global $INPUT;
9188b06d178Schris
919bcc94b2cSAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
9201b2a85e8SAndreas Gohr    if(!checkSecurityToken()) return false;
9218b06d178Schris
9223a48618aSAnika Henke    if(!actionOK('profile')) {
9238b06d178Schris        msg($lang['profna'], -1);
9248b06d178Schris        return false;
9258b06d178Schris    }
9268b06d178Schris
927bcc94b2cSAndreas Gohr    $changes         = array();
928bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
929bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
930bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
931bcc94b2cSAndreas Gohr
932bcc94b2cSAndreas Gohr    // check misspelled passwords
933bcc94b2cSAndreas Gohr    if($changes['pass'] != $INPUT->post->str('passchk')) {
934bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
9358b06d178Schris        return false;
9368b06d178Schris    }
9378b06d178Schris
9388b06d178Schris    // clean fullname and email
939bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
940bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
9418b06d178Schris
942bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
943bcc94b2cSAndreas Gohr    if((empty($changes['name']) && $auth->canDo('modName')) ||
944bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
945ab5d26daSAndreas Gohr    ) {
9468b06d178Schris        msg($lang['profnoempty'], -1);
9478b06d178Schris        return false;
9488b06d178Schris    }
949bcc94b2cSAndreas Gohr    if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
9508b06d178Schris        msg($lang['regbadmail'], -1);
9518b06d178Schris        return false;
9528b06d178Schris    }
9538b06d178Schris
954bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
9554c21b7eeSAndreas Gohr
956bcc94b2cSAndreas Gohr    // check for unavailable capabilities
957bcc94b2cSAndreas Gohr    if(!$auth->canDo('modName')) unset($changes['name']);
958bcc94b2cSAndreas Gohr    if(!$auth->canDo('modMail')) unset($changes['mail']);
959bcc94b2cSAndreas Gohr    if(!$auth->canDo('modPass')) unset($changes['pass']);
960bcc94b2cSAndreas Gohr
961bcc94b2cSAndreas Gohr    // anything to do?
9628b06d178Schris    if(!count($changes)) {
9638b06d178Schris        msg($lang['profnochange'], -1);
9648b06d178Schris        return false;
9658b06d178Schris    }
9668b06d178Schris
9678b06d178Schris    if($conf['profileconfirm']) {
968585bf44eSChristopher Smith        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
96971422fc8SChristopher Smith            msg($lang['badpassconfirm'], -1);
9708b06d178Schris            return false;
9718b06d178Schris        }
9728b06d178Schris    }
9738b06d178Schris
974e6c4392fSPatrick Brown    if(!$auth->triggerUserMod('modify', array($INPUT->server->str('REMOTE_USER'), &$changes))) {
975db9faf02SPatrick Brown        msg($lang['proffail'], -1);
976db9faf02SPatrick Brown        return false;
977db9faf02SPatrick Brown    }
978db9faf02SPatrick Brown
97932ed2b36SAndreas Gohr    if($changes['pass']) {
980c276e9e8SMarcel Pennewiss        // update cookie and session with the changed data
981ab5d26daSAndreas Gohr        list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
98204369c3eSMichael Hamann        $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
983585bf44eSChristopher Smith        auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
984c276e9e8SMarcel Pennewiss    } else {
985c276e9e8SMarcel Pennewiss        // make sure the session is writable
986c276e9e8SMarcel Pennewiss        @session_start();
987c276e9e8SMarcel Pennewiss        // invalidate session cache
988c276e9e8SMarcel Pennewiss        $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
989c276e9e8SMarcel Pennewiss        session_write_close();
99032ed2b36SAndreas Gohr    }
991c276e9e8SMarcel Pennewiss
99225b2a98cSMichael Klier    return true;
993a0b5b007SChris Smith}
994ab5d26daSAndreas Gohr
99504d68ae4SGerrit Uitslag/**
99604d68ae4SGerrit Uitslag * Delete the current logged-in user
99704d68ae4SGerrit Uitslag *
99804d68ae4SGerrit Uitslag * @return bool true on success, false on any error
99904d68ae4SGerrit Uitslag */
10002a7abf2dSChristopher Smithfunction auth_deleteprofile(){
10012a7abf2dSChristopher Smith    global $conf;
10022a7abf2dSChristopher Smith    global $lang;
100373012efdSChristopher Smith    /* @var DokuWiki_Auth_Plugin $auth */
10042a7abf2dSChristopher Smith    global $auth;
10052a7abf2dSChristopher Smith    /* @var Input $INPUT */
10062a7abf2dSChristopher Smith    global $INPUT;
10072a7abf2dSChristopher Smith
10082a7abf2dSChristopher Smith    if(!$INPUT->post->bool('delete')) return false;
10092a7abf2dSChristopher Smith    if(!checkSecurityToken()) return false;
10102a7abf2dSChristopher Smith
10112a7abf2dSChristopher Smith    // action prevented or auth module disallows
10122a7abf2dSChristopher Smith    if(!actionOK('profile_delete') || !$auth->canDo('delUser')) {
10132a7abf2dSChristopher Smith        msg($lang['profnodelete'], -1);
10142a7abf2dSChristopher Smith        return false;
10152a7abf2dSChristopher Smith    }
10162a7abf2dSChristopher Smith
10172a7abf2dSChristopher Smith    if(!$INPUT->post->bool('confirm_delete')){
10182a7abf2dSChristopher Smith        msg($lang['profconfdeletemissing'], -1);
10192a7abf2dSChristopher Smith        return false;
10202a7abf2dSChristopher Smith    }
10212a7abf2dSChristopher Smith
10222a7abf2dSChristopher Smith    if($conf['profileconfirm']) {
1023585bf44eSChristopher Smith        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
10242a7abf2dSChristopher Smith            msg($lang['badpassconfirm'], -1);
10252a7abf2dSChristopher Smith            return false;
10262a7abf2dSChristopher Smith        }
10272a7abf2dSChristopher Smith    }
10282a7abf2dSChristopher Smith
102959bc3b48SGerrit Uitslag    $deleted = array();
1030585bf44eSChristopher Smith    $deleted[] = $INPUT->server->str('REMOTE_USER');
103173012efdSChristopher Smith    if($auth->triggerUserMod('delete', array($deleted))) {
10322a7abf2dSChristopher Smith        // force and immediate logout including removing the sticky cookie
10332a7abf2dSChristopher Smith        auth_logoff();
10342a7abf2dSChristopher Smith        return true;
10352a7abf2dSChristopher Smith    }
10362a7abf2dSChristopher Smith
10372a7abf2dSChristopher Smith    return false;
10382a7abf2dSChristopher Smith}
10392a7abf2dSChristopher Smith
10408b06d178Schris/**
10418b06d178Schris * Send a  new password
10428b06d178Schris *
10431d5856cfSAndreas Gohr * This function handles both phases of the password reset:
10441d5856cfSAndreas Gohr *
10451d5856cfSAndreas Gohr *   - handling the first request of password reset
10461d5856cfSAndreas Gohr *   - validating the password reset auth token
10471d5856cfSAndreas Gohr *
10488b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
10498b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
10501d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10518b06d178Schris *
10528b06d178Schris * @return bool true on success, false on any error
10538b06d178Schris */
10548b06d178Schrisfunction act_resendpwd() {
10558b06d178Schris    global $lang;
10568b06d178Schris    global $conf;
105727058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
1058cd52f92dSchris    global $auth;
1059bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1060bcc94b2cSAndreas Gohr    global $INPUT;
10618b06d178Schris
10623a48618aSAnika Henke    if(!actionOK('resendpwd')) {
10638b06d178Schris        msg($lang['resendna'], -1);
10648b06d178Schris        return false;
10658b06d178Schris    }
10668b06d178Schris
1067bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
10688b06d178Schris
10691d5856cfSAndreas Gohr    if($token) {
1070cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
10711d5856cfSAndreas Gohr
10721d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
107379e79377SAndreas Gohr        if(!file_exists($tfile)) {
10741d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1075bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
10761d5856cfSAndreas Gohr            return false;
10771d5856cfSAndreas Gohr        }
10788a9735e3SAndreas Gohr        // token is only valid for 3 days
10798a9735e3SAndreas Gohr        if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
10808a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1081bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
10821d5856cfSAndreas Gohr            @unlink($tfile);
10838a9735e3SAndreas Gohr            return false;
10848a9735e3SAndreas Gohr        }
10858a9735e3SAndreas Gohr
10868b06d178Schris        $user     = io_readfile($tfile);
10872dc9e900SChristopher Smith        $userinfo = $auth->getUserData($user, $requireGroups = false);
10888b06d178Schris        if(!$userinfo['mail']) {
10898b06d178Schris            msg($lang['resendpwdnouser'], -1);
10908b06d178Schris            return false;
10918b06d178Schris        }
10928b06d178Schris
1093cc204bbdSAndreas Gohr        if(!$conf['autopasswd']) { // we let the user choose a password
1094bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
1095bcc94b2cSAndreas Gohr
1096cc204bbdSAndreas Gohr            // password given correctly?
1097bcc94b2cSAndreas Gohr            if(!$pass) return false;
1098bcc94b2cSAndreas Gohr            if($pass != $INPUT->str('passchk')) {
1099451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
1100cc204bbdSAndreas Gohr                return false;
1101cc204bbdSAndreas Gohr            }
1102cc204bbdSAndreas Gohr
1103bcc94b2cSAndreas Gohr            // change it
1104cc204bbdSAndreas Gohr            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1105db9faf02SPatrick Brown                msg($lang['proffail'], -1);
1106cc204bbdSAndreas Gohr                return false;
1107cc204bbdSAndreas Gohr            }
1108cc204bbdSAndreas Gohr
1109cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
1110cc204bbdSAndreas Gohr
11118a285f7fSAndreas Gohr            $pass = auth_pwgen($user);
11127d3c8d42SGabriel Birke            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1113db9faf02SPatrick Brown                msg($lang['proffail'], -1);
11148b06d178Schris                return false;
11158b06d178Schris            }
11168b06d178Schris
11178b06d178Schris            if(auth_sendPassword($user, $pass)) {
11188b06d178Schris                msg($lang['resendpwdsuccess'], 1);
11198b06d178Schris            } else {
11208b06d178Schris                msg($lang['regmailfail'], -1);
11218b06d178Schris            }
1122cc204bbdSAndreas Gohr        }
1123cc204bbdSAndreas Gohr
1124cc204bbdSAndreas Gohr        @unlink($tfile);
11258b06d178Schris        return true;
11261d5856cfSAndreas Gohr
11271d5856cfSAndreas Gohr    } else {
11281d5856cfSAndreas Gohr        // we're in request phase
11291d5856cfSAndreas Gohr
1130bcc94b2cSAndreas Gohr        if(!$INPUT->post->bool('save')) return false;
11311d5856cfSAndreas Gohr
1132bcc94b2cSAndreas Gohr        if(!$INPUT->post->str('login')) {
11331d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
11341d5856cfSAndreas Gohr            return false;
11351d5856cfSAndreas Gohr        } else {
1136bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
11371d5856cfSAndreas Gohr        }
11381d5856cfSAndreas Gohr
11392dc9e900SChristopher Smith        $userinfo = $auth->getUserData($user, $requireGroups = false);
11401d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
11411d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
11421d5856cfSAndreas Gohr            return false;
11431d5856cfSAndreas Gohr        }
11441d5856cfSAndreas Gohr
11451d5856cfSAndreas Gohr        // generate auth token
1146483b6238SMichael Hamann        $token = md5(auth_randombytes(16)); // random secret
11471d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
11481d5856cfSAndreas Gohr        $url   = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
11491d5856cfSAndreas Gohr
11501d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
11511d5856cfSAndreas Gohr
11521d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
1153d7169d19SAndreas Gohr        $trep = array(
1154d7169d19SAndreas Gohr            'FULLNAME' => $userinfo['name'],
1155d7169d19SAndreas Gohr            'LOGIN'    => $user,
1156d7169d19SAndreas Gohr            'CONFIRM'  => $url
1157d7169d19SAndreas Gohr        );
11581d5856cfSAndreas Gohr
1159d7169d19SAndreas Gohr        $mail = new Mailer();
1160d7169d19SAndreas Gohr        $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1161d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
1162d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
1163d7169d19SAndreas Gohr        if($mail->send()) {
11641d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
11651d5856cfSAndreas Gohr        } else {
11661d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
11671d5856cfSAndreas Gohr        }
11681d5856cfSAndreas Gohr        return true;
11691d5856cfSAndreas Gohr    }
1170ab5d26daSAndreas Gohr    // never reached
11718b06d178Schris}
11728b06d178Schris
11738b06d178Schris/**
1174b0855b11Sandi * Encrypts a password using the given method and salt
1175b0855b11Sandi *
1176b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1177b0855b11Sandi * is chosen.
1178b0855b11Sandi *
1179b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
118042ea7f44SGerrit Uitslag *
1181ab5d26daSAndreas Gohr * @param string $clear The clear text password
1182ab5d26daSAndreas Gohr * @param string $method The hashing method
1183ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1184b0855b11Sandi * @return  string  The crypted password
1185b0855b11Sandi */
1186577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null) {
1187b0855b11Sandi    global $conf;
1188b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
118910a76f6fSfrank
11903a0a2d05SAndreas Gohr    $pass = new PassHash();
11913a0a2d05SAndreas Gohr    $call = 'hash_'.$method;
1192b0855b11Sandi
11933a0a2d05SAndreas Gohr    if(!method_exists($pass, $call)) {
1194b0855b11Sandi        msg("Unsupported crypt method $method", -1);
11953a0a2d05SAndreas Gohr        return false;
1196b0855b11Sandi    }
11973a0a2d05SAndreas Gohr
11983a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1199b0855b11Sandi}
1200b0855b11Sandi
1201b0855b11Sandi/**
1202b0855b11Sandi * Verifies a cleartext password against a crypted hash
1203b0855b11Sandi *
1204b0855b11Sandi * @author Andreas Gohr <andi@splitbrain.org>
120542ea7f44SGerrit Uitslag *
1206ab5d26daSAndreas Gohr * @param  string $clear The clear text password
1207ab5d26daSAndreas Gohr * @param  string $crypt The hash to compare with
1208ab5d26daSAndreas Gohr * @return bool true if both match
1209b0855b11Sandi */
1210b0855b11Sandifunction auth_verifyPassword($clear, $crypt) {
12113a0a2d05SAndreas Gohr    $pass = new PassHash();
12123a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1213b0855b11Sandi}
1214340756e4Sandi
1215a0b5b007SChris Smith/**
1216a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1217a0b5b007SChris Smith *
1218a0b5b007SChris Smith * @param string  $user       username
1219a0b5b007SChris Smith * @param string  $pass       encrypted password
1220a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1221ab5d26daSAndreas Gohr * @return bool
1222a0b5b007SChris Smith */
1223a0b5b007SChris Smithfunction auth_setCookie($user, $pass, $sticky) {
1224a0b5b007SChris Smith    global $conf;
122527058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
1226a0b5b007SChris Smith    global $auth;
122779d00841SOliver Geisen    global $USERINFO;
1228a0b5b007SChris Smith
1229beca106aSAdrian Lang    if(!$auth) return false;
1230a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1231a0b5b007SChris Smith
1232a0b5b007SChris Smith    // set cookie
1233645c0a36SAndreas Gohr    $cookie    = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
123473ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1235c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
123673ab87deSGabriel Birke    setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
123755a71a16SGerrit Uitslag
1238a0b5b007SChris Smith    // set session
1239a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1240234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1241a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1242a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1243a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1244ab5d26daSAndreas Gohr
1245ab5d26daSAndreas Gohr    return true;
1246a0b5b007SChris Smith}
1247a0b5b007SChris Smith
1248645c0a36SAndreas Gohr/**
1249645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1250645c0a36SAndreas Gohr *
1251645c0a36SAndreas Gohr * @returns array
1252645c0a36SAndreas Gohr */
1253645c0a36SAndreas Gohrfunction auth_getCookie() {
1254c66972f2SAdrian Lang    if(!isset($_COOKIE[DOKU_COOKIE])) {
1255c66972f2SAdrian Lang        return array(null, null, null);
1256c66972f2SAdrian Lang    }
1257645c0a36SAndreas Gohr    list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
1258645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1259645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1260645c0a36SAndreas Gohr    $user   = base64_decode($user);
1261645c0a36SAndreas Gohr    return array($user, $sticky, $pass);
1262645c0a36SAndreas Gohr}
1263645c0a36SAndreas Gohr
1264e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1265