xref: /dokuwiki/inc/auth.php (revision 5aa52fafe8be8e728c0d2c9ff12c999e80766127)
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 * @return  bool             true on successful auth
111*/
112function auth_login($user,$pass,$sticky=false){
113  global $USERINFO;
114  global $conf;
115  global $lang;
116  global $auth;
117  $sticky ? $sticky = true : $sticky = false; //sanity check
118
119  if(!empty($user)){
120    //usual login
121    if ($auth->checkPass($user,$pass)){
122      // make logininfo globally available
123      $_SERVER['REMOTE_USER'] = $user;
124      $USERINFO = $auth->getUserData($user); //FIXME move all references to session
125
126      // set cookie
127      $pass   = PMA_blowfish_encrypt($pass,auth_cookiesalt());
128      $cookie = base64_encode("$user|$sticky|$pass");
129      if($sticky) $time = time()+60*60*24*365; //one year
130      setcookie(DOKU_COOKIE,$cookie,$time,'/');
131
132      // set session
133      $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
134      $_SESSION[DOKU_COOKIE]['auth']['pass'] = $pass;
135      $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
136      $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
137      return true;
138    }else{
139      //invalid credentials - log off
140      msg($lang['badlogin'],-1);
141      auth_logoff();
142      return false;
143    }
144  }else{
145    // read cookie information
146    $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
147    list($user,$sticky,$pass) = split('\|',$cookie,3);
148    // get session info
149    $session = $_SESSION[DOKU_COOKIE]['auth'];
150
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
163      $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
164      return auth_login($user,$pass,$sticky);
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
442  if (!isset($cache[$name][$skip_group])) {
443    if($skip_group && $name{0} =='@'){
444      $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
445                                                    "'%'.dechex(ord('\\1'))",substr($name,1));
446    }else{
447      $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
448                                                "'%'.dechex(ord('\\1'))",$name);
449    }
450  }
451
452  return $cache[$name][$skip_group];
453}
454
455/**
456 * Create a pronouncable password
457 *
458 * @author  Andreas Gohr <andi@splitbrain.org>
459 * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
460 *
461 * @return string  pronouncable password
462 */
463function auth_pwgen(){
464  $pw = '';
465  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
466  $v  = 'aeiou';              //vowels
467  $a  = $c.$v;                //both
468
469  //use two syllables...
470  for($i=0;$i < 2; $i++){
471    $pw .= $c[rand(0, strlen($c)-1)];
472    $pw .= $v[rand(0, strlen($v)-1)];
473    $pw .= $a[rand(0, strlen($a)-1)];
474  }
475  //... and add a nice number
476  $pw .= rand(10,99);
477
478  return $pw;
479}
480
481/**
482 * Sends a password to the given user
483 *
484 * @author  Andreas Gohr <andi@splitbrain.org>
485 *
486 * @return bool  true on success
487 */
488function auth_sendPassword($user,$password){
489  global $conf;
490  global $lang;
491  global $auth;
492
493  $hdrs  = '';
494  $userinfo = $auth->getUserData($user);
495
496  if(!$userinfo['mail']) return false;
497
498  $text = rawLocale('password');
499  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
500  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
501  $text = str_replace('@LOGIN@',$user,$text);
502  $text = str_replace('@PASSWORD@',$password,$text);
503  $text = str_replace('@TITLE@',$conf['title'],$text);
504
505  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
506                   $lang['regpwmail'],
507                   $text,
508                   $conf['mailfrom']);
509}
510
511/**
512 * Register a new user
513 *
514 * This registers a new user - Data is read directly from $_POST
515 *
516 * @author  Andreas Gohr <andi@splitbrain.org>
517 *
518 * @return bool  true on success, false on any error
519 */
520function register(){
521  global $lang;
522  global $conf;
523  global $auth;
524
525  if(!$_POST['save']) return false;
526  if(!$auth->canDo('addUser')) return false;
527
528  //clean username
529  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
530  $_POST['login'] = cleanID($_POST['login']);
531  //clean fullname and email
532  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
533  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
534
535  if( empty($_POST['login']) ||
536      empty($_POST['fullname']) ||
537      empty($_POST['email']) ){
538    msg($lang['regmissing'],-1);
539    return false;
540  }
541
542  if ($conf['autopasswd']) {
543    $pass = auth_pwgen();                // automatically generate password
544  } elseif (empty($_POST['pass']) ||
545            empty($_POST['passchk'])) {
546    msg($lang['regmissing'], -1);        // complain about missing passwords
547    return false;
548  } elseif ($_POST['pass'] != $_POST['passchk']) {
549    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
550    return false;
551  } else {
552    $pass = $_POST['pass'];              // accept checked and valid password
553  }
554
555  //check mail
556  if(!mail_isvalid($_POST['email'])){
557    msg($lang['regbadmail'],-1);
558    return false;
559  }
560
561  //okay try to create the user
562  if(!$auth->createUser($_POST['login'],$pass,$_POST['fullname'],$_POST['email'])){
563    msg($lang['reguexists'],-1);
564    return false;
565  }
566
567  // create substitutions for use in notification email
568  $substitutions = array(
569    'NEWUSER' => $_POST['login'],
570    'NEWNAME' => $_POST['fullname'],
571    'NEWEMAIL' => $_POST['email'],
572  );
573
574  if (!$conf['autopasswd']) {
575    msg($lang['regsuccess2'],1);
576    notify('', 'register', '', $_POST['login'], false, $substitutions);
577    return true;
578  }
579
580  // autogenerated password? then send him the password
581  if (auth_sendPassword($_POST['login'],$pass)){
582    msg($lang['regsuccess'],1);
583    notify('', 'register', '', $_POST['login'], false, $substitutions);
584    return true;
585  }else{
586    msg($lang['regmailfail'],-1);
587    return false;
588  }
589}
590
591/**
592 * Update user profile
593 *
594 * @author    Christopher Smith <chris@jalakai.co.uk>
595 */
596function updateprofile() {
597  global $conf;
598  global $INFO;
599  global $lang;
600  global $auth;
601
602  if(empty($_POST['save'])) return false;
603
604  // should not be able to get here without Profile being possible...
605  if(!$auth->canDo('Profile')) {
606    msg($lang['profna'],-1);
607    return false;
608  }
609
610  if ($_POST['newpass'] != $_POST['passchk']) {
611    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
612    return false;
613  }
614
615  //clean fullname and email
616  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
617  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
618
619  if (empty($_POST['fullname']) || empty($_POST['email'])) {
620    msg($lang['profnoempty'],-1);
621    return false;
622  }
623
624  if (!mail_isvalid($_POST['email'])){
625    msg($lang['regbadmail'],-1);
626    return false;
627  }
628
629  if ($_POST['fullname'] != $INFO['userinfo']['name']) $changes['name'] = $_POST['fullname'];
630  if ($_POST['email']    != $INFO['userinfo']['mail']) $changes['mail'] = $_POST['email'];
631  if (!empty($_POST['newpass']))  $changes['pass'] = $_POST['newpass'];
632
633  if (!count($changes)) {
634    msg($lang['profnochange'], -1);
635    return false;
636  }
637
638  if ($conf['profileconfirm']) {
639      if (!auth_verifyPassword($_POST['oldpass'],$INFO['userinfo']['pass'])) {
640      msg($lang['badlogin'],-1);
641      return false;
642    }
643  }
644
645  return $auth->modifyUser($_SERVER['REMOTE_USER'], $changes);
646}
647
648/**
649 * Send a  new password
650 *
651 * This function handles both phases of the password reset:
652 *
653 *   - handling the first request of password reset
654 *   - validating the password reset auth token
655 *
656 * @author Benoit Chesneau <benoit@bchesneau.info>
657 * @author Chris Smith <chris@jalakai.co.uk>
658 * @author Andreas Gohr <andi@splitbrain.org>
659 *
660 * @return bool true on success, false on any error
661*/
662function act_resendpwd(){
663    global $lang;
664    global $conf;
665    global $auth;
666
667    if(!actionOK('resendpwd')) return false;
668
669    // should not be able to get here without modPass being possible...
670    if(!$auth->canDo('modPass')) {
671        msg($lang['resendna'],-1);
672        return false;
673    }
674
675    $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
676
677    if($token){
678        // we're in token phase
679
680        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
681        if(!@file_exists($tfile)){
682            msg($lang['resendpwdbadauth'],-1);
683            return false;
684        }
685        $user = io_readfile($tfile);
686        @unlink($tfile);
687        $userinfo = $auth->getUserData($user);
688        if(!$userinfo['mail']) {
689            msg($lang['resendpwdnouser'], -1);
690            return false;
691        }
692
693        $pass = auth_pwgen();
694        if (!$auth->modifyUser($user,array('pass' => $pass))) {
695            msg('error modifying user data',-1);
696            return false;
697        }
698
699        if (auth_sendPassword($user,$pass)) {
700            msg($lang['resendpwdsuccess'],1);
701        } else {
702            msg($lang['regmailfail'],-1);
703        }
704        return true;
705
706    } else {
707        // we're in request phase
708
709        if(!$_POST['save']) return false;
710
711        if (empty($_POST['login'])) {
712            msg($lang['resendpwdmissing'], -1);
713            return false;
714        } else {
715            $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
716            $user = cleanID($_POST['login']);
717        }
718
719        $userinfo = $auth->getUserData($user);
720        if(!$userinfo['mail']) {
721            msg($lang['resendpwdnouser'], -1);
722            return false;
723        }
724
725        // generate auth token
726        $token = md5(auth_cookiesalt().$user); //secret but user based
727        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
728        $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
729
730        io_saveFile($tfile,$user);
731
732        $text = rawLocale('pwconfirm');
733        $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
734        $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
735        $text = str_replace('@LOGIN@',$user,$text);
736        $text = str_replace('@TITLE@',$conf['title'],$text);
737        $text = str_replace('@CONFIRM@',$url,$text);
738
739        if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
740                     $lang['regpwmail'],
741                     $text,
742                     $conf['mailfrom'])){
743            msg($lang['resendpwdconfirm'],1);
744        }else{
745            msg($lang['regmailfail'],-1);
746        }
747        return true;
748    }
749
750    return false; // never reached
751}
752
753/**
754 * Uses a regular expresion to check if a given mail address is valid
755 *
756 * May not be completly RFC conform!
757 *
758 * @link    http://www.webmasterworld.com/forum88/135.htm
759 *
760 * @param   string $email the address to check
761 * @return  bool          true if address is valid
762 */
763function isvalidemail($email){
764  return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email);
765}
766
767/**
768 * Encrypts a password using the given method and salt
769 *
770 * If the selected method needs a salt and none was given, a random one
771 * is chosen.
772 *
773 * The following methods are understood:
774 *
775 *   smd5  - Salted MD5 hashing
776 *   md5   - Simple MD5 hashing
777 *   sha1  - SHA1 hashing
778 *   ssha  - Salted SHA1 hashing
779 *   crypt - Unix crypt
780 *   mysql - MySQL password (old method)
781 *   my411 - MySQL 4.1.1 password
782 *
783 * @author  Andreas Gohr <andi@splitbrain.org>
784 * @return  string  The crypted password
785 */
786function auth_cryptPassword($clear,$method='',$salt=''){
787  global $conf;
788  if(empty($method)) $method = $conf['passcrypt'];
789
790  //prepare a salt
791  if(empty($salt)) $salt = md5(uniqid(rand(), true));
792
793  switch(strtolower($method)){
794    case 'smd5':
795        return crypt($clear,'$1$'.substr($salt,0,8).'$');
796    case 'md5':
797      return md5($clear);
798    case 'sha1':
799      return sha1($clear);
800    case 'ssha':
801      $salt=substr($salt,0,4);
802      return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
803    case 'crypt':
804      return crypt($clear,substr($salt,0,2));
805    case 'mysql':
806      //from http://www.php.net/mysql comment by <soren at byu dot edu>
807      $nr=0x50305735;
808      $nr2=0x12345671;
809      $add=7;
810      $charArr = preg_split("//", $clear);
811      foreach ($charArr as $char) {
812        if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
813        $charVal = ord($char);
814        $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
815        $nr2 += ($nr2 << 8) ^ $nr;
816        $add += $charVal;
817      }
818      return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
819    case 'my411':
820      return '*'.sha1(pack("H*", sha1($clear)));
821    default:
822      msg("Unsupported crypt method $method",-1);
823  }
824}
825
826/**
827 * Verifies a cleartext password against a crypted hash
828 *
829 * The method and salt used for the crypted hash is determined automatically
830 * then the clear text password is crypted using the same method. If both hashs
831 * match true is is returned else false
832 *
833 * @author  Andreas Gohr <andi@splitbrain.org>
834 * @return  bool
835 */
836function auth_verifyPassword($clear,$crypt){
837  $method='';
838  $salt='';
839
840  //determine the used method and salt
841  $len = strlen($crypt);
842  if(substr($crypt,0,3) == '$1$'){
843    $method = 'smd5';
844    $salt   = substr($crypt,3,8);
845  }elseif(substr($crypt,0,6) == '{SSHA}'){
846    $method = 'ssha';
847    $salt   = substr(base64_decode(substr($crypt, 6)),20);
848  }elseif($len == 32){
849    $method = 'md5';
850  }elseif($len == 40){
851    $method = 'sha1';
852  }elseif($len == 16){
853    $method = 'mysql';
854  }elseif($len == 41 && $crypt[0] == '*'){
855    $method = 'my411';
856  }else{
857    $method = 'crypt';
858    $salt   = substr($crypt,0,2);
859  }
860
861  //crypt and compare
862  if(auth_cryptPassword($clear,$method,$salt) === $crypt){
863    return true;
864  }
865  return false;
866}
867
868//Setup VIM: ex: et ts=2 enc=utf-8 :
869