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