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