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