xref: /dokuwiki/inc/auth.php (revision 7048cf73957a2c9e949fd991b2e851a11dffc923)
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  //prepend groups with @ and nameencode
281  $cnt = count($groups);
282  for($i=0; $i<$cnt; $i++){
283    $groups[$i] = '@'.auth_nameencode($groups[$i]);
284  }
285
286  // check groups against superuser and manager
287  if(in_array(auth_nameencode($conf['superuser'],true), $groups)) return true;
288  if(!$adminonly){
289    if(in_array(auth_nameencode($conf['manager'],true), $groups)) return true;
290  }
291  return false;
292}
293
294/**
295 * Check if a user is admin
296 *
297 * Alias to auth_ismanager with adminonly=true
298 *
299 * The info is available through $INFO['isadmin'], too
300 *
301 * @author Andreas Gohr <andi@splitbrain.org>
302 * @see auth_ismanager
303 */
304function auth_isadmin($user=null,$groups=null){
305  return auth_ismanager($user,$groups,true);
306}
307
308/**
309 * Convinience function for auth_aclcheck()
310 *
311 * This checks the permissions for the current user
312 *
313 * @author  Andreas Gohr <andi@splitbrain.org>
314 *
315 * @param  string  $id  page ID
316 * @return int          permission level
317 */
318function auth_quickaclcheck($id){
319  global $conf;
320  global $USERINFO;
321  # if no ACL is used always return upload rights
322  if(!$conf['useacl']) return AUTH_UPLOAD;
323  return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
324}
325
326/**
327 * Returns the maximum rights a user has for
328 * the given ID or its namespace
329 *
330 * @author  Andreas Gohr <andi@splitbrain.org>
331 *
332 * @param  string  $id     page ID
333 * @param  string  $user   Username
334 * @param  array   $groups Array of groups the user is in
335 * @return int             permission level
336 */
337function auth_aclcheck($id,$user,$groups){
338  global $conf;
339  global $AUTH_ACL;
340
341  # if no ACL is used always return upload rights
342  if(!$conf['useacl']) return AUTH_UPLOAD;
343
344  $user = auth_nameencode($user);
345
346  //if user is superuser return 255 (acl_admin)
347  if(auth_nameencode($conf['superuser']) == $user) { return AUTH_ADMIN; }
348
349  //make sure groups is an array
350  if(!is_array($groups)) $groups = array();
351
352  //prepend groups with @ and nameencode
353  $cnt = count($groups);
354  for($i=0; $i<$cnt; $i++){
355    $groups[$i] = '@'.auth_nameencode($groups[$i]);
356  }
357  //if user is in superuser group return 255 (acl_admin)
358  if(in_array(auth_nameencode($conf['superuser'],true), $groups)) { return AUTH_ADMIN; }
359
360  $ns    = getNS($id);
361  $perm  = -1;
362
363  if($user){
364    //add ALL group
365    $groups[] = '@ALL';
366    //add User
367    $groups[] = $user;
368    //build regexp
369    $regexp   = join('|',$groups);
370  }else{
371    $regexp = '@ALL';
372  }
373
374  //check exact match first
375  $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/',$AUTH_ACL);
376  if(count($matches)){
377    foreach($matches as $match){
378      $match = preg_replace('/#.*$/','',$match); //ignore comments
379      $acl   = preg_split('/\s+/',$match);
380      if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
381      if($acl[2] > $perm){
382        $perm = $acl[2];
383      }
384    }
385    if($perm > -1){
386      //we had a match - return it
387      return $perm;
388    }
389  }
390
391  //still here? do the namespace checks
392  if($ns){
393    $path = $ns.':\*';
394  }else{
395    $path = '\*'; //root document
396  }
397
398  do{
399    $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
400    if(count($matches)){
401      foreach($matches as $match){
402        $match = preg_replace('/#.*$/','',$match); //ignore comments
403        $acl   = preg_split('/\s+/',$match);
404        if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
405        if($acl[2] > $perm){
406          $perm = $acl[2];
407        }
408      }
409      //we had a match - return it
410      return $perm;
411    }
412
413    //get next higher namespace
414    $ns   = getNS($ns);
415
416    if($path != '\*'){
417      $path = $ns.':\*';
418      if($path == ':\*') $path = '\*';
419    }else{
420      //we did this already
421      //looks like there is something wrong with the ACL
422      //break here
423      msg('No ACL setup yet! Denying access to everyone.');
424      return AUTH_NONE;
425    }
426  }while(1); //this should never loop endless
427
428  //still here? return no permissions
429  return AUTH_NONE;
430}
431
432/**
433 * Encode ASCII special chars
434 *
435 * Some auth backends allow special chars in their user and groupnames
436 * The special chars are encoded with this function. Only ASCII chars
437 * are encoded UTF-8 multibyte are left as is (different from usual
438 * urlencoding!).
439 *
440 * Decoding can be done with rawurldecode
441 *
442 * @author Andreas Gohr <gohr@cosmocode.de>
443 * @see rawurldecode()
444 */
445function auth_nameencode($name,$skip_group=false){
446  global $cache_authname;
447  $cache =& $cache_authname;
448  $name  = (string) $name;
449
450  if (!isset($cache[$name][$skip_group])) {
451    if($skip_group && $name{0} =='@'){
452      $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
453                                                    "'%'.dechex(ord('\\1'))",substr($name,1));
454    }else{
455      $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
456                                                "'%'.dechex(ord('\\1'))",$name);
457    }
458  }
459
460  return $cache[$name][$skip_group];
461}
462
463/**
464 * Create a pronouncable password
465 *
466 * @author  Andreas Gohr <andi@splitbrain.org>
467 * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
468 *
469 * @return string  pronouncable password
470 */
471function auth_pwgen(){
472  $pw = '';
473  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
474  $v  = 'aeiou';              //vowels
475  $a  = $c.$v;                //both
476
477  //use two syllables...
478  for($i=0;$i < 2; $i++){
479    $pw .= $c[rand(0, strlen($c)-1)];
480    $pw .= $v[rand(0, strlen($v)-1)];
481    $pw .= $a[rand(0, strlen($a)-1)];
482  }
483  //... and add a nice number
484  $pw .= rand(10,99);
485
486  return $pw;
487}
488
489/**
490 * Sends a password to the given user
491 *
492 * @author  Andreas Gohr <andi@splitbrain.org>
493 *
494 * @return bool  true on success
495 */
496function auth_sendPassword($user,$password){
497  global $conf;
498  global $lang;
499  global $auth;
500
501  $hdrs  = '';
502  $userinfo = $auth->getUserData($user);
503
504  if(!$userinfo['mail']) return false;
505
506  $text = rawLocale('password');
507  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
508  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
509  $text = str_replace('@LOGIN@',$user,$text);
510  $text = str_replace('@PASSWORD@',$password,$text);
511  $text = str_replace('@TITLE@',$conf['title'],$text);
512
513  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
514                   $lang['regpwmail'],
515                   $text,
516                   $conf['mailfrom']);
517}
518
519/**
520 * Register a new user
521 *
522 * This registers a new user - Data is read directly from $_POST
523 *
524 * @author  Andreas Gohr <andi@splitbrain.org>
525 *
526 * @return bool  true on success, false on any error
527 */
528function register(){
529  global $lang;
530  global $conf;
531  global $auth;
532
533  if(!$_POST['save']) return false;
534  if(!$auth->canDo('addUser')) return false;
535
536  //clean username
537  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
538  $_POST['login'] = cleanID($_POST['login']);
539  //clean fullname and email
540  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
541  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
542
543  if( empty($_POST['login']) ||
544      empty($_POST['fullname']) ||
545      empty($_POST['email']) ){
546    msg($lang['regmissing'],-1);
547    return false;
548  }
549
550  if ($conf['autopasswd']) {
551    $pass = auth_pwgen();                // automatically generate password
552  } elseif (empty($_POST['pass']) ||
553            empty($_POST['passchk'])) {
554    msg($lang['regmissing'], -1);        // complain about missing passwords
555    return false;
556  } elseif ($_POST['pass'] != $_POST['passchk']) {
557    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
558    return false;
559  } else {
560    $pass = $_POST['pass'];              // accept checked and valid password
561  }
562
563  //check mail
564  if(!mail_isvalid($_POST['email'])){
565    msg($lang['regbadmail'],-1);
566    return false;
567  }
568
569  //okay try to create the user
570  if(!$auth->createUser($_POST['login'],$pass,$_POST['fullname'],$_POST['email'])){
571    msg($lang['reguexists'],-1);
572    return false;
573  }
574
575  // create substitutions for use in notification email
576  $substitutions = array(
577    'NEWUSER' => $_POST['login'],
578    'NEWNAME' => $_POST['fullname'],
579    'NEWEMAIL' => $_POST['email'],
580  );
581
582  if (!$conf['autopasswd']) {
583    msg($lang['regsuccess2'],1);
584    notify('', 'register', '', $_POST['login'], false, $substitutions);
585    return true;
586  }
587
588  // autogenerated password? then send him the password
589  if (auth_sendPassword($_POST['login'],$pass)){
590    msg($lang['regsuccess'],1);
591    notify('', 'register', '', $_POST['login'], false, $substitutions);
592    return true;
593  }else{
594    msg($lang['regmailfail'],-1);
595    return false;
596  }
597}
598
599/**
600 * Update user profile
601 *
602 * @author    Christopher Smith <chris@jalakai.co.uk>
603 */
604function updateprofile() {
605  global $conf;
606  global $INFO;
607  global $lang;
608  global $auth;
609
610  if(empty($_POST['save'])) return false;
611
612  // should not be able to get here without Profile being possible...
613  if(!$auth->canDo('Profile')) {
614    msg($lang['profna'],-1);
615    return false;
616  }
617
618  if ($_POST['newpass'] != $_POST['passchk']) {
619    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
620    return false;
621  }
622
623  //clean fullname and email
624  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
625  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
626
627  if (empty($_POST['fullname']) || empty($_POST['email'])) {
628    msg($lang['profnoempty'],-1);
629    return false;
630  }
631
632  if (!mail_isvalid($_POST['email'])){
633    msg($lang['regbadmail'],-1);
634    return false;
635  }
636
637  if ($_POST['fullname'] != $INFO['userinfo']['name']) $changes['name'] = $_POST['fullname'];
638  if ($_POST['email']    != $INFO['userinfo']['mail']) $changes['mail'] = $_POST['email'];
639  if (!empty($_POST['newpass']))  $changes['pass'] = $_POST['newpass'];
640
641  if (!count($changes)) {
642    msg($lang['profnochange'], -1);
643    return false;
644  }
645
646  if ($conf['profileconfirm']) {
647      if (!auth_verifyPassword($_POST['oldpass'],$INFO['userinfo']['pass'])) {
648      msg($lang['badlogin'],-1);
649      return false;
650    }
651  }
652
653  return $auth->modifyUser($_SERVER['REMOTE_USER'], $changes);
654}
655
656/**
657 * Send a  new password
658 *
659 * This function handles both phases of the password reset:
660 *
661 *   - handling the first request of password reset
662 *   - validating the password reset auth token
663 *
664 * @author Benoit Chesneau <benoit@bchesneau.info>
665 * @author Chris Smith <chris@jalakai.co.uk>
666 * @author Andreas Gohr <andi@splitbrain.org>
667 *
668 * @return bool true on success, false on any error
669*/
670function act_resendpwd(){
671    global $lang;
672    global $conf;
673    global $auth;
674
675    if(!actionOK('resendpwd')) return false;
676
677    // should not be able to get here without modPass being possible...
678    if(!$auth->canDo('modPass')) {
679        msg($lang['resendna'],-1);
680        return false;
681    }
682
683    $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
684
685    if($token){
686        // we're in token phase
687
688        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
689        if(!@file_exists($tfile)){
690            msg($lang['resendpwdbadauth'],-1);
691            return false;
692        }
693        $user = io_readfile($tfile);
694        @unlink($tfile);
695        $userinfo = $auth->getUserData($user);
696        if(!$userinfo['mail']) {
697            msg($lang['resendpwdnouser'], -1);
698            return false;
699        }
700
701        $pass = auth_pwgen();
702        if (!$auth->modifyUser($user,array('pass' => $pass))) {
703            msg('error modifying user data',-1);
704            return false;
705        }
706
707        if (auth_sendPassword($user,$pass)) {
708            msg($lang['resendpwdsuccess'],1);
709        } else {
710            msg($lang['regmailfail'],-1);
711        }
712        return true;
713
714    } else {
715        // we're in request phase
716
717        if(!$_POST['save']) return false;
718
719        if (empty($_POST['login'])) {
720            msg($lang['resendpwdmissing'], -1);
721            return false;
722        } else {
723            $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
724            $user = cleanID($_POST['login']);
725        }
726
727        $userinfo = $auth->getUserData($user);
728        if(!$userinfo['mail']) {
729            msg($lang['resendpwdnouser'], -1);
730            return false;
731        }
732
733        // generate auth token
734        $token = md5(auth_cookiesalt().$user); //secret but user based
735        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
736        $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
737
738        io_saveFile($tfile,$user);
739
740        $text = rawLocale('pwconfirm');
741        $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
742        $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
743        $text = str_replace('@LOGIN@',$user,$text);
744        $text = str_replace('@TITLE@',$conf['title'],$text);
745        $text = str_replace('@CONFIRM@',$url,$text);
746
747        if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
748                     $lang['regpwmail'],
749                     $text,
750                     $conf['mailfrom'])){
751            msg($lang['resendpwdconfirm'],1);
752        }else{
753            msg($lang['regmailfail'],-1);
754        }
755        return true;
756    }
757
758    return false; // never reached
759}
760
761/**
762 * Uses a regular expresion to check if a given mail address is valid
763 *
764 * May not be completly RFC conform!
765 *
766 * @link    http://www.webmasterworld.com/forum88/135.htm
767 *
768 * @param   string $email the address to check
769 * @return  bool          true if address is valid
770 */
771function isvalidemail($email){
772  return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email);
773}
774
775/**
776 * Encrypts a password using the given method and salt
777 *
778 * If the selected method needs a salt and none was given, a random one
779 * is chosen.
780 *
781 * The following methods are understood:
782 *
783 *   smd5  - Salted MD5 hashing
784 *   md5   - Simple MD5 hashing
785 *   sha1  - SHA1 hashing
786 *   ssha  - Salted SHA1 hashing
787 *   crypt - Unix crypt
788 *   mysql - MySQL password (old method)
789 *   my411 - MySQL 4.1.1 password
790 *
791 * @author  Andreas Gohr <andi@splitbrain.org>
792 * @return  string  The crypted password
793 */
794function auth_cryptPassword($clear,$method='',$salt=''){
795  global $conf;
796  if(empty($method)) $method = $conf['passcrypt'];
797
798  //prepare a salt
799  if(empty($salt)) $salt = md5(uniqid(rand(), true));
800
801  switch(strtolower($method)){
802    case 'smd5':
803        return crypt($clear,'$1$'.substr($salt,0,8).'$');
804    case 'md5':
805      return md5($clear);
806    case 'sha1':
807      return sha1($clear);
808    case 'ssha':
809      $salt=substr($salt,0,4);
810      return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
811    case 'crypt':
812      return crypt($clear,substr($salt,0,2));
813    case 'mysql':
814      //from http://www.php.net/mysql comment by <soren at byu dot edu>
815      $nr=0x50305735;
816      $nr2=0x12345671;
817      $add=7;
818      $charArr = preg_split("//", $clear);
819      foreach ($charArr as $char) {
820        if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
821        $charVal = ord($char);
822        $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
823        $nr2 += ($nr2 << 8) ^ $nr;
824        $add += $charVal;
825      }
826      return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
827    case 'my411':
828      return '*'.sha1(pack("H*", sha1($clear)));
829    default:
830      msg("Unsupported crypt method $method",-1);
831  }
832}
833
834/**
835 * Verifies a cleartext password against a crypted hash
836 *
837 * The method and salt used for the crypted hash is determined automatically
838 * then the clear text password is crypted using the same method. If both hashs
839 * match true is is returned else false
840 *
841 * @author  Andreas Gohr <andi@splitbrain.org>
842 * @return  bool
843 */
844function auth_verifyPassword($clear,$crypt){
845  $method='';
846  $salt='';
847
848  //determine the used method and salt
849  $len = strlen($crypt);
850  if(substr($crypt,0,3) == '$1$'){
851    $method = 'smd5';
852    $salt   = substr($crypt,3,8);
853  }elseif(substr($crypt,0,6) == '{SSHA}'){
854    $method = 'ssha';
855    $salt   = substr(base64_decode(substr($crypt, 6)),20);
856  }elseif($len == 32){
857    $method = 'md5';
858  }elseif($len == 40){
859    $method = 'sha1';
860  }elseif($len == 16){
861    $method = 'mysql';
862  }elseif($len == 41 && $crypt[0] == '*'){
863    $method = 'my411';
864  }else{
865    $method = 'crypt';
866    $salt   = substr($crypt,0,2);
867  }
868
869  //crypt and compare
870  if(auth_cryptPassword($clear,$method,$salt) === $crypt){
871    return true;
872  }
873  return false;
874}
875
876//Setup VIM: ex: et ts=2 enc=utf-8 :
877