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