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