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