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