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