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