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