xref: /dokuwiki/inc/auth.php (revision 30d544a4c371bf69023e4d9958bc2b00d84387d9)
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;
54e71b0ef7SGuy Brand      } elseif ('auth' . $conf['authtype'] === $plugin) {
55e71b0ef7SGuy Brand        // matches old auth backends (pre-Weatherwax)
56e71b0ef7SGuy Brand        $auth = $plugin_controller->load('auth', $plugin);
57a91f1103SAnika Henke        msg('Your authtype setting is deprecated. You must set $conf[\'authtype\'] = "auth' . $conf['authtype'] . '"'
5898e31f85SKlap-in             . ' in your configuration (see <a href="https://www.dokuwiki.org/auth">Authentication Backends</a>)',-1,'','',MSG_ADMINS_ONLY);
599c29eea5SJan Schumann      }
609c29eea5SJan Schumann    }
618b06d178Schris
626416b708SMichael Hamann    if(!isset($auth) || !$auth){
633094e817SAndreas Gohr        msg($lang['authtempfail'], -1);
643094e817SAndreas Gohr        return false;
653094e817SAndreas Gohr    }
668b06d178Schris
676416b708SMichael Hamann    if ($auth->success == false) {
680f4f4adfSAndreas Gohr    // degrade to unauthenticated user
69d2dde4ebSMatthias Grimm      unset($auth);
700f4f4adfSAndreas Gohr      auth_logoff();
71cd52f92dSchris      msg($lang['authtempfail'], -1);
726416b708SMichael Hamann        return false;
73d2dde4ebSMatthias Grimm    }
7416905344SAndreas Gohr
7516905344SAndreas Gohr    // do the login either by cookie or provided credentials XXX
76bcc94b2cSAndreas Gohr    $INPUT->set('http_credentials', false);
77bcc94b2cSAndreas Gohr    if(!$conf['rememberme']) $INPUT->set('r', false);
78bbbd6568SAndreas Gohr
79b2665af7SMichael Hamann    // handle renamed HTTP_AUTHORIZATION variable (can happen when a fix like
80b2665af7SMichael Hamann    // the one presented at
81b2665af7SMichael Hamann    // http://www.besthostratings.com/articles/http-auth-php-cgi.html is used
82b2665af7SMichael Hamann    // for enabling HTTP authentication with CGI/SuExec)
83b2665af7SMichael Hamann    if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
84b2665af7SMichael Hamann        $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
85528ddc7cSAndreas Gohr    // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
8606156f3cSAndreas Gohr    if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
87528ddc7cSAndreas Gohr        list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
88528ddc7cSAndreas Gohr            explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
89528ddc7cSAndreas Gohr    }
90528ddc7cSAndreas Gohr
911e8c9c90SAndreas Gohr    // if no credentials were given try to use HTTP auth (for SSO)
92bcc94b2cSAndreas Gohr    if(!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])) {
93bcc94b2cSAndreas Gohr        $INPUT->set('u', $_SERVER['PHP_AUTH_USER']);
94bcc94b2cSAndreas Gohr        $INPUT->set('p', $_SERVER['PHP_AUTH_PW']);
95bcc94b2cSAndreas Gohr        $INPUT->set('http_credentials', true);
961e8c9c90SAndreas Gohr    }
971e8c9c90SAndreas Gohr
98191bb90aSAndreas Gohr    // apply cleaning
9993a7873eSAndreas Gohr    if (true === $auth->success) {
10000d58927SMichael Hamann        $INPUT->set('u', $auth->cleanUser($INPUT->str('u')));
101f4476bd9SJan Schumann    }
102191bb90aSAndreas Gohr
103bcc94b2cSAndreas Gohr    if($INPUT->str('authtok')) {
104f13fa892SAndreas Gohr        // when an authentication token is given, trust the session
105bcc94b2cSAndreas Gohr        auth_validateToken($INPUT->str('authtok'));
106f13fa892SAndreas Gohr    } elseif(!is_null($auth) && $auth->canDo('external')) {
107f13fa892SAndreas Gohr        // external trust mechanism in place
108bcc94b2cSAndreas Gohr        $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
109f5cb575dSAndreas Gohr    } else {
1106080c584SRobin Gareus        $evdata = array(
111bcc94b2cSAndreas Gohr            'user'     => $INPUT->str('u'),
112bcc94b2cSAndreas Gohr            'password' => $INPUT->str('p'),
113bcc94b2cSAndreas Gohr            'sticky'   => $INPUT->bool('r'),
114bcc94b2cSAndreas Gohr            'silent'   => $INPUT->bool('http_credentials')
1156080c584SRobin Gareus        );
116b5ee21aaSAdrian Lang        trigger_event('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
117f5cb575dSAndreas Gohr    }
118f5cb575dSAndreas Gohr
11916905344SAndreas Gohr    //load ACL into a global array XXX
12075c93b77SAndreas Gohr    $AUTH_ACL = auth_loadACL();
121ab5d26daSAndreas Gohr
122ab5d26daSAndreas Gohr    return true;
12375c93b77SAndreas Gohr}
12475c93b77SAndreas Gohr
12575c93b77SAndreas Gohr/**
12675c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards
12775c93b77SAndreas Gohr *
12875c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
129ab5d26daSAndreas Gohr * @return array
13075c93b77SAndreas Gohr */
13175c93b77SAndreas Gohrfunction auth_loadACL() {
13275c93b77SAndreas Gohr    global $config_cascade;
133b78bf706Sromain    global $USERINFO;
13475c93b77SAndreas Gohr
13575c93b77SAndreas Gohr    if(!is_readable($config_cascade['acl']['default'])) return array();
13675c93b77SAndreas Gohr
13775c93b77SAndreas Gohr    $acl = file($config_cascade['acl']['default']);
13875c93b77SAndreas Gohr
139191bb90aSAndreas Gohr    //support user wildcard
14032e82180SAndreas Gohr    $out = array();
1419ce556d2SAndreas Gohr    foreach($acl as $line) {
1429ce556d2SAndreas Gohr        $line = trim($line);
1439ce556d2SAndreas Gohr        if($line{0} == '#') continue;
1449ce556d2SAndreas Gohr        list($id,$rest) = preg_split('/\s+/',$line,2);
14532e82180SAndreas Gohr
1469ce556d2SAndreas Gohr        if(strstr($line, '%GROUP%')){
1479ce556d2SAndreas Gohr            foreach((array) $USERINFO['grps'] as $grp){
148b78bf706Sromain                $nid   = str_replace('%GROUP%',cleanID($grp),$id);
14932e82180SAndreas Gohr                $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest);
15032e82180SAndreas Gohr                $out[] = "$nid\t$nrest";
151b78bf706Sromain            }
15232e82180SAndreas Gohr        } else {
15375c93b77SAndreas Gohr            $id   = str_replace('%USER%',cleanID($_SERVER['REMOTE_USER']),$id);
15475c93b77SAndreas Gohr            $rest = str_replace('%USER%',auth_nameencode($_SERVER['REMOTE_USER']),$rest);
15532e82180SAndreas Gohr            $out[] = "$id\t$rest";
156a8fe108bSGuy Brand        }
15711799630Sandi    }
1589ce556d2SAndreas Gohr
15932e82180SAndreas Gohr    return $out;
160f3f0262cSandi}
161f3f0262cSandi
162ab5d26daSAndreas Gohr/**
163ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK
164ab5d26daSAndreas Gohr *
165ab5d26daSAndreas Gohr * @param $evdata
166ab5d26daSAndreas Gohr * @return bool
167ab5d26daSAndreas Gohr */
168b5ee21aaSAdrian Langfunction auth_login_wrapper($evdata) {
169ab5d26daSAndreas Gohr    return auth_login(
170ab5d26daSAndreas Gohr        $evdata['user'],
171b5ee21aaSAdrian Lang        $evdata['password'],
172b5ee21aaSAdrian Lang        $evdata['sticky'],
173ab5d26daSAndreas Gohr        $evdata['silent']
174ab5d26daSAndreas Gohr    );
175b5ee21aaSAdrian Lang}
176b5ee21aaSAdrian Lang
177f3f0262cSandi/**
178f3f0262cSandi * This tries to login the user based on the sent auth credentials
179f3f0262cSandi *
180f3f0262cSandi * The authentication works like this: if a username was given
18115fae107Sandi * a new login is assumed and user/password are checked. If they
18215fae107Sandi * are correct the password is encrypted with blowfish and stored
18315fae107Sandi * together with the username in a cookie - the same info is stored
18415fae107Sandi * in the session, too. Additonally a browserID is stored in the
18515fae107Sandi * session.
18615fae107Sandi *
18715fae107Sandi * If no username was given the cookie is checked: if the username,
18815fae107Sandi * crypted password and browserID match between session and cookie
18915fae107Sandi * no further testing is done and the user is accepted
19015fae107Sandi *
19115fae107Sandi * If a cookie was found but no session info was availabe the
192136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
19315fae107Sandi * together with username rechecked by calling this function again.
194f3f0262cSandi *
195f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
196f3f0262cSandi * are set.
19715fae107Sandi *
19815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
19915fae107Sandi *
20015fae107Sandi * @param   string  $user    Username
20115fae107Sandi * @param   string  $pass    Cleartext Password
20215fae107Sandi * @param   bool    $sticky  Cookie should not expire
203f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
20415fae107Sandi * @return  bool             true on successful auth
205f3f0262cSandi */
206f112c2faSAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false) {
207f3f0262cSandi    global $USERINFO;
208f3f0262cSandi    global $conf;
209f3f0262cSandi    global $lang;
21027058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
211cd52f92dSchris    global $auth;
212ab5d26daSAndreas Gohr
213132bdbfeSandi    $sticky ? $sticky = true : $sticky = false; //sanity check
214f3f0262cSandi
215beca106aSAdrian Lang    if(!$auth) return false;
216beca106aSAdrian Lang
217bbbd6568SAndreas Gohr    if(!empty($user)) {
218132bdbfeSandi        //usual login
219cd52f92dSchris        if($auth->checkPass($user, $pass)) {
220132bdbfeSandi            // make logininfo globally available
221f3f0262cSandi            $_SERVER['REMOTE_USER'] = $user;
222*30d544a4SMichael Hamann            $secret                 = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
223e940aea4SAndreas Gohr            auth_setCookie($user, PMA_blowfish_encrypt($pass, $secret), $sticky);
224132bdbfeSandi            return true;
225f3f0262cSandi        } else {
226f3f0262cSandi            //invalid credentials - log off
227f112c2faSAndreas Gohr            if(!$silent) msg($lang['badlogin'], -1);
228f3f0262cSandi            auth_logoff();
229132bdbfeSandi            return false;
230f3f0262cSandi        }
231f3f0262cSandi    } else {
232132bdbfeSandi        // read cookie information
233645c0a36SAndreas Gohr        list($user, $sticky, $pass) = auth_getCookie();
234132bdbfeSandi        if($user && $pass) {
235132bdbfeSandi            // we got a cookie - see if we can trust it
236fa7c70ffSAdrian Lang
237fa7c70ffSAdrian Lang            // get session info
238fa7c70ffSAdrian Lang            $session = $_SESSION[DOKU_COOKIE]['auth'];
239132bdbfeSandi            if(isset($session) &&
2407172dbc0SAndreas Gohr                $auth->useSessionCache($user) &&
2414c989037SChris Smith                ($session['time'] >= time() - $conf['auth_security_timeout']) &&
242132bdbfeSandi                ($session['user'] == $user) &&
243234ce57eSAndreas Gohr                ($session['pass'] == sha1($pass)) && //still crypted
244ab5d26daSAndreas Gohr                ($session['buid'] == auth_browseruid())
245ab5d26daSAndreas Gohr            ) {
246234ce57eSAndreas Gohr
247132bdbfeSandi                // he has session, cookie and browser right - let him in
248132bdbfeSandi                $_SERVER['REMOTE_USER'] = $user;
249132bdbfeSandi                $USERINFO               = $session['info']; //FIXME move all references to session
250132bdbfeSandi                return true;
251132bdbfeSandi            }
252f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
253*30d544a4SMichael Hamann            $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
254e940aea4SAndreas Gohr            $pass   = PMA_blowfish_decrypt($pass, $secret);
255f112c2faSAndreas Gohr            return auth_login($user, $pass, $sticky, true);
256132bdbfeSandi        }
257132bdbfeSandi    }
258f3f0262cSandi    //just to be sure
259883179a4SAndreas Gohr    auth_logoff(true);
260132bdbfeSandi    return false;
261f3f0262cSandi}
262132bdbfeSandi
263132bdbfeSandi/**
264f13fa892SAndreas Gohr * Checks if a given authentication token was stored in the session
265f13fa892SAndreas Gohr *
266f13fa892SAndreas Gohr * Will setup authentication data using data from the session if the
267f13fa892SAndreas Gohr * token is correct. Will exit with a 401 Status if not.
268f13fa892SAndreas Gohr *
269f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
270f13fa892SAndreas Gohr * @param  string $token The authentication token
271f13fa892SAndreas Gohr * @return boolean true (or will exit on failure)
272f13fa892SAndreas Gohr */
273f13fa892SAndreas Gohrfunction auth_validateToken($token) {
274f13fa892SAndreas Gohr    if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']) {
275f13fa892SAndreas Gohr        // bad token
2769d2e1be6SAndreas Gohr        http_status(401);
277f13fa892SAndreas Gohr        print 'Invalid auth token - maybe the session timed out';
278f13fa892SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
279f13fa892SAndreas Gohr        exit;
280f13fa892SAndreas Gohr    }
281f13fa892SAndreas Gohr    // still here? trust the session data
282f13fa892SAndreas Gohr    global $USERINFO;
283f13fa892SAndreas Gohr    $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
284f13fa892SAndreas Gohr    $USERINFO               = $_SESSION[DOKU_COOKIE]['auth']['info'];
285f13fa892SAndreas Gohr    return true;
286f13fa892SAndreas Gohr}
287f13fa892SAndreas Gohr
288f13fa892SAndreas Gohr/**
289f13fa892SAndreas Gohr * Create an auth token and store it in the session
290f13fa892SAndreas Gohr *
291f13fa892SAndreas Gohr * NOTE: this is completely unrelated to the getSecurityToken() function
292f13fa892SAndreas Gohr *
293f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
294f13fa892SAndreas Gohr * @return string The auth token
295f13fa892SAndreas Gohr */
296f13fa892SAndreas Gohrfunction auth_createToken() {
297483b6238SMichael Hamann    $token = md5(auth_randombytes(16));
29809c2d803SAndreas Gohr    @session_start(); // reopen the session if needed
299f13fa892SAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
30009c2d803SAndreas Gohr    session_write_close();
301f13fa892SAndreas Gohr    return $token;
302f13fa892SAndreas Gohr}
303f13fa892SAndreas Gohr
304f13fa892SAndreas Gohr/**
305136ce040Sandi * Builds a pseudo UID from browser and IP data
306132bdbfeSandi *
307132bdbfeSandi * This is neither unique nor unfakable - still it adds some
308136ce040Sandi * security. Using the first part of the IP makes sure
30980b4f376SAndreas Gohr * proxy farms like AOLs are still okay.
31015fae107Sandi *
31115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
31215fae107Sandi *
31315fae107Sandi * @return  string  a MD5 sum of various browser headers
314132bdbfeSandi */
315132bdbfeSandifunction auth_browseruid() {
3162f9daf16SAndreas Gohr    $ip  = clientIP(true);
317132bdbfeSandi    $uid = '';
318132bdbfeSandi    $uid .= $_SERVER['HTTP_USER_AGENT'];
319132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
320132bdbfeSandi    $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
3212f9daf16SAndreas Gohr    $uid .= substr($ip, 0, strpos($ip, '.'));
32280b4f376SAndreas Gohr    $uid = strtolower($uid);
323132bdbfeSandi    return md5($uid);
324132bdbfeSandi}
325132bdbfeSandi
326132bdbfeSandi/**
327132bdbfeSandi * Creates a random key to encrypt the password in cookies
32815fae107Sandi *
32915fae107Sandi * This function tries to read the password for encrypting
33098407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
33115fae107Sandi * if no such file is found a random key is created and
33215fae107Sandi * and stored in this file.
33315fae107Sandi *
33415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
33532ed2b36SAndreas Gohr * @param   bool $addsession if true, the sessionid is added to the salt
336*30d544a4SMichael Hamann * @param   bool $secure     if security is more important than keeping the old value
33715fae107Sandi * @return  string
338132bdbfeSandi */
339*30d544a4SMichael Hamannfunction auth_cookiesalt($addsession = false, $secure = false) {
340132bdbfeSandi    global $conf;
34198407a7aSandi    $file = $conf['metadir'].'/_htcookiesalt';
342*30d544a4SMichael Hamann    if ($secure || !file_exists($file)) {
343*30d544a4SMichael Hamann        $file = $conf['metadir'].'/_htcookiesalt2';
344*30d544a4SMichael Hamann    }
345132bdbfeSandi    $salt = io_readFile($file);
346132bdbfeSandi    if(empty($salt)) {
347*30d544a4SMichael Hamann        $salt = bin2hex(auth_randombytes(64));
348132bdbfeSandi        io_saveFile($file, $salt);
349132bdbfeSandi    }
35032ed2b36SAndreas Gohr    if($addsession) {
35132ed2b36SAndreas Gohr        $salt .= session_id();
35232ed2b36SAndreas Gohr    }
353132bdbfeSandi    return $salt;
354f3f0262cSandi}
355f3f0262cSandi
356f3f0262cSandi/**
357483b6238SMichael Hamann * Return truly (pseudo) random bytes if available, otherwise fall back to mt_rand
358483b6238SMichael Hamann *
359483b6238SMichael Hamann * @author Mark Seecof
360483b6238SMichael Hamann * @author Michael Hamann <michael@content-space.de>
361483b6238SMichael Hamann * @link   http://www.php.net/manual/de/function.mt-rand.php#83655
362483b6238SMichael Hamann * @param int $length number of bytes to get
363483b6238SMichael Hamann * @throws Exception when no usable random generator is found
364483b6238SMichael Hamann * @return string binary random strings
365483b6238SMichael Hamann */
366483b6238SMichael Hamannfunction auth_randombytes($length) {
367483b6238SMichael Hamann    $strong = false;
368483b6238SMichael Hamann    $rbytes = false;
369483b6238SMichael Hamann
370483b6238SMichael Hamann    if (function_exists('openssl_random_pseudo_bytes')
371483b6238SMichael Hamann        && (version_compare(PHP_VERSION, '5.3.4') >= 0
372483b6238SMichael Hamann            || strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')
373483b6238SMichael Hamann    ) {
374483b6238SMichael Hamann        $rbytes = openssl_random_pseudo_bytes($length, $strong);
375483b6238SMichael Hamann    }
376483b6238SMichael Hamann
377483b6238SMichael Hamann    if (!$strong && function_exists('mcrypt_create_iv')
378483b6238SMichael Hamann        && (version_compare(PHP_VERSION, '5.3.7') >= 0
379483b6238SMichael Hamann            || strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')
380483b6238SMichael Hamann    ) {
381483b6238SMichael Hamann        $rbytes = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
382483b6238SMichael Hamann        if ($rbytes !== false && strlen($rbytes) === $length) {
383483b6238SMichael Hamann            $strong = true;
384483b6238SMichael Hamann        }
385483b6238SMichael Hamann    }
386483b6238SMichael Hamann
387483b6238SMichael Hamann
388483b6238SMichael Hamann    // If no strong randoms available, try OS the specific ways
389483b6238SMichael Hamann    if(!$strong) {
390483b6238SMichael Hamann        // Unix/Linux platform
391483b6238SMichael Hamann        $fp = @fopen('/dev/urandom', 'rb');
392483b6238SMichael Hamann        if($fp !== false) {
393483b6238SMichael Hamann            $rbytes = fread($fp, $length);
394483b6238SMichael Hamann            fclose($fp);
395483b6238SMichael Hamann        }
396483b6238SMichael Hamann
397483b6238SMichael Hamann        // MS-Windows platform
398483b6238SMichael Hamann        if(class_exists('COM')) {
399483b6238SMichael Hamann            // http://msdn.microsoft.com/en-us/library/aa388176(VS.85).aspx
400483b6238SMichael Hamann            try {
401483b6238SMichael Hamann                $CAPI_Util = new COM('CAPICOM.Utilities.1');
402483b6238SMichael Hamann                $rbytes    = $CAPI_Util->GetRandom($length, 0);
403483b6238SMichael Hamann
404483b6238SMichael Hamann                // if we ask for binary data PHP munges it, so we
405483b6238SMichael Hamann                // request base64 return value.
406483b6238SMichael Hamann                if($rbytes) $rbytes = base64_decode($rbytes);
407483b6238SMichael Hamann            } catch(Exception $ex) {
408483b6238SMichael Hamann                // fail
409483b6238SMichael Hamann            }
410483b6238SMichael Hamann        }
411483b6238SMichael Hamann    }
412483b6238SMichael Hamann    if(strlen($rbytes) < $length) $rbytes = false;
413483b6238SMichael Hamann
414483b6238SMichael Hamann    // still no random bytes available - fall back to mt_rand()
415483b6238SMichael Hamann    if($rbytes === false) {
416483b6238SMichael Hamann        $rbytes = '';
417483b6238SMichael Hamann        for ($i = 0; $i < $length; ++$i) {
418483b6238SMichael Hamann            $rbytes .= chr(mt_rand(0, 255));
419483b6238SMichael Hamann        }
420483b6238SMichael Hamann    }
421483b6238SMichael Hamann
422483b6238SMichael Hamann    return $rbytes;
423483b6238SMichael Hamann}
424483b6238SMichael Hamann
425483b6238SMichael Hamann/**
426483b6238SMichael Hamann * Random number generator using the best available source
427483b6238SMichael Hamann *
428483b6238SMichael Hamann * @author Michael Samuel
429483b6238SMichael Hamann * @author Michael Hamann <michael@content-space.de>
430483b6238SMichael Hamann * @param int $min
431483b6238SMichael Hamann * @param int $max
432483b6238SMichael Hamann * @return int
433483b6238SMichael Hamann */
434483b6238SMichael Hamannfunction auth_random($min, $max) {
435483b6238SMichael Hamann    $abs_max = $max - $min;
436483b6238SMichael Hamann
437483b6238SMichael Hamann    $nbits = 0;
438483b6238SMichael Hamann    for ($n = $abs_max; $n > 0; $n >>= 1) {
439483b6238SMichael Hamann        ++$nbits;
440483b6238SMichael Hamann    }
441483b6238SMichael Hamann
442483b6238SMichael Hamann    $mask = (1 << $nbits) - 1;
443483b6238SMichael Hamann    do {
444483b6238SMichael Hamann        $bytes    = auth_randombytes(PHP_INT_SIZE);
445483b6238SMichael Hamann        $integers = unpack('Inum', $bytes);
446483b6238SMichael Hamann        $integer  = $integers["num"] & $mask;
447483b6238SMichael Hamann    } while ($integer > $abs_max);
448483b6238SMichael Hamann
449483b6238SMichael Hamann    return $min + $integer;
450483b6238SMichael Hamann}
451483b6238SMichael Hamann
452483b6238SMichael Hamann/**
453883179a4SAndreas Gohr * Log out the current user
454883179a4SAndreas Gohr *
455f3f0262cSandi * This clears all authentication data and thus log the user
456883179a4SAndreas Gohr * off. It also clears session data.
45715fae107Sandi *
45815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
459883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
460f3f0262cSandi */
461883179a4SAndreas Gohrfunction auth_logoff($keepbc = false) {
462f3f0262cSandi    global $conf;
463f3f0262cSandi    global $USERINFO;
46427058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
4655298a619SAndreas Gohr    global $auth;
46637065e65Sandi
467d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
468e9621d07SAndreas Gohr    @session_start();
469e9621d07SAndreas Gohr
470e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
471e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
472e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
473e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
474e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
475e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
476883179a4SAndreas Gohr    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
477e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
47837065e65Sandi    if(isset($_SERVER['REMOTE_USER']))
479f3f0262cSandi        unset($_SERVER['REMOTE_USER']);
480132bdbfeSandi    $USERINFO = null; //FIXME
481f5c6743cSAndreas Gohr
48273ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
483f5c6743cSAndreas Gohr    if(version_compare(PHP_VERSION, '5.2.0', '>')) {
48473ab87deSGabriel Birke        setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
485f5c6743cSAndreas Gohr    } else {
48673ab87deSGabriel Birke        setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
487f5c6743cSAndreas Gohr    }
4885298a619SAndreas Gohr
489880f62faSAndreas Gohr    if($auth) $auth->logOff();
490f3f0262cSandi}
491f3f0262cSandi
492f3f0262cSandi/**
493f8cc712eSAndreas Gohr * Check if a user is a manager
494f8cc712eSAndreas Gohr *
495f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
496f8cc712eSAndreas Gohr * user.
497f8cc712eSAndreas Gohr *
498f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
499f8cc712eSAndreas Gohr *
500f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
501f8cc712eSAndreas Gohr * @see    auth_isadmin
502ab5d26daSAndreas Gohr * @param  string $user       Username
503ab5d26daSAndreas Gohr * @param  array  $groups     List of groups the user is in
504ab5d26daSAndreas Gohr * @param  bool   $adminonly  when true checks if user is admin
505ab5d26daSAndreas Gohr * @return bool
506f8cc712eSAndreas Gohr */
507f8cc712eSAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false) {
508f8cc712eSAndreas Gohr    global $conf;
509f8cc712eSAndreas Gohr    global $USERINFO;
51027058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
511d752aedeSAndreas Gohr    global $auth;
512f8cc712eSAndreas Gohr
513beca106aSAdrian Lang    if(!$auth) return false;
514c66972f2SAdrian Lang    if(is_null($user)) {
515c66972f2SAdrian Lang        if(!isset($_SERVER['REMOTE_USER'])) {
516c66972f2SAdrian Lang            return false;
517c66972f2SAdrian Lang        } else {
518c66972f2SAdrian Lang            $user = $_SERVER['REMOTE_USER'];
519c66972f2SAdrian Lang        }
520c66972f2SAdrian Lang    }
521d6dc956fSAndreas Gohr    if(is_null($groups)) {
522d6dc956fSAndreas Gohr        $groups = (array) $USERINFO['grps'];
523e259aa79SAndreas Gohr    }
524e259aa79SAndreas Gohr
525d6dc956fSAndreas Gohr    // check superuser match
526d6dc956fSAndreas Gohr    if(auth_isMember($conf['superuser'], $user, $groups)) return true;
527d6dc956fSAndreas Gohr    if($adminonly) return false;
528e259aa79SAndreas Gohr    // check managers
529d6dc956fSAndreas Gohr    if(auth_isMember($conf['manager'], $user, $groups)) return true;
53000ce12daSChris Smith
531f8cc712eSAndreas Gohr    return false;
532f8cc712eSAndreas Gohr}
533f8cc712eSAndreas Gohr
534f8cc712eSAndreas Gohr/**
535f8cc712eSAndreas Gohr * Check if a user is admin
536f8cc712eSAndreas Gohr *
537f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
538f8cc712eSAndreas Gohr *
539f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
540f8cc712eSAndreas Gohr *
541f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
542ab5d26daSAndreas Gohr * @see auth_ismanager()
543ab5d26daSAndreas Gohr * @param  string $user       Username
544ab5d26daSAndreas Gohr * @param  array  $groups     List of groups the user is in
545ab5d26daSAndreas Gohr * @return bool
546f8cc712eSAndreas Gohr */
547f8cc712eSAndreas Gohrfunction auth_isadmin($user = null, $groups = null) {
548f8cc712eSAndreas Gohr    return auth_ismanager($user, $groups, true);
549f8cc712eSAndreas Gohr}
550f8cc712eSAndreas Gohr
551d6dc956fSAndreas Gohr/**
552d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
553d6dc956fSAndreas Gohr * users and groups to determine membership status
554d6dc956fSAndreas Gohr *
555d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
556d6dc956fSAndreas Gohr *
557d6dc956fSAndreas Gohr * @param $memberlist string commaseparated list of allowed users and groups
558d6dc956fSAndreas Gohr * @param $user       string user to match against
559d6dc956fSAndreas Gohr * @param $groups     array  groups the user is member of
5605446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
561d6dc956fSAndreas Gohr */
562d6dc956fSAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups) {
56327058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
564d6dc956fSAndreas Gohr    global $auth;
565d6dc956fSAndreas Gohr    if(!$auth) return false;
566d6dc956fSAndreas Gohr
567d6dc956fSAndreas Gohr    // clean user and groups
5684f56ecbfSAdrian Lang    if(!$auth->isCaseSensitive()) {
569d6dc956fSAndreas Gohr        $user   = utf8_strtolower($user);
570d6dc956fSAndreas Gohr        $groups = array_map('utf8_strtolower', $groups);
571d6dc956fSAndreas Gohr    }
572d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
573d6dc956fSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), $groups);
574d6dc956fSAndreas Gohr
575d6dc956fSAndreas Gohr    // extract the memberlist
576d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
577d6dc956fSAndreas Gohr    $members = array_map('trim', $members);
578d6dc956fSAndreas Gohr    $members = array_unique($members);
579d6dc956fSAndreas Gohr    $members = array_filter($members);
580d6dc956fSAndreas Gohr
581d6dc956fSAndreas Gohr    // compare cleaned values
582d6dc956fSAndreas Gohr    foreach($members as $member) {
5834f56ecbfSAdrian Lang        if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member);
584d6dc956fSAndreas Gohr        if($member[0] == '@') {
585d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
586d6dc956fSAndreas Gohr            if(in_array($member, $groups)) return true;
587d6dc956fSAndreas Gohr        } else {
588d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
589d6dc956fSAndreas Gohr            if($member == $user) return true;
590d6dc956fSAndreas Gohr        }
591d6dc956fSAndreas Gohr    }
592d6dc956fSAndreas Gohr
593d6dc956fSAndreas Gohr    // still here? not a member!
594d6dc956fSAndreas Gohr    return false;
595d6dc956fSAndreas Gohr}
596d6dc956fSAndreas Gohr
597f8cc712eSAndreas Gohr/**
59815fae107Sandi * Convinience function for auth_aclcheck()
59915fae107Sandi *
60015fae107Sandi * This checks the permissions for the current user
60115fae107Sandi *
60215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
60315fae107Sandi *
6041698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
60515fae107Sandi * @return int          permission level
606f3f0262cSandi */
607f3f0262cSandifunction auth_quickaclcheck($id) {
608f3f0262cSandi    global $conf;
609f3f0262cSandi    global $USERINFO;
610f3f0262cSandi    # if no ACL is used always return upload rights
611f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
612f3f0262cSandi    return auth_aclcheck($id, $_SERVER['REMOTE_USER'], $USERINFO['grps']);
613f3f0262cSandi}
614f3f0262cSandi
615f3f0262cSandi/**
616f3f0262cSandi * Returns the maximum rights a user has for
617f3f0262cSandi * the given ID or its namespace
61815fae107Sandi *
61915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
62015fae107Sandi *
6211698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
62215fae107Sandi * @param  string       $user   Username
6233272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
62415fae107Sandi * @return int             permission level
625f3f0262cSandi */
626f3f0262cSandifunction auth_aclcheck($id, $user, $groups) {
627f3f0262cSandi    global $conf;
628f3f0262cSandi    global $AUTH_ACL;
62927058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
630d752aedeSAndreas Gohr    global $auth;
631f3f0262cSandi
63285d03f68SAndreas Gohr    // if no ACL is used always return upload rights
633f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
634beca106aSAdrian Lang    if(!$auth) return AUTH_NONE;
635f3f0262cSandi
636074cf26bSandi    //make sure groups is an array
637074cf26bSandi    if(!is_array($groups)) $groups = array();
638074cf26bSandi
63985d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
640ab5d26daSAndreas Gohr    if(auth_isadmin($user, $groups)) {
641ab5d26daSAndreas Gohr        return AUTH_ADMIN;
642ab5d26daSAndreas Gohr    }
64385d03f68SAndreas Gohr
644eb3ce0d5SKazutaka Miyasaka    if(!$auth->isCaseSensitive()) {
645eb3ce0d5SKazutaka Miyasaka        $user   = utf8_strtolower($user);
646eb3ce0d5SKazutaka Miyasaka        $groups = array_map('utf8_strtolower', $groups);
647eb3ce0d5SKazutaka Miyasaka    }
648d752aedeSAndreas Gohr    $user   = $auth->cleanUser($user);
649d752aedeSAndreas Gohr    $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
65085d03f68SAndreas Gohr    $user   = auth_nameencode($user);
65185d03f68SAndreas Gohr
6526c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
6532cd2db38Sandi    $cnt = count($groups);
6542cd2db38Sandi    for($i = 0; $i < $cnt; $i++) {
6556c2bb100SAndreas Gohr        $groups[$i] = '@'.auth_nameencode($groups[$i]);
65610a76f6fSfrank    }
65710a76f6fSfrank
658f3f0262cSandi    $ns   = getNS($id);
659f3f0262cSandi    $perm = -1;
660f3f0262cSandi
66134aeb4afSAndreas Gohr    if($user || count($groups)) {
662f3f0262cSandi        //add ALL group
663f3f0262cSandi        $groups[] = '@ALL';
664f3f0262cSandi        //add User
66534aeb4afSAndreas Gohr        if($user) $groups[] = $user;
666f3f0262cSandi    } else {
66748d7b7a6SDominik Eckelmann        $groups[] = '@ALL';
668f3f0262cSandi    }
669f3f0262cSandi
670f3f0262cSandi    //check exact match first
671eb3ce0d5SKazutaka Miyasaka    $matches = preg_grep('/^'.preg_quote($id, '/').'\s+(\S+)\s+/u', $AUTH_ACL);
672f3f0262cSandi    if(count($matches)) {
673f3f0262cSandi        foreach($matches as $match) {
674f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
675f3f0262cSandi            $acl   = preg_split('/\s+/', $match);
676eb3ce0d5SKazutaka Miyasaka            if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
677eb3ce0d5SKazutaka Miyasaka                $acl[1] = utf8_strtolower($acl[1]);
678eb3ce0d5SKazutaka Miyasaka            }
67948d7b7a6SDominik Eckelmann            if(!in_array($acl[1], $groups)) {
68048d7b7a6SDominik Eckelmann                continue;
68148d7b7a6SDominik Eckelmann            }
6828ef6b7caSandi            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
683f3f0262cSandi            if($acl[2] > $perm) {
684f3f0262cSandi                $perm = $acl[2];
685f3f0262cSandi            }
686f3f0262cSandi        }
687f3f0262cSandi        if($perm > -1) {
688f3f0262cSandi            //we had a match - return it
689def492a2SGuillaume Turri            return (int) $perm;
690f3f0262cSandi        }
691f3f0262cSandi    }
692f3f0262cSandi
693f3f0262cSandi    //still here? do the namespace checks
694f3f0262cSandi    if($ns) {
6953e304b55SMichael Hamann        $path = $ns.':*';
696f3f0262cSandi    } else {
6973e304b55SMichael Hamann        $path = '*'; //root document
698f3f0262cSandi    }
699f3f0262cSandi
700f3f0262cSandi    do {
701eb3ce0d5SKazutaka Miyasaka        $matches = preg_grep('/^'.preg_quote($path, '/').'\s+(\S+)\s+/u', $AUTH_ACL);
702f3f0262cSandi        if(count($matches)) {
703f3f0262cSandi            foreach($matches as $match) {
704f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
705f3f0262cSandi                $acl   = preg_split('/\s+/', $match);
706eb3ce0d5SKazutaka Miyasaka                if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
707eb3ce0d5SKazutaka Miyasaka                    $acl[1] = utf8_strtolower($acl[1]);
708eb3ce0d5SKazutaka Miyasaka                }
70948d7b7a6SDominik Eckelmann                if(!in_array($acl[1], $groups)) {
71048d7b7a6SDominik Eckelmann                    continue;
71148d7b7a6SDominik Eckelmann                }
7128ef6b7caSandi                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
713f3f0262cSandi                if($acl[2] > $perm) {
714f3f0262cSandi                    $perm = $acl[2];
715f3f0262cSandi                }
716f3f0262cSandi            }
717f3f0262cSandi            //we had a match - return it
71848d7b7a6SDominik Eckelmann            if($perm != -1) {
719def492a2SGuillaume Turri                return (int) $perm;
720f3f0262cSandi            }
72148d7b7a6SDominik Eckelmann        }
722f3f0262cSandi        //get next higher namespace
723f3f0262cSandi        $ns = getNS($ns);
724f3f0262cSandi
7253e304b55SMichael Hamann        if($path != '*') {
7263e304b55SMichael Hamann            $path = $ns.':*';
7273e304b55SMichael Hamann            if($path == ':*') $path = '*';
728f3f0262cSandi        } else {
729f3f0262cSandi            //we did this already
730f3f0262cSandi            //looks like there is something wrong with the ACL
731f3f0262cSandi            //break here
732d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
733d5ce66f6SAndreas Gohr            return AUTH_NONE;
734f3f0262cSandi        }
735f3f0262cSandi    } while(1); //this should never loop endless
736ab5d26daSAndreas Gohr    return AUTH_NONE;
737f3f0262cSandi}
738f3f0262cSandi
739f3f0262cSandi/**
7406c2bb100SAndreas Gohr * Encode ASCII special chars
7416c2bb100SAndreas Gohr *
7426c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
7436c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
7446c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
7456c2bb100SAndreas Gohr * urlencoding!).
7466c2bb100SAndreas Gohr *
7476c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
7486c2bb100SAndreas Gohr *
7496c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
7506c2bb100SAndreas Gohr * @see rawurldecode()
7516c2bb100SAndreas Gohr */
752e838fc2eSAndreas Gohrfunction auth_nameencode($name, $skip_group = false) {
753a424cd8eSchris    global $cache_authname;
754a424cd8eSchris    $cache =& $cache_authname;
75531784267SAndreas Gohr    $name  = (string) $name;
756a424cd8eSchris
75780601d26SAndreas Gohr    // never encode wildcard FS#1955
75880601d26SAndreas Gohr    if($name == '%USER%') return $name;
759b78bf706Sromain    if($name == '%GROUP%') return $name;
76080601d26SAndreas Gohr
761a424cd8eSchris    if(!isset($cache[$name][$skip_group])) {
762e838fc2eSAndreas Gohr        if($skip_group && $name{0} == '@') {
763ab5d26daSAndreas Gohr            $cache[$name][$skip_group] = '@'.preg_replace(
764ab5d26daSAndreas Gohr                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
765ab5d26daSAndreas Gohr                "'%'.dechex(ord(substr('\\1',-1)))", substr($name, 1)
766ab5d26daSAndreas Gohr            );
767e838fc2eSAndreas Gohr        } else {
768ab5d26daSAndreas Gohr            $cache[$name][$skip_group] = preg_replace(
769ab5d26daSAndreas Gohr                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
770ab5d26daSAndreas Gohr                "'%'.dechex(ord(substr('\\1',-1)))", $name
771ab5d26daSAndreas Gohr            );
772e838fc2eSAndreas Gohr        }
7736c2bb100SAndreas Gohr    }
7746c2bb100SAndreas Gohr
775a424cd8eSchris    return $cache[$name][$skip_group];
776a424cd8eSchris}
777a424cd8eSchris
7786c2bb100SAndreas Gohr/**
779f3f0262cSandi * Create a pronouncable password
780f3f0262cSandi *
7818a285f7fSAndreas Gohr * The $foruser variable might be used by plugins to run additional password
7828a285f7fSAndreas Gohr * policy checks, but is not used by the default implementation
7838a285f7fSAndreas Gohr *
78415fae107Sandi * @author   Andreas Gohr <andi@splitbrain.org>
78515fae107Sandi * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
7868a285f7fSAndreas Gohr * @triggers AUTH_PASSWORD_GENERATE
78715fae107Sandi *
7888a285f7fSAndreas Gohr * @param  string $foruser username for which the password is generated
78915fae107Sandi * @return string  pronouncable password
790f3f0262cSandi */
7918a285f7fSAndreas Gohrfunction auth_pwgen($foruser = '') {
7928a285f7fSAndreas Gohr    $data = array(
793d628dcf3SAndreas Gohr        'password' => '',
794d628dcf3SAndreas Gohr        'foruser'  => $foruser
7958a285f7fSAndreas Gohr    );
7968a285f7fSAndreas Gohr
7978a285f7fSAndreas Gohr    $evt = new Doku_Event('AUTH_PASSWORD_GENERATE', $data);
7988a285f7fSAndreas Gohr    if($evt->advise_before(true)) {
799f3f0262cSandi        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
800f3f0262cSandi        $v = 'aeiou'; //vowels
801f3f0262cSandi        $a = $c.$v; //both
802987c8d26SAndreas Gohr        $s = '!$%&?+*~#-_:.;,'; // specials
803f3f0262cSandi
804987c8d26SAndreas Gohr        //use thre syllables...
805987c8d26SAndreas Gohr        for($i = 0; $i < 3; $i++) {
806483b6238SMichael Hamann            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
807483b6238SMichael Hamann            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
808483b6238SMichael Hamann            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
809f3f0262cSandi        }
810987c8d26SAndreas Gohr        //... and add a nice number and special
811483b6238SMichael Hamann        $data['password'] .= auth_random(10, 99).$s[auth_random(0, strlen($s) - 1)];
8128a285f7fSAndreas Gohr    }
8138a285f7fSAndreas Gohr    $evt->advise_after();
814f3f0262cSandi
8158a285f7fSAndreas Gohr    return $data['password'];
816f3f0262cSandi}
817f3f0262cSandi
818f3f0262cSandi/**
819f3f0262cSandi * Sends a password to the given user
820f3f0262cSandi *
82115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
822ab5d26daSAndreas Gohr * @param string $user Login name of the user
823ab5d26daSAndreas Gohr * @param string $password The new password in clear text
82415fae107Sandi * @return bool  true on success
825f3f0262cSandi */
826f3f0262cSandifunction auth_sendPassword($user, $password) {
827f3f0262cSandi    global $lang;
82827058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
829cd52f92dSchris    global $auth;
830beca106aSAdrian Lang    if(!$auth) return false;
831cd52f92dSchris
832d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
833cd52f92dSchris    $userinfo = $auth->getUserData($user);
834f3f0262cSandi
83587ddda95Sandi    if(!$userinfo['mail']) return false;
836f3f0262cSandi
837f3f0262cSandi    $text = rawLocale('password');
838d7169d19SAndreas Gohr    $trep = array(
839d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
840d7169d19SAndreas Gohr        'LOGIN'    => $user,
841d7169d19SAndreas Gohr        'PASSWORD' => $password
842d7169d19SAndreas Gohr    );
843f3f0262cSandi
844d7169d19SAndreas Gohr    $mail = new Mailer();
845d7169d19SAndreas Gohr    $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
846d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
847d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
848d7169d19SAndreas Gohr    return $mail->send();
849f3f0262cSandi}
850f3f0262cSandi
851f3f0262cSandi/**
85215fae107Sandi * Register a new user
853f3f0262cSandi *
85415fae107Sandi * This registers a new user - Data is read directly from $_POST
85515fae107Sandi *
85615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
85715fae107Sandi * @return bool  true on success, false on any error
858f3f0262cSandi */
859f3f0262cSandifunction register() {
860f3f0262cSandi    global $lang;
861eb5d07e4Sjan    global $conf;
86227058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
863cd52f92dSchris    global $auth;
86464273335SAndreas Gohr    global $INPUT;
865f3f0262cSandi
86664273335SAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
8673a48618aSAnika Henke    if(!actionOK('register')) return false;
868640145a5Sandi
86964273335SAndreas Gohr    // gather input
87064273335SAndreas Gohr    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
87164273335SAndreas Gohr    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
87264273335SAndreas Gohr    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
87364273335SAndreas Gohr    $pass     = $INPUT->post->str('pass');
87464273335SAndreas Gohr    $passchk  = $INPUT->post->str('passchk');
875d752aedeSAndreas Gohr
87664273335SAndreas Gohr    if(empty($login) || empty($fullname) || empty($email)) {
877f3f0262cSandi        msg($lang['regmissing'], -1);
878f3f0262cSandi        return false;
879f3f0262cSandi    }
880f3f0262cSandi
881cab2716aSmatthias.grimm    if($conf['autopasswd']) {
8828a285f7fSAndreas Gohr        $pass = auth_pwgen($login); // automatically generate password
88364273335SAndreas Gohr    } elseif(empty($pass) || empty($passchk)) {
884bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
885cab2716aSmatthias.grimm        return false;
88664273335SAndreas Gohr    } elseif($pass != $passchk) {
887bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
888cab2716aSmatthias.grimm        return false;
889cab2716aSmatthias.grimm    }
890cab2716aSmatthias.grimm
891f3f0262cSandi    //check mail
89264273335SAndreas Gohr    if(!mail_isvalid($email)) {
893f3f0262cSandi        msg($lang['regbadmail'], -1);
894f3f0262cSandi        return false;
895f3f0262cSandi    }
896f3f0262cSandi
897f3f0262cSandi    //okay try to create the user
89864273335SAndreas Gohr    if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) {
899f3f0262cSandi        msg($lang['reguexists'], -1);
900f3f0262cSandi        return false;
901f3f0262cSandi    }
902f3f0262cSandi
903790b7720SAndreas Gohr    // send notification about the new user
904790b7720SAndreas Gohr    $subscription = new Subscription();
905790b7720SAndreas Gohr    $subscription->send_register($login, $fullname, $email);
90602a498e7Schris
907790b7720SAndreas Gohr    // are we done?
908cab2716aSmatthias.grimm    if(!$conf['autopasswd']) {
909cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
910cab2716aSmatthias.grimm        return true;
911cab2716aSmatthias.grimm    }
912cab2716aSmatthias.grimm
913790b7720SAndreas Gohr    // autogenerated password? then send password to user
91464273335SAndreas Gohr    if(auth_sendPassword($login, $pass)) {
915f3f0262cSandi        msg($lang['regsuccess'], 1);
916f3f0262cSandi        return true;
917f3f0262cSandi    } else {
918f3f0262cSandi        msg($lang['regmailfail'], -1);
919f3f0262cSandi        return false;
920f3f0262cSandi    }
921f3f0262cSandi}
922f3f0262cSandi
92310a76f6fSfrank/**
9248b06d178Schris * Update user profile
9258b06d178Schris *
9268b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
9278b06d178Schris */
9288b06d178Schrisfunction updateprofile() {
9298b06d178Schris    global $conf;
9308b06d178Schris    global $lang;
93127058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
932cd52f92dSchris    global $auth;
933bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
934bcc94b2cSAndreas Gohr    global $INPUT;
9358b06d178Schris
936bcc94b2cSAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
9371b2a85e8SAndreas Gohr    if(!checkSecurityToken()) return false;
9388b06d178Schris
9393a48618aSAnika Henke    if(!actionOK('profile')) {
9408b06d178Schris        msg($lang['profna'], -1);
9418b06d178Schris        return false;
9428b06d178Schris    }
9438b06d178Schris
944bcc94b2cSAndreas Gohr    $changes         = array();
945bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
946bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
947bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
948bcc94b2cSAndreas Gohr
949bcc94b2cSAndreas Gohr    // check misspelled passwords
950bcc94b2cSAndreas Gohr    if($changes['pass'] != $INPUT->post->str('passchk')) {
951bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
9528b06d178Schris        return false;
9538b06d178Schris    }
9548b06d178Schris
9558b06d178Schris    // clean fullname and email
956bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
957bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
9588b06d178Schris
959bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
960bcc94b2cSAndreas Gohr    if((empty($changes['name']) && $auth->canDo('modName')) ||
961bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
962ab5d26daSAndreas Gohr    ) {
9638b06d178Schris        msg($lang['profnoempty'], -1);
9648b06d178Schris        return false;
9658b06d178Schris    }
966bcc94b2cSAndreas Gohr    if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
9678b06d178Schris        msg($lang['regbadmail'], -1);
9688b06d178Schris        return false;
9698b06d178Schris    }
9708b06d178Schris
971bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
9724c21b7eeSAndreas Gohr
973bcc94b2cSAndreas Gohr    // check for unavailable capabilities
974bcc94b2cSAndreas Gohr    if(!$auth->canDo('modName')) unset($changes['name']);
975bcc94b2cSAndreas Gohr    if(!$auth->canDo('modMail')) unset($changes['mail']);
976bcc94b2cSAndreas Gohr    if(!$auth->canDo('modPass')) unset($changes['pass']);
977bcc94b2cSAndreas Gohr
978bcc94b2cSAndreas Gohr    // anything to do?
9798b06d178Schris    if(!count($changes)) {
9808b06d178Schris        msg($lang['profnochange'], -1);
9818b06d178Schris        return false;
9828b06d178Schris    }
9838b06d178Schris
9848b06d178Schris    if($conf['profileconfirm']) {
985bcc94b2cSAndreas Gohr        if(!$auth->checkPass($_SERVER['REMOTE_USER'], $INPUT->post->str('oldpass'))) {
9868b06d178Schris            msg($lang['badlogin'], -1);
9878b06d178Schris            return false;
9888b06d178Schris        }
9898b06d178Schris    }
9908b06d178Schris
991a0b5b007SChris Smith    if($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
992a0b5b007SChris Smith        // update cookie and session with the changed data
99332ed2b36SAndreas Gohr        if($changes['pass']) {
994ab5d26daSAndreas Gohr            list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
995*30d544a4SMichael Hamann            $pass = PMA_blowfish_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
996a0b5b007SChris Smith            auth_setCookie($_SERVER['REMOTE_USER'], $pass, (bool) $sticky);
99732ed2b36SAndreas Gohr        }
99825b2a98cSMichael Klier        return true;
999a0b5b007SChris Smith    }
1000ab5d26daSAndreas Gohr
1001ab5d26daSAndreas Gohr    return false;
10028b06d178Schris}
10038b06d178Schris
10048b06d178Schris/**
10058b06d178Schris * Send a  new password
10068b06d178Schris *
10071d5856cfSAndreas Gohr * This function handles both phases of the password reset:
10081d5856cfSAndreas Gohr *
10091d5856cfSAndreas Gohr *   - handling the first request of password reset
10101d5856cfSAndreas Gohr *   - validating the password reset auth token
10111d5856cfSAndreas Gohr *
10128b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
10138b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
10141d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10158b06d178Schris *
10168b06d178Schris * @return bool true on success, false on any error
10178b06d178Schris */
10188b06d178Schrisfunction act_resendpwd() {
10198b06d178Schris    global $lang;
10208b06d178Schris    global $conf;
102127058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
1022cd52f92dSchris    global $auth;
1023bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1024bcc94b2cSAndreas Gohr    global $INPUT;
10258b06d178Schris
10263a48618aSAnika Henke    if(!actionOK('resendpwd')) {
10278b06d178Schris        msg($lang['resendna'], -1);
10288b06d178Schris        return false;
10298b06d178Schris    }
10308b06d178Schris
1031bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
10328b06d178Schris
10331d5856cfSAndreas Gohr    if($token) {
1034cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
10351d5856cfSAndreas Gohr
10361d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
10371d5856cfSAndreas Gohr        if(!@file_exists($tfile)) {
10381d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1039bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
10401d5856cfSAndreas Gohr            return false;
10411d5856cfSAndreas Gohr        }
10428a9735e3SAndreas Gohr        // token is only valid for 3 days
10438a9735e3SAndreas Gohr        if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
10448a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1045bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
10461d5856cfSAndreas Gohr            @unlink($tfile);
10478a9735e3SAndreas Gohr            return false;
10488a9735e3SAndreas Gohr        }
10498a9735e3SAndreas Gohr
10508b06d178Schris        $user     = io_readfile($tfile);
1051cd52f92dSchris        $userinfo = $auth->getUserData($user);
10528b06d178Schris        if(!$userinfo['mail']) {
10538b06d178Schris            msg($lang['resendpwdnouser'], -1);
10548b06d178Schris            return false;
10558b06d178Schris        }
10568b06d178Schris
1057cc204bbdSAndreas Gohr        if(!$conf['autopasswd']) { // we let the user choose a password
1058bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
1059bcc94b2cSAndreas Gohr
1060cc204bbdSAndreas Gohr            // password given correctly?
1061bcc94b2cSAndreas Gohr            if(!$pass) return false;
1062bcc94b2cSAndreas Gohr            if($pass != $INPUT->str('passchk')) {
1063451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
1064cc204bbdSAndreas Gohr                return false;
1065cc204bbdSAndreas Gohr            }
1066cc204bbdSAndreas Gohr
1067bcc94b2cSAndreas Gohr            // change it
1068cc204bbdSAndreas Gohr            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1069cc204bbdSAndreas Gohr                msg('error modifying user data', -1);
1070cc204bbdSAndreas Gohr                return false;
1071cc204bbdSAndreas Gohr            }
1072cc204bbdSAndreas Gohr
1073cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
1074cc204bbdSAndreas Gohr
10758a285f7fSAndreas Gohr            $pass = auth_pwgen($user);
10767d3c8d42SGabriel Birke            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
10778b06d178Schris                msg('error modifying user data', -1);
10788b06d178Schris                return false;
10798b06d178Schris            }
10808b06d178Schris
10818b06d178Schris            if(auth_sendPassword($user, $pass)) {
10828b06d178Schris                msg($lang['resendpwdsuccess'], 1);
10838b06d178Schris            } else {
10848b06d178Schris                msg($lang['regmailfail'], -1);
10858b06d178Schris            }
1086cc204bbdSAndreas Gohr        }
1087cc204bbdSAndreas Gohr
1088cc204bbdSAndreas Gohr        @unlink($tfile);
10898b06d178Schris        return true;
10901d5856cfSAndreas Gohr
10911d5856cfSAndreas Gohr    } else {
10921d5856cfSAndreas Gohr        // we're in request phase
10931d5856cfSAndreas Gohr
1094bcc94b2cSAndreas Gohr        if(!$INPUT->post->bool('save')) return false;
10951d5856cfSAndreas Gohr
1096bcc94b2cSAndreas Gohr        if(!$INPUT->post->str('login')) {
10971d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
10981d5856cfSAndreas Gohr            return false;
10991d5856cfSAndreas Gohr        } else {
1100bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
11011d5856cfSAndreas Gohr        }
11021d5856cfSAndreas Gohr
11031d5856cfSAndreas Gohr        $userinfo = $auth->getUserData($user);
11041d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
11051d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
11061d5856cfSAndreas Gohr            return false;
11071d5856cfSAndreas Gohr        }
11081d5856cfSAndreas Gohr
11091d5856cfSAndreas Gohr        // generate auth token
1110483b6238SMichael Hamann        $token = md5(auth_randombytes(16)); // random secret
11111d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
11121d5856cfSAndreas Gohr        $url   = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
11131d5856cfSAndreas Gohr
11141d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
11151d5856cfSAndreas Gohr
11161d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
1117d7169d19SAndreas Gohr        $trep = array(
1118d7169d19SAndreas Gohr            'FULLNAME' => $userinfo['name'],
1119d7169d19SAndreas Gohr            'LOGIN'    => $user,
1120d7169d19SAndreas Gohr            'CONFIRM'  => $url
1121d7169d19SAndreas Gohr        );
11221d5856cfSAndreas Gohr
1123d7169d19SAndreas Gohr        $mail = new Mailer();
1124d7169d19SAndreas Gohr        $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1125d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
1126d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
1127d7169d19SAndreas Gohr        if($mail->send()) {
11281d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
11291d5856cfSAndreas Gohr        } else {
11301d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
11311d5856cfSAndreas Gohr        }
11321d5856cfSAndreas Gohr        return true;
11331d5856cfSAndreas Gohr    }
1134ab5d26daSAndreas Gohr    // never reached
11358b06d178Schris}
11368b06d178Schris
11378b06d178Schris/**
1138b0855b11Sandi * Encrypts a password using the given method and salt
1139b0855b11Sandi *
1140b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1141b0855b11Sandi * is chosen.
1142b0855b11Sandi *
1143b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
1144ab5d26daSAndreas Gohr * @param string $clear The clear text password
1145ab5d26daSAndreas Gohr * @param string $method The hashing method
1146ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1147b0855b11Sandi * @return  string  The crypted password
1148b0855b11Sandi */
1149577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null) {
1150b0855b11Sandi    global $conf;
1151b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
115210a76f6fSfrank
11533a0a2d05SAndreas Gohr    $pass = new PassHash();
11543a0a2d05SAndreas Gohr    $call = 'hash_'.$method;
1155b0855b11Sandi
11563a0a2d05SAndreas Gohr    if(!method_exists($pass, $call)) {
1157b0855b11Sandi        msg("Unsupported crypt method $method", -1);
11583a0a2d05SAndreas Gohr        return false;
1159b0855b11Sandi    }
11603a0a2d05SAndreas Gohr
11613a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1162b0855b11Sandi}
1163b0855b11Sandi
1164b0855b11Sandi/**
1165b0855b11Sandi * Verifies a cleartext password against a crypted hash
1166b0855b11Sandi *
1167b0855b11Sandi * @author Andreas Gohr <andi@splitbrain.org>
1168ab5d26daSAndreas Gohr * @param  string $clear The clear text password
1169ab5d26daSAndreas Gohr * @param  string $crypt The hash to compare with
1170ab5d26daSAndreas Gohr * @return bool true if both match
1171b0855b11Sandi */
1172b0855b11Sandifunction auth_verifyPassword($clear, $crypt) {
11733a0a2d05SAndreas Gohr    $pass = new PassHash();
11743a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1175b0855b11Sandi}
1176340756e4Sandi
1177a0b5b007SChris Smith/**
1178a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1179a0b5b007SChris Smith *
1180a0b5b007SChris Smith * @param string  $user       username
1181a0b5b007SChris Smith * @param string  $pass       encrypted password
1182a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1183ab5d26daSAndreas Gohr * @return bool
1184a0b5b007SChris Smith */
1185a0b5b007SChris Smithfunction auth_setCookie($user, $pass, $sticky) {
1186a0b5b007SChris Smith    global $conf;
118727058a05SMichael Hamann    /* @var DokuWiki_Auth_Plugin $auth */
1188a0b5b007SChris Smith    global $auth;
118979d00841SOliver Geisen    global $USERINFO;
1190a0b5b007SChris Smith
1191beca106aSAdrian Lang    if(!$auth) return false;
1192a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1193a0b5b007SChris Smith
1194a0b5b007SChris Smith    // set cookie
1195645c0a36SAndreas Gohr    $cookie    = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
119673ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1197c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1198a0b5b007SChris Smith    if(version_compare(PHP_VERSION, '5.2.0', '>')) {
119973ab87deSGabriel Birke        setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
1200a0b5b007SChris Smith    } else {
120173ab87deSGabriel Birke        setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
1202a0b5b007SChris Smith    }
1203a0b5b007SChris Smith    // set session
1204a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1205234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1206a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1207a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1208a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1209ab5d26daSAndreas Gohr
1210ab5d26daSAndreas Gohr    return true;
1211a0b5b007SChris Smith}
1212a0b5b007SChris Smith
1213645c0a36SAndreas Gohr/**
1214645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1215645c0a36SAndreas Gohr *
1216645c0a36SAndreas Gohr * @returns array
1217645c0a36SAndreas Gohr */
1218645c0a36SAndreas Gohrfunction auth_getCookie() {
1219c66972f2SAdrian Lang    if(!isset($_COOKIE[DOKU_COOKIE])) {
1220c66972f2SAdrian Lang        return array(null, null, null);
1221c66972f2SAdrian Lang    }
1222645c0a36SAndreas Gohr    list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
1223645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1224645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1225645c0a36SAndreas Gohr    $user   = base64_decode($user);
1226645c0a36SAndreas Gohr    return array($user, $sticky, $pass);
1227645c0a36SAndreas Gohr}
1228645c0a36SAndreas Gohr
1229e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1230