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