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