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