xref: /dokuwiki/inc/auth.php (revision 5398a7b652eabdd0a20f154b97b60f89cad72f8c)
1<?php
2/**
3 * Authentication library
4 *
5 * Including this file will automatically try to login
6 * a user by calling auth_login()
7 *
8 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
9 * @author     Andreas Gohr <andi@splitbrain.org>
10 */
11
12if(!defined('DOKU_INC')) die('meh.');
13
14// some ACL level defines
15define('AUTH_NONE', 0);
16define('AUTH_READ', 1);
17define('AUTH_EDIT', 2);
18define('AUTH_CREATE', 4);
19define('AUTH_UPLOAD', 8);
20define('AUTH_DELETE', 16);
21define('AUTH_ADMIN', 255);
22
23/**
24 * Initialize the auth system.
25 *
26 * This function is automatically called at the end of init.php
27 *
28 * This used to be the main() of the auth.php
29 *
30 * @todo backend loading maybe should be handled by the class autoloader
31 * @todo maybe split into multiple functions at the XXX marked positions
32 * @triggers AUTH_LOGIN_CHECK
33 * @return bool
34 */
35function auth_setup() {
36    global $conf;
37    /* @var DokuWiki_Auth_Plugin $auth */
38    global $auth;
39    /* @var Input $INPUT */
40    global $INPUT;
41    global $AUTH_ACL;
42    global $lang;
43    global $config_cascade;
44    global $plugin_controller;
45    $AUTH_ACL = array();
46
47    if(!$conf['useacl']) return false;
48
49    // try to load auth backend from plugins
50    foreach ($plugin_controller->getList('auth') as $plugin) {
51    	if ($conf['authtype'] === $plugin) {
52    		$auth = $plugin_controller->load('auth', $plugin);
53    		break;
54    	}
55    }
56
57	if(!$auth){
58        msg($lang['authtempfail'], -1);
59        return false;
60    }
61
62	if ($auth && $auth->success == false) {
63		// degrade to unauthenticated user
64	    unset($auth);
65	    auth_logoff();
66	    msg($lang['authtempfail'], -1);
67	}
68
69    // do the login either by cookie or provided credentials XXX
70    $INPUT->set('http_credentials', false);
71    if(!$conf['rememberme']) $INPUT->set('r', false);
72
73    // handle renamed HTTP_AUTHORIZATION variable (can happen when a fix like
74    // the one presented at
75    // http://www.besthostratings.com/articles/http-auth-php-cgi.html is used
76    // for enabling HTTP authentication with CGI/SuExec)
77    if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
78        $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
79    // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
80    if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
81        list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
82            explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
83    }
84
85    // if no credentials were given try to use HTTP auth (for SSO)
86    if(!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])) {
87        $INPUT->set('u', $_SERVER['PHP_AUTH_USER']);
88        $INPUT->set('p', $_SERVER['PHP_AUTH_PW']);
89        $INPUT->set('http_credentials', true);
90    }
91
92    // apply cleaning
93    if (true === $auth->success) {
94    	$_REQUEST['u'] = $auth->cleanUser($_REQUEST['u']);
95    }
96
97    if($INPUT->str('authtok')) {
98        // when an authentication token is given, trust the session
99        auth_validateToken($INPUT->str('authtok'));
100    } elseif(!is_null($auth) && $auth->canDo('external')) {
101        // external trust mechanism in place
102        $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
103    } else {
104        $evdata = array(
105            'user'     => $INPUT->str('u'),
106            'password' => $INPUT->str('p'),
107            'sticky'   => $INPUT->bool('r'),
108            'silent'   => $INPUT->bool('http_credentials')
109        );
110        trigger_event('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
111    }
112
113    //load ACL into a global array XXX
114    $AUTH_ACL = auth_loadACL();
115
116    return true;
117}
118
119/**
120 * Loads the ACL setup and handle user wildcards
121 *
122 * @author Andreas Gohr <andi@splitbrain.org>
123 * @return array
124 */
125function auth_loadACL() {
126    global $config_cascade;
127    global $USERINFO;
128
129    if(!is_readable($config_cascade['acl']['default'])) return array();
130
131    $acl = file($config_cascade['acl']['default']);
132
133    //support user wildcard
134    $out = array();
135    foreach($acl as $line) {
136        $line = trim($line);
137        if($line{0} == '#') continue;
138        list($id,$rest) = preg_split('/\s+/',$line,2);
139
140        if(strstr($line, '%GROUP%')){
141            foreach((array) $USERINFO['grps'] as $grp){
142                $nid   = str_replace('%GROUP%',cleanID($grp),$id);
143                $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest);
144                $out[] = "$nid\t$nrest";
145            }
146        } else {
147            $id   = str_replace('%USER%',cleanID($_SERVER['REMOTE_USER']),$id);
148            $rest = str_replace('%USER%',auth_nameencode($_SERVER['REMOTE_USER']),$rest);
149            $out[] = "$id\t$rest";
150        }
151    }
152
153    return $out;
154}
155
156/**
157 * Event hook callback for AUTH_LOGIN_CHECK
158 *
159 * @param $evdata
160 * @return bool
161 */
162function auth_login_wrapper($evdata) {
163    return auth_login(
164        $evdata['user'],
165        $evdata['password'],
166        $evdata['sticky'],
167        $evdata['silent']
168    );
169}
170
171/**
172 * This tries to login the user based on the sent auth credentials
173 *
174 * The authentication works like this: if a username was given
175 * a new login is assumed and user/password are checked. If they
176 * are correct the password is encrypted with blowfish and stored
177 * together with the username in a cookie - the same info is stored
178 * in the session, too. Additonally a browserID is stored in the
179 * session.
180 *
181 * If no username was given the cookie is checked: if the username,
182 * crypted password and browserID match between session and cookie
183 * no further testing is done and the user is accepted
184 *
185 * If a cookie was found but no session info was availabe the
186 * blowfish encrypted password from the cookie is decrypted and
187 * together with username rechecked by calling this function again.
188 *
189 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
190 * are set.
191 *
192 * @author  Andreas Gohr <andi@splitbrain.org>
193 *
194 * @param   string  $user    Username
195 * @param   string  $pass    Cleartext Password
196 * @param   bool    $sticky  Cookie should not expire
197 * @param   bool    $silent  Don't show error on bad auth
198 * @return  bool             true on successful auth
199 */
200function auth_login($user, $pass, $sticky = false, $silent = false) {
201    global $USERINFO;
202    global $conf;
203    global $lang;
204    /* @var auth_basic $auth */
205    global $auth;
206
207    $sticky ? $sticky = true : $sticky = false; //sanity check
208
209    if(!$auth) return false;
210
211    if(!empty($user)) {
212        //usual login
213        if($auth->checkPass($user, $pass)) {
214            // make logininfo globally available
215            $_SERVER['REMOTE_USER'] = $user;
216            $secret                 = auth_cookiesalt(!$sticky); //bind non-sticky to session
217            auth_setCookie($user, PMA_blowfish_encrypt($pass, $secret), $sticky);
218            return true;
219        } else {
220            //invalid credentials - log off
221            if(!$silent) msg($lang['badlogin'], -1);
222            auth_logoff();
223            return false;
224        }
225    } else {
226        // read cookie information
227        list($user, $sticky, $pass) = auth_getCookie();
228        if($user && $pass) {
229            // we got a cookie - see if we can trust it
230
231            // get session info
232            $session = $_SESSION[DOKU_COOKIE]['auth'];
233            if(isset($session) &&
234                $auth->useSessionCache($user) &&
235                ($session['time'] >= time() - $conf['auth_security_timeout']) &&
236                ($session['user'] == $user) &&
237                ($session['pass'] == sha1($pass)) && //still crypted
238                ($session['buid'] == auth_browseruid())
239            ) {
240
241                // he has session, cookie and browser right - let him in
242                $_SERVER['REMOTE_USER'] = $user;
243                $USERINFO               = $session['info']; //FIXME move all references to session
244                return true;
245            }
246            // no we don't trust it yet - recheck pass but silent
247            $secret = auth_cookiesalt(!$sticky); //bind non-sticky to session
248            $pass   = PMA_blowfish_decrypt($pass, $secret);
249            return auth_login($user, $pass, $sticky, true);
250        }
251    }
252    //just to be sure
253    auth_logoff(true);
254    return false;
255}
256
257/**
258 * Checks if a given authentication token was stored in the session
259 *
260 * Will setup authentication data using data from the session if the
261 * token is correct. Will exit with a 401 Status if not.
262 *
263 * @author Andreas Gohr <andi@splitbrain.org>
264 * @param  string $token The authentication token
265 * @return boolean true (or will exit on failure)
266 */
267function auth_validateToken($token) {
268    if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']) {
269        // bad token
270        http_status(401);
271        print 'Invalid auth token - maybe the session timed out';
272        unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
273        exit;
274    }
275    // still here? trust the session data
276    global $USERINFO;
277    $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
278    $USERINFO               = $_SESSION[DOKU_COOKIE]['auth']['info'];
279    return true;
280}
281
282/**
283 * Create an auth token and store it in the session
284 *
285 * NOTE: this is completely unrelated to the getSecurityToken() function
286 *
287 * @author Andreas Gohr <andi@splitbrain.org>
288 * @return string The auth token
289 */
290function auth_createToken() {
291    $token = md5(mt_rand());
292    @session_start(); // reopen the session if needed
293    $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
294    session_write_close();
295    return $token;
296}
297
298/**
299 * Builds a pseudo UID from browser and IP data
300 *
301 * This is neither unique nor unfakable - still it adds some
302 * security. Using the first part of the IP makes sure
303 * proxy farms like AOLs are still okay.
304 *
305 * @author  Andreas Gohr <andi@splitbrain.org>
306 *
307 * @return  string  a MD5 sum of various browser headers
308 */
309function auth_browseruid() {
310    $ip  = clientIP(true);
311    $uid = '';
312    $uid .= $_SERVER['HTTP_USER_AGENT'];
313    $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
314    $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
315    $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
316    $uid .= substr($ip, 0, strpos($ip, '.'));
317    $uid = strtolower($uid);
318    return md5($uid);
319}
320
321/**
322 * Creates a random key to encrypt the password in cookies
323 *
324 * This function tries to read the password for encrypting
325 * cookies from $conf['metadir'].'/_htcookiesalt'
326 * if no such file is found a random key is created and
327 * and stored in this file.
328 *
329 * @author  Andreas Gohr <andi@splitbrain.org>
330 * @param   bool $addsession if true, the sessionid is added to the salt
331 * @return  string
332 */
333function auth_cookiesalt($addsession = false) {
334    global $conf;
335    $file = $conf['metadir'].'/_htcookiesalt';
336    $salt = io_readFile($file);
337    if(empty($salt)) {
338        $salt = uniqid(rand(), true);
339        io_saveFile($file, $salt);
340    }
341    if($addsession) {
342        $salt .= session_id();
343    }
344    return $salt;
345}
346
347/**
348 * Log out the current user
349 *
350 * This clears all authentication data and thus log the user
351 * off. It also clears session data.
352 *
353 * @author  Andreas Gohr <andi@splitbrain.org>
354 * @param bool $keepbc - when true, the breadcrumb data is not cleared
355 */
356function auth_logoff($keepbc = false) {
357    global $conf;
358    global $USERINFO;
359    /* @var auth_basic $auth */
360    global $auth;
361
362    // make sure the session is writable (it usually is)
363    @session_start();
364
365    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
366        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
367    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
368        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
369    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
370        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
371    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
372        unset($_SESSION[DOKU_COOKIE]['bc']);
373    if(isset($_SERVER['REMOTE_USER']))
374        unset($_SERVER['REMOTE_USER']);
375    $USERINFO = null; //FIXME
376
377    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
378    if(version_compare(PHP_VERSION, '5.2.0', '>')) {
379        setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
380    } else {
381        setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
382    }
383
384    if($auth) $auth->logOff();
385}
386
387/**
388 * Check if a user is a manager
389 *
390 * Should usually be called without any parameters to check the current
391 * user.
392 *
393 * The info is available through $INFO['ismanager'], too
394 *
395 * @author Andreas Gohr <andi@splitbrain.org>
396 * @see    auth_isadmin
397 * @param  string $user       Username
398 * @param  array  $groups     List of groups the user is in
399 * @param  bool   $adminonly  when true checks if user is admin
400 * @return bool
401 */
402function auth_ismanager($user = null, $groups = null, $adminonly = false) {
403    global $conf;
404    global $USERINFO;
405    /* @var auth_basic $auth */
406    global $auth;
407
408    if(!$auth) return false;
409    if(is_null($user)) {
410        if(!isset($_SERVER['REMOTE_USER'])) {
411            return false;
412        } else {
413            $user = $_SERVER['REMOTE_USER'];
414        }
415    }
416    if(is_null($groups)) {
417        $groups = (array) $USERINFO['grps'];
418    }
419
420    // check superuser match
421    if(auth_isMember($conf['superuser'], $user, $groups)) return true;
422    if($adminonly) return false;
423    // check managers
424    if(auth_isMember($conf['manager'], $user, $groups)) return true;
425
426    return false;
427}
428
429/**
430 * Check if a user is admin
431 *
432 * Alias to auth_ismanager with adminonly=true
433 *
434 * The info is available through $INFO['isadmin'], too
435 *
436 * @author Andreas Gohr <andi@splitbrain.org>
437 * @see auth_ismanager()
438 * @param  string $user       Username
439 * @param  array  $groups     List of groups the user is in
440 * @return bool
441 */
442function auth_isadmin($user = null, $groups = null) {
443    return auth_ismanager($user, $groups, true);
444}
445
446/**
447 * Match a user and his groups against a comma separated list of
448 * users and groups to determine membership status
449 *
450 * Note: all input should NOT be nameencoded.
451 *
452 * @param $memberlist string commaseparated list of allowed users and groups
453 * @param $user       string user to match against
454 * @param $groups     array  groups the user is member of
455 * @return bool       true for membership acknowledged
456 */
457function auth_isMember($memberlist, $user, array $groups) {
458    /* @var auth_basic $auth */
459    global $auth;
460    if(!$auth) return false;
461
462    // clean user and groups
463    if(!$auth->isCaseSensitive()) {
464        $user   = utf8_strtolower($user);
465        $groups = array_map('utf8_strtolower', $groups);
466    }
467    $user   = $auth->cleanUser($user);
468    $groups = array_map(array($auth, 'cleanGroup'), $groups);
469
470    // extract the memberlist
471    $members = explode(',', $memberlist);
472    $members = array_map('trim', $members);
473    $members = array_unique($members);
474    $members = array_filter($members);
475
476    // compare cleaned values
477    foreach($members as $member) {
478        if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member);
479        if($member[0] == '@') {
480            $member = $auth->cleanGroup(substr($member, 1));
481            if(in_array($member, $groups)) return true;
482        } else {
483            $member = $auth->cleanUser($member);
484            if($member == $user) return true;
485        }
486    }
487
488    // still here? not a member!
489    return false;
490}
491
492/**
493 * Convinience function for auth_aclcheck()
494 *
495 * This checks the permissions for the current user
496 *
497 * @author  Andreas Gohr <andi@splitbrain.org>
498 *
499 * @param  string  $id  page ID (needs to be resolved and cleaned)
500 * @return int          permission level
501 */
502function auth_quickaclcheck($id) {
503    global $conf;
504    global $USERINFO;
505    # if no ACL is used always return upload rights
506    if(!$conf['useacl']) return AUTH_UPLOAD;
507    return auth_aclcheck($id, $_SERVER['REMOTE_USER'], $USERINFO['grps']);
508}
509
510/**
511 * Returns the maximum rights a user has for
512 * the given ID or its namespace
513 *
514 * @author  Andreas Gohr <andi@splitbrain.org>
515 *
516 * @param  string       $id     page ID (needs to be resolved and cleaned)
517 * @param  string       $user   Username
518 * @param  array|null   $groups Array of groups the user is in
519 * @return int             permission level
520 */
521function auth_aclcheck($id, $user, $groups) {
522    global $conf;
523    global $AUTH_ACL;
524    /* @var auth_basic $auth */
525    global $auth;
526
527    // if no ACL is used always return upload rights
528    if(!$conf['useacl']) return AUTH_UPLOAD;
529    if(!$auth) return AUTH_NONE;
530
531    //make sure groups is an array
532    if(!is_array($groups)) $groups = array();
533
534    //if user is superuser or in superusergroup return 255 (acl_admin)
535    if(auth_isadmin($user, $groups)) {
536        return AUTH_ADMIN;
537    }
538
539    if(!$auth->isCaseSensitive()) {
540        $user   = utf8_strtolower($user);
541        $groups = array_map('utf8_strtolower', $groups);
542    }
543    $user   = $auth->cleanUser($user);
544    $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
545    $user   = auth_nameencode($user);
546
547    //prepend groups with @ and nameencode
548    $cnt = count($groups);
549    for($i = 0; $i < $cnt; $i++) {
550        $groups[$i] = '@'.auth_nameencode($groups[$i]);
551    }
552
553    $ns   = getNS($id);
554    $perm = -1;
555
556    if($user || count($groups)) {
557        //add ALL group
558        $groups[] = '@ALL';
559        //add User
560        if($user) $groups[] = $user;
561    } else {
562        $groups[] = '@ALL';
563    }
564
565    //check exact match first
566    $matches = preg_grep('/^'.preg_quote($id, '/').'\s+(\S+)\s+/u', $AUTH_ACL);
567    if(count($matches)) {
568        foreach($matches as $match) {
569            $match = preg_replace('/#.*$/', '', $match); //ignore comments
570            $acl   = preg_split('/\s+/', $match);
571            if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
572                $acl[1] = utf8_strtolower($acl[1]);
573            }
574            if(!in_array($acl[1], $groups)) {
575                continue;
576            }
577            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
578            if($acl[2] > $perm) {
579                $perm = $acl[2];
580            }
581        }
582        if($perm > -1) {
583            //we had a match - return it
584            return (int) $perm;
585        }
586    }
587
588    //still here? do the namespace checks
589    if($ns) {
590        $path = $ns.':*';
591    } else {
592        $path = '*'; //root document
593    }
594
595    do {
596        $matches = preg_grep('/^'.preg_quote($path, '/').'\s+(\S+)\s+/u', $AUTH_ACL);
597        if(count($matches)) {
598            foreach($matches as $match) {
599                $match = preg_replace('/#.*$/', '', $match); //ignore comments
600                $acl   = preg_split('/\s+/', $match);
601                if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
602                    $acl[1] = utf8_strtolower($acl[1]);
603                }
604                if(!in_array($acl[1], $groups)) {
605                    continue;
606                }
607                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
608                if($acl[2] > $perm) {
609                    $perm = $acl[2];
610                }
611            }
612            //we had a match - return it
613            if($perm != -1) {
614                return (int) $perm;
615            }
616        }
617        //get next higher namespace
618        $ns = getNS($ns);
619
620        if($path != '*') {
621            $path = $ns.':*';
622            if($path == ':*') $path = '*';
623        } else {
624            //we did this already
625            //looks like there is something wrong with the ACL
626            //break here
627            msg('No ACL setup yet! Denying access to everyone.');
628            return AUTH_NONE;
629        }
630    } while(1); //this should never loop endless
631    return AUTH_NONE;
632}
633
634/**
635 * Encode ASCII special chars
636 *
637 * Some auth backends allow special chars in their user and groupnames
638 * The special chars are encoded with this function. Only ASCII chars
639 * are encoded UTF-8 multibyte are left as is (different from usual
640 * urlencoding!).
641 *
642 * Decoding can be done with rawurldecode
643 *
644 * @author Andreas Gohr <gohr@cosmocode.de>
645 * @see rawurldecode()
646 */
647function auth_nameencode($name, $skip_group = false) {
648    global $cache_authname;
649    $cache =& $cache_authname;
650    $name  = (string) $name;
651
652    // never encode wildcard FS#1955
653    if($name == '%USER%') return $name;
654    if($name == '%GROUP%') return $name;
655
656    if(!isset($cache[$name][$skip_group])) {
657        if($skip_group && $name{0} == '@') {
658            $cache[$name][$skip_group] = '@'.preg_replace(
659                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
660                "'%'.dechex(ord(substr('\\1',-1)))", substr($name, 1)
661            );
662        } else {
663            $cache[$name][$skip_group] = preg_replace(
664                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
665                "'%'.dechex(ord(substr('\\1',-1)))", $name
666            );
667        }
668    }
669
670    return $cache[$name][$skip_group];
671}
672
673/**
674 * Create a pronouncable password
675 *
676 * @author  Andreas Gohr <andi@splitbrain.org>
677 * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
678 *
679 * @return string  pronouncable password
680 */
681function auth_pwgen() {
682    $pw = '';
683    $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
684    $v  = 'aeiou'; //vowels
685    $a  = $c.$v; //both
686
687    //use two syllables...
688    for($i = 0; $i < 2; $i++) {
689        $pw .= $c[rand(0, strlen($c) - 1)];
690        $pw .= $v[rand(0, strlen($v) - 1)];
691        $pw .= $a[rand(0, strlen($a) - 1)];
692    }
693    //... and add a nice number
694    $pw .= rand(10, 99);
695
696    return $pw;
697}
698
699/**
700 * Sends a password to the given user
701 *
702 * @author  Andreas Gohr <andi@splitbrain.org>
703 * @param string $user Login name of the user
704 * @param string $password The new password in clear text
705 * @return bool  true on success
706 */
707function auth_sendPassword($user, $password) {
708    global $lang;
709    /* @var auth_basic $auth */
710    global $auth;
711    if(!$auth) return false;
712
713    $user     = $auth->cleanUser($user);
714    $userinfo = $auth->getUserData($user);
715
716    if(!$userinfo['mail']) return false;
717
718    $text = rawLocale('password');
719    $trep = array(
720        'FULLNAME' => $userinfo['name'],
721        'LOGIN'    => $user,
722        'PASSWORD' => $password
723    );
724
725    $mail = new Mailer();
726    $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
727    $mail->subject($lang['regpwmail']);
728    $mail->setBody($text, $trep);
729    return $mail->send();
730}
731
732/**
733 * Register a new user
734 *
735 * This registers a new user - Data is read directly from $_POST
736 *
737 * @author  Andreas Gohr <andi@splitbrain.org>
738 * @return bool  true on success, false on any error
739 */
740function register() {
741    global $lang;
742    global $conf;
743    /* @var auth_basic $auth */
744    global $auth;
745    global $INPUT;
746
747    if(!$INPUT->post->bool('save')) return false;
748    if(!actionOK('register')) return false;
749
750    // gather input
751    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
752    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
753    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
754    $pass     = $INPUT->post->str('pass');
755    $passchk  = $INPUT->post->str('passchk');
756
757    if(empty($login) || empty($fullname) || empty($email)) {
758        msg($lang['regmissing'], -1);
759        return false;
760    }
761
762    if($conf['autopasswd']) {
763        $pass = auth_pwgen(); // automatically generate password
764    } elseif(empty($pass) || empty($passchk)) {
765        msg($lang['regmissing'], -1); // complain about missing passwords
766        return false;
767    } elseif($pass != $passchk) {
768        msg($lang['regbadpass'], -1); // complain about misspelled passwords
769        return false;
770    }
771
772    //check mail
773    if(!mail_isvalid($email)) {
774        msg($lang['regbadmail'], -1);
775        return false;
776    }
777
778    //okay try to create the user
779    if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) {
780        msg($lang['reguexists'], -1);
781        return false;
782    }
783
784    // send notification about the new user
785    $subscription = new Subscription();
786    $subscription->send_register($login, $fullname, $email);
787
788    // are we done?
789    if(!$conf['autopasswd']) {
790        msg($lang['regsuccess2'], 1);
791        return true;
792    }
793
794    // autogenerated password? then send password to user
795    if(auth_sendPassword($login, $pass)) {
796        msg($lang['regsuccess'], 1);
797        return true;
798    } else {
799        msg($lang['regmailfail'], -1);
800        return false;
801    }
802}
803
804/**
805 * Update user profile
806 *
807 * @author    Christopher Smith <chris@jalakai.co.uk>
808 */
809function updateprofile() {
810    global $conf;
811    global $lang;
812    /* @var auth_basic $auth */
813    global $auth;
814    /* @var Input $INPUT */
815    global $INPUT;
816
817    if(!$INPUT->post->bool('save')) return false;
818    if(!checkSecurityToken()) return false;
819
820    if(!actionOK('profile')) {
821        msg($lang['profna'], -1);
822        return false;
823    }
824
825    $changes         = array();
826    $changes['pass'] = $INPUT->post->str('newpass');
827    $changes['name'] = $INPUT->post->str('fullname');
828    $changes['mail'] = $INPUT->post->str('email');
829
830    // check misspelled passwords
831    if($changes['pass'] != $INPUT->post->str('passchk')) {
832        msg($lang['regbadpass'], -1);
833        return false;
834    }
835
836    // clean fullname and email
837    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
838    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
839
840    // no empty name and email (except the backend doesn't support them)
841    if((empty($changes['name']) && $auth->canDo('modName')) ||
842        (empty($changes['mail']) && $auth->canDo('modMail'))
843    ) {
844        msg($lang['profnoempty'], -1);
845        return false;
846    }
847    if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
848        msg($lang['regbadmail'], -1);
849        return false;
850    }
851
852    $changes = array_filter($changes);
853
854    // check for unavailable capabilities
855    if(!$auth->canDo('modName')) unset($changes['name']);
856    if(!$auth->canDo('modMail')) unset($changes['mail']);
857    if(!$auth->canDo('modPass')) unset($changes['pass']);
858
859    // anything to do?
860    if(!count($changes)) {
861        msg($lang['profnochange'], -1);
862        return false;
863    }
864
865    if($conf['profileconfirm']) {
866        if(!$auth->checkPass($_SERVER['REMOTE_USER'], $INPUT->post->str('oldpass'))) {
867            msg($lang['badlogin'], -1);
868            return false;
869        }
870    }
871
872    if($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
873        // update cookie and session with the changed data
874        if($changes['pass']) {
875            list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
876            $pass = PMA_blowfish_encrypt($changes['pass'], auth_cookiesalt(!$sticky));
877            auth_setCookie($_SERVER['REMOTE_USER'], $pass, (bool) $sticky);
878        }
879        return true;
880    }
881
882    return false;
883}
884
885/**
886 * Send a  new password
887 *
888 * This function handles both phases of the password reset:
889 *
890 *   - handling the first request of password reset
891 *   - validating the password reset auth token
892 *
893 * @author Benoit Chesneau <benoit@bchesneau.info>
894 * @author Chris Smith <chris@jalakai.co.uk>
895 * @author Andreas Gohr <andi@splitbrain.org>
896 *
897 * @return bool true on success, false on any error
898 */
899function act_resendpwd() {
900    global $lang;
901    global $conf;
902    /* @var auth_basic $auth */
903    global $auth;
904    /* @var Input $INPUT */
905    global $INPUT;
906
907    if(!actionOK('resendpwd')) {
908        msg($lang['resendna'], -1);
909        return false;
910    }
911
912    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
913
914    if($token) {
915        // we're in token phase - get user info from token
916
917        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
918        if(!@file_exists($tfile)) {
919            msg($lang['resendpwdbadauth'], -1);
920            $INPUT->remove('pwauth');
921            return false;
922        }
923        // token is only valid for 3 days
924        if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
925            msg($lang['resendpwdbadauth'], -1);
926            $INPUT->remove('pwauth');
927            @unlink($tfile);
928            return false;
929        }
930
931        $user     = io_readfile($tfile);
932        $userinfo = $auth->getUserData($user);
933        if(!$userinfo['mail']) {
934            msg($lang['resendpwdnouser'], -1);
935            return false;
936        }
937
938        if(!$conf['autopasswd']) { // we let the user choose a password
939            $pass = $INPUT->str('pass');
940
941            // password given correctly?
942            if(!$pass) return false;
943            if($pass != $INPUT->str('passchk')) {
944                msg($lang['regbadpass'], -1);
945                return false;
946            }
947
948            // change it
949            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
950                msg('error modifying user data', -1);
951                return false;
952            }
953
954        } else { // autogenerate the password and send by mail
955
956            $pass = auth_pwgen();
957            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
958                msg('error modifying user data', -1);
959                return false;
960            }
961
962            if(auth_sendPassword($user, $pass)) {
963                msg($lang['resendpwdsuccess'], 1);
964            } else {
965                msg($lang['regmailfail'], -1);
966            }
967        }
968
969        @unlink($tfile);
970        return true;
971
972    } else {
973        // we're in request phase
974
975        if(!$INPUT->post->bool('save')) return false;
976
977        if(!$INPUT->post->str('login')) {
978            msg($lang['resendpwdmissing'], -1);
979            return false;
980        } else {
981            $user = trim($auth->cleanUser($INPUT->post->str('login')));
982        }
983
984        $userinfo = $auth->getUserData($user);
985        if(!$userinfo['mail']) {
986            msg($lang['resendpwdnouser'], -1);
987            return false;
988        }
989
990        // generate auth token
991        $token = md5(auth_cookiesalt().$user); //secret but user based
992        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
993        $url   = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
994
995        io_saveFile($tfile, $user);
996
997        $text = rawLocale('pwconfirm');
998        $trep = array(
999            'FULLNAME' => $userinfo['name'],
1000            'LOGIN'    => $user,
1001            'CONFIRM'  => $url
1002        );
1003
1004        $mail = new Mailer();
1005        $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1006        $mail->subject($lang['regpwmail']);
1007        $mail->setBody($text, $trep);
1008        if($mail->send()) {
1009            msg($lang['resendpwdconfirm'], 1);
1010        } else {
1011            msg($lang['regmailfail'], -1);
1012        }
1013        return true;
1014    }
1015    // never reached
1016}
1017
1018/**
1019 * Encrypts a password using the given method and salt
1020 *
1021 * If the selected method needs a salt and none was given, a random one
1022 * is chosen.
1023 *
1024 * @author  Andreas Gohr <andi@splitbrain.org>
1025 * @param string $clear The clear text password
1026 * @param string $method The hashing method
1027 * @param string $salt A salt, null for random
1028 * @return  string  The crypted password
1029 */
1030function auth_cryptPassword($clear, $method = '', $salt = null) {
1031    global $conf;
1032    if(empty($method)) $method = $conf['passcrypt'];
1033
1034    $pass = new PassHash();
1035    $call = 'hash_'.$method;
1036
1037    if(!method_exists($pass, $call)) {
1038        msg("Unsupported crypt method $method", -1);
1039        return false;
1040    }
1041
1042    return $pass->$call($clear, $salt);
1043}
1044
1045/**
1046 * Verifies a cleartext password against a crypted hash
1047 *
1048 * @author Andreas Gohr <andi@splitbrain.org>
1049 * @param  string $clear The clear text password
1050 * @param  string $crypt The hash to compare with
1051 * @return bool true if both match
1052 */
1053function auth_verifyPassword($clear, $crypt) {
1054    $pass = new PassHash();
1055    return $pass->verify_hash($clear, $crypt);
1056}
1057
1058/**
1059 * Set the authentication cookie and add user identification data to the session
1060 *
1061 * @param string  $user       username
1062 * @param string  $pass       encrypted password
1063 * @param bool    $sticky     whether or not the cookie will last beyond the session
1064 * @return bool
1065 */
1066function auth_setCookie($user, $pass, $sticky) {
1067    global $conf;
1068    /* @var auth_basic $auth */
1069    global $auth;
1070    global $USERINFO;
1071
1072    if(!$auth) return false;
1073    $USERINFO = $auth->getUserData($user);
1074
1075    // set cookie
1076    $cookie    = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
1077    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1078    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1079    if(version_compare(PHP_VERSION, '5.2.0', '>')) {
1080        setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
1081    } else {
1082        setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
1083    }
1084    // set session
1085    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1086    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1087    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1088    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1089    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1090
1091    return true;
1092}
1093
1094/**
1095 * Returns the user, (encrypted) password and sticky bit from cookie
1096 *
1097 * @returns array
1098 */
1099function auth_getCookie() {
1100    if(!isset($_COOKIE[DOKU_COOKIE])) {
1101        return array(null, null, null);
1102    }
1103    list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
1104    $sticky = (bool) $sticky;
1105    $pass   = base64_decode($pass);
1106    $user   = base64_decode($user);
1107    return array($user, $sticky, $pass);
1108}
1109
1110//Setup VIM: ex: et ts=2 :
1111