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