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