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