xref: /dokuwiki/inc/auth.php (revision d0f8d50b16073494dc8ccc16905d445467e648cd)
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 $conf;
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    if(isset($_SERVER['REMOTE_USER']) && $conf['use_wildcards']){
135        $len = count($acl);
136        for($i = 0; $i < $len; $i++) {
137            if($acl[$i]{0} == '#') continue;
138            list($id,$rest) = preg_split('/\s+/',$acl[$i],2);
139            if(strstr($acl[$i], '%GROUP%')){
140                foreach($USERINFO['grps'] as $grp){
141                    $nid   = str_replace('%GROUP%',cleanID($grp),$id);
142                    $nrest = str_replace('%GROUP%',auth_nameencode($grp),$rest);
143                    $acl[] = "$nid\t$nrest";
144                }
145            }
146            $id   = str_replace('%USER%',cleanID($_SERVER['REMOTE_USER']),$id);
147            $rest = str_replace('%USER%',auth_nameencode($_SERVER['REMOTE_USER']),$rest);
148            $acl[$i] = "$id\t$rest";
149        }
150    }
151    return $acl;
152}
153
154/**
155 * Event hook callback for AUTH_LOGIN_CHECK
156 *
157 * @param $evdata
158 * @return bool
159 */
160function auth_login_wrapper($evdata) {
161    return auth_login(
162        $evdata['user'],
163        $evdata['password'],
164        $evdata['sticky'],
165        $evdata['silent']
166    );
167}
168
169/**
170 * This tries to login the user based on the sent auth credentials
171 *
172 * The authentication works like this: if a username was given
173 * a new login is assumed and user/password are checked. If they
174 * are correct the password is encrypted with blowfish and stored
175 * together with the username in a cookie - the same info is stored
176 * in the session, too. Additonally a browserID is stored in the
177 * session.
178 *
179 * If no username was given the cookie is checked: if the username,
180 * crypted password and browserID match between session and cookie
181 * no further testing is done and the user is accepted
182 *
183 * If a cookie was found but no session info was availabe the
184 * blowfish encrypted password from the cookie is decrypted and
185 * together with username rechecked by calling this function again.
186 *
187 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
188 * are set.
189 *
190 * @author  Andreas Gohr <andi@splitbrain.org>
191 *
192 * @param   string  $user    Username
193 * @param   string  $pass    Cleartext Password
194 * @param   bool    $sticky  Cookie should not expire
195 * @param   bool    $silent  Don't show error on bad auth
196 * @return  bool             true on successful auth
197 */
198function auth_login($user, $pass, $sticky = false, $silent = false) {
199    global $USERINFO;
200    global $conf;
201    global $lang;
202    /* @var auth_basic $auth */
203    global $auth;
204
205    $sticky ? $sticky = true : $sticky = false; //sanity check
206
207    if(!$auth) return false;
208
209    if(!empty($user)) {
210        //usual login
211        if($auth->checkPass($user, $pass)) {
212            // make logininfo globally available
213            $_SERVER['REMOTE_USER'] = $user;
214            $secret                 = auth_cookiesalt(!$sticky); //bind non-sticky to session
215            auth_setCookie($user, PMA_blowfish_encrypt($pass, $secret), $sticky);
216            return true;
217        } else {
218            //invalid credentials - log off
219            if(!$silent) msg($lang['badlogin'], -1);
220            auth_logoff();
221            return false;
222        }
223    } else {
224        // read cookie information
225        list($user, $sticky, $pass) = auth_getCookie();
226        if($user && $pass) {
227            // we got a cookie - see if we can trust it
228
229            // get session info
230            $session = $_SESSION[DOKU_COOKIE]['auth'];
231            if(isset($session) &&
232                $auth->useSessionCache($user) &&
233                ($session['time'] >= time() - $conf['auth_security_timeout']) &&
234                ($session['user'] == $user) &&
235                ($session['pass'] == sha1($pass)) && //still crypted
236                ($session['buid'] == auth_browseruid())
237            ) {
238
239                // he has session, cookie and browser right - let him in
240                $_SERVER['REMOTE_USER'] = $user;
241                $USERINFO               = $session['info']; //FIXME move all references to session
242                return true;
243            }
244            // no we don't trust it yet - recheck pass but silent
245            $secret = auth_cookiesalt(!$sticky); //bind non-sticky to session
246            $pass   = PMA_blowfish_decrypt($pass, $secret);
247            return auth_login($user, $pass, $sticky, true);
248        }
249    }
250    //just to be sure
251    auth_logoff(true);
252    return false;
253}
254
255/**
256 * Checks if a given authentication token was stored in the session
257 *
258 * Will setup authentication data using data from the session if the
259 * token is correct. Will exit with a 401 Status if not.
260 *
261 * @author Andreas Gohr <andi@splitbrain.org>
262 * @param  string $token The authentication token
263 * @return boolean true (or will exit on failure)
264 */
265function auth_validateToken($token) {
266    if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']) {
267        // bad token
268        header("HTTP/1.0 401 Unauthorized");
269        print 'Invalid auth token - maybe the session timed out';
270        unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
271        exit;
272    }
273    // still here? trust the session data
274    global $USERINFO;
275    $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
276    $USERINFO               = $_SESSION[DOKU_COOKIE]['auth']['info'];
277    return true;
278}
279
280/**
281 * Create an auth token and store it in the session
282 *
283 * NOTE: this is completely unrelated to the getSecurityToken() function
284 *
285 * @author Andreas Gohr <andi@splitbrain.org>
286 * @return string The auth token
287 */
288function auth_createToken() {
289    $token = md5(mt_rand());
290    @session_start(); // reopen the session if needed
291    $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
292    session_write_close();
293    return $token;
294}
295
296/**
297 * Builds a pseudo UID from browser and IP data
298 *
299 * This is neither unique nor unfakable - still it adds some
300 * security. Using the first part of the IP makes sure
301 * proxy farms like AOLs are stil okay.
302 *
303 * @author  Andreas Gohr <andi@splitbrain.org>
304 *
305 * @return  string  a MD5 sum of various browser headers
306 */
307function auth_browseruid() {
308    $ip  = clientIP(true);
309    $uid = '';
310    $uid .= $_SERVER['HTTP_USER_AGENT'];
311    $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
312    $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
313    $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
314    $uid .= substr($ip, 0, strpos($ip, '.'));
315    return md5($uid);
316}
317
318/**
319 * Creates a random key to encrypt the password in cookies
320 *
321 * This function tries to read the password for encrypting
322 * cookies from $conf['metadir'].'/_htcookiesalt'
323 * if no such file is found a random key is created and
324 * and stored in this file.
325 *
326 * @author  Andreas Gohr <andi@splitbrain.org>
327 * @param   bool $addsession if true, the sessionid is added to the salt
328 * @return  string
329 */
330function auth_cookiesalt($addsession = false) {
331    global $conf;
332    $file = $conf['metadir'].'/_htcookiesalt';
333    $salt = io_readFile($file);
334    if(empty($salt)) {
335        $salt = uniqid(rand(), true);
336        io_saveFile($file, $salt);
337    }
338    if($addsession) {
339        $salt .= session_id();
340    }
341    return $salt;
342}
343
344/**
345 * Log out the current user
346 *
347 * This clears all authentication data and thus log the user
348 * off. It also clears session data.
349 *
350 * @author  Andreas Gohr <andi@splitbrain.org>
351 * @param bool $keepbc - when true, the breadcrumb data is not cleared
352 */
353function auth_logoff($keepbc = false) {
354    global $conf;
355    global $USERINFO;
356    /* @var auth_basic $auth */
357    global $auth;
358
359    // make sure the session is writable (it usually is)
360    @session_start();
361
362    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
363        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
364    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
365        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
366    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
367        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
368    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
369        unset($_SESSION[DOKU_COOKIE]['bc']);
370    if(isset($_SERVER['REMOTE_USER']))
371        unset($_SERVER['REMOTE_USER']);
372    $USERINFO = null; //FIXME
373
374    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
375    if(version_compare(PHP_VERSION, '5.2.0', '>')) {
376        setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
377    } else {
378        setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
379    }
380
381    if($auth) $auth->logOff();
382}
383
384/**
385 * Check if a user is a manager
386 *
387 * Should usually be called without any parameters to check the current
388 * user.
389 *
390 * The info is available through $INFO['ismanager'], too
391 *
392 * @author Andreas Gohr <andi@splitbrain.org>
393 * @see    auth_isadmin
394 * @param  string $user       Username
395 * @param  array  $groups     List of groups the user is in
396 * @param  bool   $adminonly  when true checks if user is admin
397 * @return bool
398 */
399function auth_ismanager($user = null, $groups = null, $adminonly = false) {
400    global $conf;
401    global $USERINFO;
402    /* @var auth_basic $auth */
403    global $auth;
404
405    if(!$auth) return false;
406    if(is_null($user)) {
407        if(!isset($_SERVER['REMOTE_USER'])) {
408            return false;
409        } else {
410            $user = $_SERVER['REMOTE_USER'];
411        }
412    }
413    if(is_null($groups)) {
414        $groups = (array) $USERINFO['grps'];
415    }
416
417    // check superuser match
418    if(auth_isMember($conf['superuser'], $user, $groups)) return true;
419    if($adminonly) return false;
420    // check managers
421    if(auth_isMember($conf['manager'], $user, $groups)) return true;
422
423    return false;
424}
425
426/**
427 * Check if a user is admin
428 *
429 * Alias to auth_ismanager with adminonly=true
430 *
431 * The info is available through $INFO['isadmin'], too
432 *
433 * @author Andreas Gohr <andi@splitbrain.org>
434 * @see auth_ismanager()
435 * @param  string $user       Username
436 * @param  array  $groups     List of groups the user is in
437 * @return bool
438 */
439function auth_isadmin($user = null, $groups = null) {
440    return auth_ismanager($user, $groups, true);
441}
442
443/**
444 * Match a user and his groups against a comma separated list of
445 * users and groups to determine membership status
446 *
447 * Note: all input should NOT be nameencoded.
448 *
449 * @param $memberlist string commaseparated list of allowed users and groups
450 * @param $user       string user to match against
451 * @param $groups     array  groups the user is member of
452 * @return bool       true for membership acknowledged
453 */
454function auth_isMember($memberlist, $user, array $groups) {
455    /* @var auth_basic $auth */
456    global $auth;
457    if(!$auth) return false;
458
459    // clean user and groups
460    if(!$auth->isCaseSensitive()) {
461        $user   = utf8_strtolower($user);
462        $groups = array_map('utf8_strtolower', $groups);
463    }
464    $user   = $auth->cleanUser($user);
465    $groups = array_map(array($auth, 'cleanGroup'), $groups);
466
467    // extract the memberlist
468    $members = explode(',', $memberlist);
469    $members = array_map('trim', $members);
470    $members = array_unique($members);
471    $members = array_filter($members);
472
473    // compare cleaned values
474    foreach($members as $member) {
475        if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member);
476        if($member[0] == '@') {
477            $member = $auth->cleanGroup(substr($member, 1));
478            if(in_array($member, $groups)) return true;
479        } else {
480            $member = $auth->cleanUser($member);
481            if($member == $user) return true;
482        }
483    }
484
485    // still here? not a member!
486    return false;
487}
488
489/**
490 * Convinience function for auth_aclcheck()
491 *
492 * This checks the permissions for the current user
493 *
494 * @author  Andreas Gohr <andi@splitbrain.org>
495 *
496 * @param  string  $id  page ID (needs to be resolved and cleaned)
497 * @return int          permission level
498 */
499function auth_quickaclcheck($id) {
500    global $conf;
501    global $USERINFO;
502    # if no ACL is used always return upload rights
503    if(!$conf['useacl']) return AUTH_UPLOAD;
504    return auth_aclcheck($id, $_SERVER['REMOTE_USER'], $USERINFO['grps']);
505}
506
507/**
508 * Returns the maximum rights a user has for
509 * the given ID or its namespace
510 *
511 * @author  Andreas Gohr <andi@splitbrain.org>
512 *
513 * @param  string       $id     page ID (needs to be resolved and cleaned)
514 * @param  string       $user   Username
515 * @param  array|null   $groups Array of groups the user is in
516 * @return int             permission level
517 */
518function auth_aclcheck($id, $user, $groups) {
519    global $conf;
520    global $AUTH_ACL;
521    /* @var auth_basic $auth */
522    global $auth;
523
524    // if no ACL is used always return upload rights
525    if(!$conf['useacl']) return AUTH_UPLOAD;
526    if(!$auth) return AUTH_NONE;
527
528    //make sure groups is an array
529    if(!is_array($groups)) $groups = array();
530
531    //if user is superuser or in superusergroup return 255 (acl_admin)
532    if(auth_isadmin($user, $groups)) {
533        return AUTH_ADMIN;
534    }
535
536    $ci = '';
537    if(!$auth->isCaseSensitive()) $ci = 'ui';
538
539    $user   = $auth->cleanUser($user);
540    $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
541    $user   = auth_nameencode($user);
542
543    //prepend groups with @ and nameencode
544    $cnt = count($groups);
545    for($i = 0; $i < $cnt; $i++) {
546        $groups[$i] = '@'.auth_nameencode($groups[$i]);
547    }
548
549    $ns   = getNS($id);
550    $perm = -1;
551
552    if($user || count($groups)) {
553        //add ALL group
554        $groups[] = '@ALL';
555        //add User
556        if($user) $groups[] = $user;
557    } else {
558        $groups[] = '@ALL';
559    }
560
561    //check exact match first
562    $matches = preg_grep('/^'.preg_quote($id, '/').'\s+(\S+)\s+/'.$ci, $AUTH_ACL);
563    if(count($matches)) {
564        foreach($matches as $match) {
565            $match = preg_replace('/#.*$/', '', $match); //ignore comments
566            $acl   = preg_split('/\s+/', $match);
567            if(!in_array($acl[1], $groups)) {
568                continue;
569            }
570            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
571            if($acl[2] > $perm) {
572                $perm = $acl[2];
573            }
574        }
575        if($perm > -1) {
576            //we had a match - return it
577            return $perm;
578        }
579    }
580
581    //still here? do the namespace checks
582    if($ns) {
583        $path = $ns.':*';
584    } else {
585        $path = '*'; //root document
586    }
587
588    do {
589        $matches = preg_grep('/^'.preg_quote($path, '/').'\s+(\S+)\s+/'.$ci, $AUTH_ACL);
590        if(count($matches)) {
591            foreach($matches as $match) {
592                $match = preg_replace('/#.*$/', '', $match); //ignore comments
593                $acl   = preg_split('/\s+/', $match);
594                if(!in_array($acl[1], $groups)) {
595                    continue;
596                }
597                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
598                if($acl[2] > $perm) {
599                    $perm = $acl[2];
600                }
601            }
602            //we had a match - return it
603            if($perm != -1) {
604                return $perm;
605            }
606        }
607        //get next higher namespace
608        $ns = getNS($ns);
609
610        if($path != '*') {
611            $path = $ns.':*';
612            if($path == ':*') $path = '*';
613        } else {
614            //we did this already
615            //looks like there is something wrong with the ACL
616            //break here
617            msg('No ACL setup yet! Denying access to everyone.');
618            return AUTH_NONE;
619        }
620    } while(1); //this should never loop endless
621    return AUTH_NONE;
622}
623
624/**
625 * Encode ASCII special chars
626 *
627 * Some auth backends allow special chars in their user and groupnames
628 * The special chars are encoded with this function. Only ASCII chars
629 * are encoded UTF-8 multibyte are left as is (different from usual
630 * urlencoding!).
631 *
632 * Decoding can be done with rawurldecode
633 *
634 * @author Andreas Gohr <gohr@cosmocode.de>
635 * @see rawurldecode()
636 */
637function auth_nameencode($name, $skip_group = false) {
638    global $cache_authname;
639    $cache =& $cache_authname;
640    $name  = (string) $name;
641
642    // never encode wildcard FS#1955
643    if($name == '%USER%') return $name;
644    if($name == '%GROUP%') return $name;
645
646    if(!isset($cache[$name][$skip_group])) {
647        if($skip_group && $name{0} == '@') {
648            $cache[$name][$skip_group] = '@'.preg_replace(
649                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
650                "'%'.dechex(ord(substr('\\1',-1)))", substr($name, 1)
651            );
652        } else {
653            $cache[$name][$skip_group] = preg_replace(
654                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
655                "'%'.dechex(ord(substr('\\1',-1)))", $name
656            );
657        }
658    }
659
660    return $cache[$name][$skip_group];
661}
662
663/**
664 * Create a pronouncable password
665 *
666 * @author  Andreas Gohr <andi@splitbrain.org>
667 * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
668 *
669 * @return string  pronouncable password
670 */
671function auth_pwgen() {
672    $pw = '';
673    $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
674    $v  = 'aeiou'; //vowels
675    $a  = $c.$v; //both
676
677    //use two syllables...
678    for($i = 0; $i < 2; $i++) {
679        $pw .= $c[rand(0, strlen($c) - 1)];
680        $pw .= $v[rand(0, strlen($v) - 1)];
681        $pw .= $a[rand(0, strlen($a) - 1)];
682    }
683    //... and add a nice number
684    $pw .= rand(10, 99);
685
686    return $pw;
687}
688
689/**
690 * Sends a password to the given user
691 *
692 * @author  Andreas Gohr <andi@splitbrain.org>
693 * @param string $user Login name of the user
694 * @param string $password The new password in clear text
695 * @return bool  true on success
696 */
697function auth_sendPassword($user, $password) {
698    global $lang;
699    /* @var auth_basic $auth */
700    global $auth;
701    if(!$auth) return false;
702
703    $user     = $auth->cleanUser($user);
704    $userinfo = $auth->getUserData($user);
705
706    if(!$userinfo['mail']) return false;
707
708    $text = rawLocale('password');
709    $trep = array(
710        'FULLNAME' => $userinfo['name'],
711        'LOGIN'    => $user,
712        'PASSWORD' => $password
713    );
714
715    $mail = new Mailer();
716    $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
717    $mail->subject($lang['regpwmail']);
718    $mail->setBody($text, $trep);
719    return $mail->send();
720}
721
722/**
723 * Register a new user
724 *
725 * This registers a new user - Data is read directly from $_POST
726 *
727 * @author  Andreas Gohr <andi@splitbrain.org>
728 * @return bool  true on success, false on any error
729 */
730function register() {
731    global $lang;
732    global $conf;
733    /* @var auth_basic $auth */
734    global $auth;
735
736    if(!$_POST['save']) return false;
737    if(!actionOK('register')) return false;
738
739    //clean username
740    $_POST['login'] = trim($auth->cleanUser($_POST['login']));
741
742    //clean fullname and email
743    $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $_POST['fullname']));
744    $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $_POST['email']));
745
746    if(empty($_POST['login']) ||
747        empty($_POST['fullname']) ||
748        empty($_POST['email'])
749    ) {
750        msg($lang['regmissing'], -1);
751        return false;
752    }
753
754    if($conf['autopasswd']) {
755        $pass = auth_pwgen(); // automatically generate password
756    } elseif(empty($_POST['pass']) ||
757        empty($_POST['passchk'])
758    ) {
759        msg($lang['regmissing'], -1); // complain about missing passwords
760        return false;
761    } elseif($_POST['pass'] != $_POST['passchk']) {
762        msg($lang['regbadpass'], -1); // complain about misspelled passwords
763        return false;
764    } else {
765        $pass = $_POST['pass']; // accept checked and valid password
766    }
767
768    //check mail
769    if(!mail_isvalid($_POST['email'])) {
770        msg($lang['regbadmail'], -1);
771        return false;
772    }
773
774    //okay try to create the user
775    if(!$auth->triggerUserMod('create', array($_POST['login'], $pass, $_POST['fullname'], $_POST['email']))) {
776        msg($lang['reguexists'], -1);
777        return false;
778    }
779
780    // create substitutions for use in notification email
781    $substitutions = array(
782        'NEWUSER'  => $_POST['login'],
783        'NEWNAME'  => $_POST['fullname'],
784        'NEWEMAIL' => $_POST['email'],
785    );
786
787    if(!$conf['autopasswd']) {
788        msg($lang['regsuccess2'], 1);
789        notify('', 'register', '', $_POST['login'], false, $substitutions);
790        return true;
791    }
792
793    // autogenerated password? then send him the password
794    if(auth_sendPassword($_POST['login'], $pass)) {
795        msg($lang['regsuccess'], 1);
796        notify('', 'register', '', $_POST['login'], false, $substitutions);
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