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