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