xref: /dokuwiki/inc/auth.php (revision 32e82180a785b09b1886cf44ecca5ed22ce37b9d)
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 auth_basic $auth */
38    global $auth;
39    /* @var Input $INPUT */
40    global $INPUT;
41    global $AUTH_ACL;
42    global $lang;
43    $AUTH_ACL = array();
44
45    if(!$conf['useacl']) return false;
46
47    // load the the backend auth functions and instantiate the auth object XXX
48    if(@file_exists(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php')) {
49        require_once(DOKU_INC.'inc/auth/basic.class.php');
50        require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php');
51
52        $auth_class = "auth_".$conf['authtype'];
53        if(class_exists($auth_class)) {
54            $auth = new $auth_class();
55            if($auth->success == false) {
56                // degrade to unauthenticated user
57                unset($auth);
58                auth_logoff();
59                msg($lang['authtempfail'], -1);
60            }
61        } else {
62            nice_die($lang['authmodfailed']);
63        }
64    } else {
65        nice_die($lang['authmodfailed']);
66    }
67
68    if(!$auth) return false;
69
70    // do the login either by cookie or provided credentials XXX
71    $INPUT->set('http_credentials', false);
72    if(!$conf['rememberme']) $INPUT->set('r', false);
73
74    // handle renamed HTTP_AUTHORIZATION variable (can happen when a fix like
75    // the one presented at
76    // http://www.besthostratings.com/articles/http-auth-php-cgi.html is used
77    // for enabling HTTP authentication with CGI/SuExec)
78    if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
79        $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
80    // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
81    if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
82        list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
83            explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
84    }
85
86    // if no credentials were given try to use HTTP auth (for SSO)
87    if(!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])) {
88        $INPUT->set('u', $_SERVER['PHP_AUTH_USER']);
89        $INPUT->set('p', $_SERVER['PHP_AUTH_PW']);
90        $INPUT->set('http_credentials', true);
91    }
92
93    // apply cleaning
94    $INPUT->set('u', $auth->cleanUser($INPUT->str('u')));
95
96    if($INPUT->str('authtok')) {
97        // when an authentication token is given, trust the session
98        auth_validateToken($INPUT->str('authtok'));
99    } elseif(!is_null($auth) && $auth->canDo('external')) {
100        // external trust mechanism in place
101        $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
102    } else {
103        $evdata = array(
104            'user'     => $INPUT->str('u'),
105            'password' => $INPUT->str('p'),
106            'sticky'   => $INPUT->bool('r'),
107            'silent'   => $INPUT->bool('http_credentials')
108        );
109        trigger_event('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
110    }
111
112    //load ACL into a global array XXX
113    $AUTH_ACL = auth_loadACL();
114
115    return true;
116}
117
118/**
119 * Loads the ACL setup and handle user wildcards
120 *
121 * @author Andreas Gohr <andi@splitbrain.org>
122 * @return array
123 */
124function auth_loadACL() {
125    global $config_cascade;
126    global $USERINFO;
127
128    if(!is_readable($config_cascade['acl']['default'])) return array();
129
130    $acl = file($config_cascade['acl']['default']);
131
132    //support user wildcard
133    $out = array();
134    if(isset($_SERVER['REMOTE_USER'])){
135        $len = count($acl);
136        for($i = 0; $i < $len; $i++) {
137            if($acl[$i]{0} == '#') continue;
138            if(!trim($acl[$i])) continue;
139            list($id,$rest) = preg_split('/\s+/',$acl[$i],2);
140
141            if(strstr($acl[$i], '%GROUP%')){
142                foreach($USERINFO['grps'] as $grp){
143                    $nid   = str_replace('%GROUP%',cleanID($grp),$id);
144                    $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest);
145                    $out[] = "$nid\t$nrest";
146                }
147            } else {
148                $id   = str_replace('%USER%',cleanID($_SERVER['REMOTE_USER']),$id);
149                $rest = str_replace('%USER%',auth_nameencode($_SERVER['REMOTE_USER']),$rest);
150                $out[] = "$id\t$rest";
151            }
152        }
153    }
154    return $out;
155}
156
157/**
158 * Event hook callback for AUTH_LOGIN_CHECK
159 *
160 * @param $evdata
161 * @return bool
162 */
163function auth_login_wrapper($evdata) {
164    return auth_login(
165        $evdata['user'],
166        $evdata['password'],
167        $evdata['sticky'],
168        $evdata['silent']
169    );
170}
171
172/**
173 * This tries to login the user based on the sent auth credentials
174 *
175 * The authentication works like this: if a username was given
176 * a new login is assumed and user/password are checked. If they
177 * are correct the password is encrypted with blowfish and stored
178 * together with the username in a cookie - the same info is stored
179 * in the session, too. Additonally a browserID is stored in the
180 * session.
181 *
182 * If no username was given the cookie is checked: if the username,
183 * crypted password and browserID match between session and cookie
184 * no further testing is done and the user is accepted
185 *
186 * If a cookie was found but no session info was availabe the
187 * blowfish encrypted password from the cookie is decrypted and
188 * together with username rechecked by calling this function again.
189 *
190 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
191 * are set.
192 *
193 * @author  Andreas Gohr <andi@splitbrain.org>
194 *
195 * @param   string  $user    Username
196 * @param   string  $pass    Cleartext Password
197 * @param   bool    $sticky  Cookie should not expire
198 * @param   bool    $silent  Don't show error on bad auth
199 * @return  bool             true on successful auth
200 */
201function auth_login($user, $pass, $sticky = false, $silent = false) {
202    global $USERINFO;
203    global $conf;
204    global $lang;
205    /* @var auth_basic $auth */
206    global $auth;
207
208    $sticky ? $sticky = true : $sticky = false; //sanity check
209
210    if(!$auth) return false;
211
212    if(!empty($user)) {
213        //usual login
214        if($auth->checkPass($user, $pass)) {
215            // make logininfo globally available
216            $_SERVER['REMOTE_USER'] = $user;
217            $secret                 = auth_cookiesalt(!$sticky); //bind non-sticky to session
218            auth_setCookie($user, PMA_blowfish_encrypt($pass, $secret), $sticky);
219            return true;
220        } else {
221            //invalid credentials - log off
222            if(!$silent) msg($lang['badlogin'], -1);
223            auth_logoff();
224            return false;
225        }
226    } else {
227        // read cookie information
228        list($user, $sticky, $pass) = auth_getCookie();
229        if($user && $pass) {
230            // we got a cookie - see if we can trust it
231
232            // get session info
233            $session = $_SESSION[DOKU_COOKIE]['auth'];
234            if(isset($session) &&
235                $auth->useSessionCache($user) &&
236                ($session['time'] >= time() - $conf['auth_security_timeout']) &&
237                ($session['user'] == $user) &&
238                ($session['pass'] == sha1($pass)) && //still crypted
239                ($session['buid'] == auth_browseruid())
240            ) {
241
242                // he has session, cookie and browser right - let him in
243                $_SERVER['REMOTE_USER'] = $user;
244                $USERINFO               = $session['info']; //FIXME move all references to session
245                return true;
246            }
247            // no we don't trust it yet - recheck pass but silent
248            $secret = auth_cookiesalt(!$sticky); //bind non-sticky to session
249            $pass   = PMA_blowfish_decrypt($pass, $secret);
250            return auth_login($user, $pass, $sticky, true);
251        }
252    }
253    //just to be sure
254    auth_logoff(true);
255    return false;
256}
257
258/**
259 * Checks if a given authentication token was stored in the session
260 *
261 * Will setup authentication data using data from the session if the
262 * token is correct. Will exit with a 401 Status if not.
263 *
264 * @author Andreas Gohr <andi@splitbrain.org>
265 * @param  string $token The authentication token
266 * @return boolean true (or will exit on failure)
267 */
268function auth_validateToken($token) {
269    if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']) {
270        // bad token
271        header("HTTP/1.0 401 Unauthorized");
272        print 'Invalid auth token - maybe the session timed out';
273        unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
274        exit;
275    }
276    // still here? trust the session data
277    global $USERINFO;
278    $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
279    $USERINFO               = $_SESSION[DOKU_COOKIE]['auth']['info'];
280    return true;
281}
282
283/**
284 * Create an auth token and store it in the session
285 *
286 * NOTE: this is completely unrelated to the getSecurityToken() function
287 *
288 * @author Andreas Gohr <andi@splitbrain.org>
289 * @return string The auth token
290 */
291function auth_createToken() {
292    $token = md5(mt_rand());
293    @session_start(); // reopen the session if needed
294    $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
295    session_write_close();
296    return $token;
297}
298
299/**
300 * Builds a pseudo UID from browser and IP data
301 *
302 * This is neither unique nor unfakable - still it adds some
303 * security. Using the first part of the IP makes sure
304 * proxy farms like AOLs are stil okay.
305 *
306 * @author  Andreas Gohr <andi@splitbrain.org>
307 *
308 * @return  string  a MD5 sum of various browser headers
309 */
310function auth_browseruid() {
311    $ip  = clientIP(true);
312    $uid = '';
313    $uid .= $_SERVER['HTTP_USER_AGENT'];
314    $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
315    $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
316    $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
317    $uid .= substr($ip, 0, strpos($ip, '.'));
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    $ci = '';
540    if(!$auth->isCaseSensitive()) $ci = 'ui';
541
542    $user   = $auth->cleanUser($user);
543    $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
544    $user   = auth_nameencode($user);
545
546    //prepend groups with @ and nameencode
547    $cnt = count($groups);
548    for($i = 0; $i < $cnt; $i++) {
549        $groups[$i] = '@'.auth_nameencode($groups[$i]);
550    }
551
552    $ns   = getNS($id);
553    $perm = -1;
554
555    if($user || count($groups)) {
556        //add ALL group
557        $groups[] = '@ALL';
558        //add User
559        if($user) $groups[] = $user;
560    } else {
561        $groups[] = '@ALL';
562    }
563
564    //check exact match first
565    $matches = preg_grep('/^'.preg_quote($id, '/').'\s+(\S+)\s+/'.$ci, $AUTH_ACL);
566    if(count($matches)) {
567        foreach($matches as $match) {
568            $match = preg_replace('/#.*$/', '', $match); //ignore comments
569            $acl   = preg_split('/\s+/', $match);
570            if(!in_array($acl[1], $groups)) {
571                continue;
572            }
573            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
574            if($acl[2] > $perm) {
575                $perm = $acl[2];
576            }
577        }
578        if($perm > -1) {
579            //we had a match - return it
580            return $perm;
581        }
582    }
583
584    //still here? do the namespace checks
585    if($ns) {
586        $path = $ns.':*';
587    } else {
588        $path = '*'; //root document
589    }
590
591    do {
592        $matches = preg_grep('/^'.preg_quote($path, '/').'\s+(\S+)\s+/'.$ci, $AUTH_ACL);
593        if(count($matches)) {
594            foreach($matches as $match) {
595                $match = preg_replace('/#.*$/', '', $match); //ignore comments
596                $acl   = preg_split('/\s+/', $match);
597                if(!in_array($acl[1], $groups)) {
598                    continue;
599                }
600                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
601                if($acl[2] > $perm) {
602                    $perm = $acl[2];
603                }
604            }
605            //we had a match - return it
606            if($perm != -1) {
607                return $perm;
608            }
609        }
610        //get next higher namespace
611        $ns = getNS($ns);
612
613        if($path != '*') {
614            $path = $ns.':*';
615            if($path == ':*') $path = '*';
616        } else {
617            //we did this already
618            //looks like there is something wrong with the ACL
619            //break here
620            msg('No ACL setup yet! Denying access to everyone.');
621            return AUTH_NONE;
622        }
623    } while(1); //this should never loop endless
624    return AUTH_NONE;
625}
626
627/**
628 * Encode ASCII special chars
629 *
630 * Some auth backends allow special chars in their user and groupnames
631 * The special chars are encoded with this function. Only ASCII chars
632 * are encoded UTF-8 multibyte are left as is (different from usual
633 * urlencoding!).
634 *
635 * Decoding can be done with rawurldecode
636 *
637 * @author Andreas Gohr <gohr@cosmocode.de>
638 * @see rawurldecode()
639 */
640function auth_nameencode($name, $skip_group = false) {
641    global $cache_authname;
642    $cache =& $cache_authname;
643    $name  = (string) $name;
644
645    // never encode wildcard FS#1955
646    if($name == '%USER%') return $name;
647    if($name == '%GROUP%') return $name;
648
649    if(!isset($cache[$name][$skip_group])) {
650        if($skip_group && $name{0} == '@') {
651            $cache[$name][$skip_group] = '@'.preg_replace(
652                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
653                "'%'.dechex(ord(substr('\\1',-1)))", substr($name, 1)
654            );
655        } else {
656            $cache[$name][$skip_group] = preg_replace(
657                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
658                "'%'.dechex(ord(substr('\\1',-1)))", $name
659            );
660        }
661    }
662
663    return $cache[$name][$skip_group];
664}
665
666/**
667 * Create a pronouncable password
668 *
669 * @author  Andreas Gohr <andi@splitbrain.org>
670 * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
671 *
672 * @return string  pronouncable password
673 */
674function auth_pwgen() {
675    $pw = '';
676    $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
677    $v  = 'aeiou'; //vowels
678    $a  = $c.$v; //both
679
680    //use two syllables...
681    for($i = 0; $i < 2; $i++) {
682        $pw .= $c[rand(0, strlen($c) - 1)];
683        $pw .= $v[rand(0, strlen($v) - 1)];
684        $pw .= $a[rand(0, strlen($a) - 1)];
685    }
686    //... and add a nice number
687    $pw .= rand(10, 99);
688
689    return $pw;
690}
691
692/**
693 * Sends a password to the given user
694 *
695 * @author  Andreas Gohr <andi@splitbrain.org>
696 * @param string $user Login name of the user
697 * @param string $password The new password in clear text
698 * @return bool  true on success
699 */
700function auth_sendPassword($user, $password) {
701    global $lang;
702    /* @var auth_basic $auth */
703    global $auth;
704    if(!$auth) return false;
705
706    $user     = $auth->cleanUser($user);
707    $userinfo = $auth->getUserData($user);
708
709    if(!$userinfo['mail']) return false;
710
711    $text = rawLocale('password');
712    $trep = array(
713        'FULLNAME' => $userinfo['name'],
714        'LOGIN'    => $user,
715        'PASSWORD' => $password
716    );
717
718    $mail = new Mailer();
719    $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
720    $mail->subject($lang['regpwmail']);
721    $mail->setBody($text, $trep);
722    return $mail->send();
723}
724
725/**
726 * Register a new user
727 *
728 * This registers a new user - Data is read directly from $_POST
729 *
730 * @author  Andreas Gohr <andi@splitbrain.org>
731 * @return bool  true on success, false on any error
732 */
733function register() {
734    global $lang;
735    global $conf;
736    /* @var auth_basic $auth */
737    global $auth;
738
739    if(!$_POST['save']) return false;
740    if(!actionOK('register')) return false;
741
742    //clean username
743    $_POST['login'] = trim($auth->cleanUser($_POST['login']));
744
745    //clean fullname and email
746    $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $_POST['fullname']));
747    $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $_POST['email']));
748
749    if(empty($_POST['login']) ||
750        empty($_POST['fullname']) ||
751        empty($_POST['email'])
752    ) {
753        msg($lang['regmissing'], -1);
754        return false;
755    }
756
757    if($conf['autopasswd']) {
758        $pass = auth_pwgen(); // automatically generate password
759    } elseif(empty($_POST['pass']) ||
760        empty($_POST['passchk'])
761    ) {
762        msg($lang['regmissing'], -1); // complain about missing passwords
763        return false;
764    } elseif($_POST['pass'] != $_POST['passchk']) {
765        msg($lang['regbadpass'], -1); // complain about misspelled passwords
766        return false;
767    } else {
768        $pass = $_POST['pass']; // accept checked and valid password
769    }
770
771    //check mail
772    if(!mail_isvalid($_POST['email'])) {
773        msg($lang['regbadmail'], -1);
774        return false;
775    }
776
777    //okay try to create the user
778    if(!$auth->triggerUserMod('create', array($_POST['login'], $pass, $_POST['fullname'], $_POST['email']))) {
779        msg($lang['reguexists'], -1);
780        return false;
781    }
782
783    // create substitutions for use in notification email
784    $substitutions = array(
785        'NEWUSER'  => $_POST['login'],
786        'NEWNAME'  => $_POST['fullname'],
787        'NEWEMAIL' => $_POST['email'],
788    );
789
790    if(!$conf['autopasswd']) {
791        msg($lang['regsuccess2'], 1);
792        notify('', 'register', '', $_POST['login'], false, $substitutions);
793        return true;
794    }
795
796    // autogenerated password? then send him the password
797    if(auth_sendPassword($_POST['login'], $pass)) {
798        msg($lang['regsuccess'], 1);
799        notify('', 'register', '', $_POST['login'], false, $substitutions);
800        return true;
801    } else {
802        msg($lang['regmailfail'], -1);
803        return false;
804    }
805}
806
807/**
808 * Update user profile
809 *
810 * @author    Christopher Smith <chris@jalakai.co.uk>
811 */
812function updateprofile() {
813    global $conf;
814    global $lang;
815    /* @var auth_basic $auth */
816    global $auth;
817    /* @var Input $INPUT */
818    global $INPUT;
819
820    if(!$INPUT->post->bool('save')) return false;
821    if(!checkSecurityToken()) return false;
822
823    if(!actionOK('profile')) {
824        msg($lang['profna'], -1);
825        return false;
826    }
827
828    $changes         = array();
829    $changes['pass'] = $INPUT->post->str('newpass');
830    $changes['name'] = $INPUT->post->str('fullname');
831    $changes['mail'] = $INPUT->post->str('email');
832
833    // check misspelled passwords
834    if($changes['pass'] != $INPUT->post->str('passchk')) {
835        msg($lang['regbadpass'], -1);
836        return false;
837    }
838
839    // clean fullname and email
840    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
841    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
842
843    // no empty name and email (except the backend doesn't support them)
844    if((empty($changes['name']) && $auth->canDo('modName')) ||
845        (empty($changes['mail']) && $auth->canDo('modMail'))
846    ) {
847        msg($lang['profnoempty'], -1);
848        return false;
849    }
850    if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
851        msg($lang['regbadmail'], -1);
852        return false;
853    }
854
855    $changes = array_filter($changes);
856
857    // check for unavailable capabilities
858    if(!$auth->canDo('modName')) unset($changes['name']);
859    if(!$auth->canDo('modMail')) unset($changes['mail']);
860    if(!$auth->canDo('modPass')) unset($changes['pass']);
861
862    // anything to do?
863    if(!count($changes)) {
864        msg($lang['profnochange'], -1);
865        return false;
866    }
867
868    if($conf['profileconfirm']) {
869        if(!$auth->checkPass($_SERVER['REMOTE_USER'], $INPUT->post->str('oldpass'))) {
870            msg($lang['badlogin'], -1);
871            return false;
872        }
873    }
874
875    if($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
876        // update cookie and session with the changed data
877        if($changes['pass']) {
878            list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
879            $pass = PMA_blowfish_encrypt($changes['pass'], auth_cookiesalt(!$sticky));
880            auth_setCookie($_SERVER['REMOTE_USER'], $pass, (bool) $sticky);
881        }
882        return true;
883    }
884
885    return false;
886}
887
888/**
889 * Send a  new password
890 *
891 * This function handles both phases of the password reset:
892 *
893 *   - handling the first request of password reset
894 *   - validating the password reset auth token
895 *
896 * @author Benoit Chesneau <benoit@bchesneau.info>
897 * @author Chris Smith <chris@jalakai.co.uk>
898 * @author Andreas Gohr <andi@splitbrain.org>
899 *
900 * @return bool true on success, false on any error
901 */
902function act_resendpwd() {
903    global $lang;
904    global $conf;
905    /* @var auth_basic $auth */
906    global $auth;
907    /* @var Input $INPUT */
908    global $INPUT;
909
910    if(!actionOK('resendpwd')) {
911        msg($lang['resendna'], -1);
912        return false;
913    }
914
915    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
916
917    if($token) {
918        // we're in token phase - get user info from token
919
920        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
921        if(!@file_exists($tfile)) {
922            msg($lang['resendpwdbadauth'], -1);
923            $INPUT->remove('pwauth');
924            return false;
925        }
926        // token is only valid for 3 days
927        if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
928            msg($lang['resendpwdbadauth'], -1);
929            $INPUT->remove('pwauth');
930            @unlink($tfile);
931            return false;
932        }
933
934        $user     = io_readfile($tfile);
935        $userinfo = $auth->getUserData($user);
936        if(!$userinfo['mail']) {
937            msg($lang['resendpwdnouser'], -1);
938            return false;
939        }
940
941        if(!$conf['autopasswd']) { // we let the user choose a password
942            $pass = $INPUT->str('pass');
943
944            // password given correctly?
945            if(!$pass) return false;
946            if($pass != $INPUT->str('passchk')) {
947                msg($lang['regbadpass'], -1);
948                return false;
949            }
950
951            // change it
952            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
953                msg('error modifying user data', -1);
954                return false;
955            }
956
957        } else { // autogenerate the password and send by mail
958
959            $pass = auth_pwgen();
960            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
961                msg('error modifying user data', -1);
962                return false;
963            }
964
965            if(auth_sendPassword($user, $pass)) {
966                msg($lang['resendpwdsuccess'], 1);
967            } else {
968                msg($lang['regmailfail'], -1);
969            }
970        }
971
972        @unlink($tfile);
973        return true;
974
975    } else {
976        // we're in request phase
977
978        if(!$INPUT->post->bool('save')) return false;
979
980        if(!$INPUT->post->str('login')) {
981            msg($lang['resendpwdmissing'], -1);
982            return false;
983        } else {
984            $user = trim($auth->cleanUser($INPUT->post->str('login')));
985        }
986
987        $userinfo = $auth->getUserData($user);
988        if(!$userinfo['mail']) {
989            msg($lang['resendpwdnouser'], -1);
990            return false;
991        }
992
993        // generate auth token
994        $token = md5(auth_cookiesalt().$user); //secret but user based
995        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
996        $url   = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
997
998        io_saveFile($tfile, $user);
999
1000        $text = rawLocale('pwconfirm');
1001        $trep = array(
1002            'FULLNAME' => $userinfo['name'],
1003            'LOGIN'    => $user,
1004            'CONFIRM'  => $url
1005        );
1006
1007        $mail = new Mailer();
1008        $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1009        $mail->subject($lang['regpwmail']);
1010        $mail->setBody($text, $trep);
1011        if($mail->send()) {
1012            msg($lang['resendpwdconfirm'], 1);
1013        } else {
1014            msg($lang['regmailfail'], -1);
1015        }
1016        return true;
1017    }
1018    // never reached
1019}
1020
1021/**
1022 * Encrypts a password using the given method and salt
1023 *
1024 * If the selected method needs a salt and none was given, a random one
1025 * is chosen.
1026 *
1027 * @author  Andreas Gohr <andi@splitbrain.org>
1028 * @param string $clear The clear text password
1029 * @param string $method The hashing method
1030 * @param string $salt A salt, null for random
1031 * @return  string  The crypted password
1032 */
1033function auth_cryptPassword($clear, $method = '', $salt = null) {
1034    global $conf;
1035    if(empty($method)) $method = $conf['passcrypt'];
1036
1037    $pass = new PassHash();
1038    $call = 'hash_'.$method;
1039
1040    if(!method_exists($pass, $call)) {
1041        msg("Unsupported crypt method $method", -1);
1042        return false;
1043    }
1044
1045    return $pass->$call($clear, $salt);
1046}
1047
1048/**
1049 * Verifies a cleartext password against a crypted hash
1050 *
1051 * @author Andreas Gohr <andi@splitbrain.org>
1052 * @param  string $clear The clear text password
1053 * @param  string $crypt The hash to compare with
1054 * @return bool true if both match
1055 */
1056function auth_verifyPassword($clear, $crypt) {
1057    $pass = new PassHash();
1058    return $pass->verify_hash($clear, $crypt);
1059}
1060
1061/**
1062 * Set the authentication cookie and add user identification data to the session
1063 *
1064 * @param string  $user       username
1065 * @param string  $pass       encrypted password
1066 * @param bool    $sticky     whether or not the cookie will last beyond the session
1067 * @return bool
1068 */
1069function auth_setCookie($user, $pass, $sticky) {
1070    global $conf;
1071    /* @var auth_basic $auth */
1072    global $auth;
1073    global $USERINFO;
1074
1075    if(!$auth) return false;
1076    $USERINFO = $auth->getUserData($user);
1077
1078    // set cookie
1079    $cookie    = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
1080    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1081    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1082    if(version_compare(PHP_VERSION, '5.2.0', '>')) {
1083        setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
1084    } else {
1085        setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
1086    }
1087    // set session
1088    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1089    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1090    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1091    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1092    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1093
1094    return true;
1095}
1096
1097/**
1098 * Returns the user, (encrypted) password and sticky bit from cookie
1099 *
1100 * @returns array
1101 */
1102function auth_getCookie() {
1103    if(!isset($_COOKIE[DOKU_COOKIE])) {
1104        return array(null, null, null);
1105    }
1106    list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
1107    $sticky = (bool) $sticky;
1108    $pass   = base64_decode($pass);
1109    $user   = base64_decode($user);
1110    return array($user, $sticky, $pass);
1111}
1112
1113//Setup VIM: ex: et ts=2 :
1114