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