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 //make sure groups is an array 351 if(!is_array($groups)) $groups = array(); 352 353 //if user is superuser or in superusergroup return 255 (acl_admin) 354 if(auth_isadmin($user,$groups)) { return AUTH_ADMIN; } 355 356 $user = auth_nameencode($user); 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 $ns = getNS($id); 365 $perm = -1; 366 367 if($user){ 368 //add ALL group 369 $groups[] = '@ALL'; 370 //add User 371 $groups[] = $user; 372 //build regexp 373 $regexp = join('|',$groups); 374 }else{ 375 $regexp = '@ALL'; 376 } 377 378 //check exact match first 379 $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/',$AUTH_ACL); 380 if(count($matches)){ 381 foreach($matches as $match){ 382 $match = preg_replace('/#.*$/','',$match); //ignore comments 383 $acl = preg_split('/\s+/',$match); 384 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 385 if($acl[2] > $perm){ 386 $perm = $acl[2]; 387 } 388 } 389 if($perm > -1){ 390 //we had a match - return it 391 return $perm; 392 } 393 } 394 395 //still here? do the namespace checks 396 if($ns){ 397 $path = $ns.':\*'; 398 }else{ 399 $path = '\*'; //root document 400 } 401 402 do{ 403 $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL); 404 if(count($matches)){ 405 foreach($matches as $match){ 406 $match = preg_replace('/#.*$/','',$match); //ignore comments 407 $acl = preg_split('/\s+/',$match); 408 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 409 if($acl[2] > $perm){ 410 $perm = $acl[2]; 411 } 412 } 413 //we had a match - return it 414 return $perm; 415 } 416 417 //get next higher namespace 418 $ns = getNS($ns); 419 420 if($path != '\*'){ 421 $path = $ns.':\*'; 422 if($path == ':\*') $path = '\*'; 423 }else{ 424 //we did this already 425 //looks like there is something wrong with the ACL 426 //break here 427 msg('No ACL setup yet! Denying access to everyone.'); 428 return AUTH_NONE; 429 } 430 }while(1); //this should never loop endless 431 432 //still here? return no permissions 433 return AUTH_NONE; 434} 435 436/** 437 * Encode ASCII special chars 438 * 439 * Some auth backends allow special chars in their user and groupnames 440 * The special chars are encoded with this function. Only ASCII chars 441 * are encoded UTF-8 multibyte are left as is (different from usual 442 * urlencoding!). 443 * 444 * Decoding can be done with rawurldecode 445 * 446 * @author Andreas Gohr <gohr@cosmocode.de> 447 * @see rawurldecode() 448 */ 449function auth_nameencode($name,$skip_group=false){ 450 global $cache_authname; 451 $cache =& $cache_authname; 452 $name = (string) $name; 453 454 if (!isset($cache[$name][$skip_group])) { 455 if($skip_group && $name{0} =='@'){ 456 $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e', 457 "'%'.dechex(ord(substr('\\1',-1)))",substr($name,1)); 458 }else{ 459 $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e', 460 "'%'.dechex(ord(substr('\\1',-1)))",$name); 461 } 462 } 463 464 return $cache[$name][$skip_group]; 465} 466 467/** 468 * Create a pronouncable password 469 * 470 * @author Andreas Gohr <andi@splitbrain.org> 471 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451 472 * 473 * @return string pronouncable password 474 */ 475function auth_pwgen(){ 476 $pw = ''; 477 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones 478 $v = 'aeiou'; //vowels 479 $a = $c.$v; //both 480 481 //use two syllables... 482 for($i=0;$i < 2; $i++){ 483 $pw .= $c[rand(0, strlen($c)-1)]; 484 $pw .= $v[rand(0, strlen($v)-1)]; 485 $pw .= $a[rand(0, strlen($a)-1)]; 486 } 487 //... and add a nice number 488 $pw .= rand(10,99); 489 490 return $pw; 491} 492 493/** 494 * Sends a password to the given user 495 * 496 * @author Andreas Gohr <andi@splitbrain.org> 497 * 498 * @return bool true on success 499 */ 500function auth_sendPassword($user,$password){ 501 global $conf; 502 global $lang; 503 global $auth; 504 505 $hdrs = ''; 506 $userinfo = $auth->getUserData($user); 507 508 if(!$userinfo['mail']) return false; 509 510 $text = rawLocale('password'); 511 $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text); 512 $text = str_replace('@FULLNAME@',$userinfo['name'],$text); 513 $text = str_replace('@LOGIN@',$user,$text); 514 $text = str_replace('@PASSWORD@',$password,$text); 515 $text = str_replace('@TITLE@',$conf['title'],$text); 516 517 return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>', 518 $lang['regpwmail'], 519 $text, 520 $conf['mailfrom']); 521} 522 523/** 524 * Register a new user 525 * 526 * This registers a new user - Data is read directly from $_POST 527 * 528 * @author Andreas Gohr <andi@splitbrain.org> 529 * 530 * @return bool true on success, false on any error 531 */ 532function register(){ 533 global $lang; 534 global $conf; 535 global $auth; 536 537 if(!$_POST['save']) return false; 538 if(!$auth->canDo('addUser')) return false; 539 540 //clean username 541 $_POST['login'] = preg_replace('/.*:/','',$_POST['login']); 542 $_POST['login'] = cleanID($_POST['login']); 543 //clean fullname and email 544 $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname'])); 545 $_POST['email'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email'])); 546 547 if( empty($_POST['login']) || 548 empty($_POST['fullname']) || 549 empty($_POST['email']) ){ 550 msg($lang['regmissing'],-1); 551 return false; 552 } 553 554 if ($conf['autopasswd']) { 555 $pass = auth_pwgen(); // automatically generate password 556 } elseif (empty($_POST['pass']) || 557 empty($_POST['passchk'])) { 558 msg($lang['regmissing'], -1); // complain about missing passwords 559 return false; 560 } elseif ($_POST['pass'] != $_POST['passchk']) { 561 msg($lang['regbadpass'], -1); // complain about misspelled passwords 562 return false; 563 } else { 564 $pass = $_POST['pass']; // accept checked and valid password 565 } 566 567 //check mail 568 if(!mail_isvalid($_POST['email'])){ 569 msg($lang['regbadmail'],-1); 570 return false; 571 } 572 573 //okay try to create the user 574 if(!$auth->createUser($_POST['login'],$pass,$_POST['fullname'],$_POST['email'])){ 575 msg($lang['reguexists'],-1); 576 return false; 577 } 578 579 // create substitutions for use in notification email 580 $substitutions = array( 581 'NEWUSER' => $_POST['login'], 582 'NEWNAME' => $_POST['fullname'], 583 'NEWEMAIL' => $_POST['email'], 584 ); 585 586 if (!$conf['autopasswd']) { 587 msg($lang['regsuccess2'],1); 588 notify('', 'register', '', $_POST['login'], false, $substitutions); 589 return true; 590 } 591 592 // autogenerated password? then send him the password 593 if (auth_sendPassword($_POST['login'],$pass)){ 594 msg($lang['regsuccess'],1); 595 notify('', 'register', '', $_POST['login'], false, $substitutions); 596 return true; 597 }else{ 598 msg($lang['regmailfail'],-1); 599 return false; 600 } 601} 602 603/** 604 * Update user profile 605 * 606 * @author Christopher Smith <chris@jalakai.co.uk> 607 */ 608function updateprofile() { 609 global $conf; 610 global $INFO; 611 global $lang; 612 global $auth; 613 614 if(empty($_POST['save'])) return false; 615 if(!checkSecurityToken()) return false; 616 617 // should not be able to get here without Profile being possible... 618 if(!$auth->canDo('Profile')) { 619 msg($lang['profna'],-1); 620 return false; 621 } 622 623 if ($_POST['newpass'] != $_POST['passchk']) { 624 msg($lang['regbadpass'], -1); // complain about misspelled passwords 625 return false; 626 } 627 628 //clean fullname and email 629 $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname'])); 630 $_POST['email'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email'])); 631 632 if (empty($_POST['fullname']) || empty($_POST['email'])) { 633 msg($lang['profnoempty'],-1); 634 return false; 635 } 636 637 if (!mail_isvalid($_POST['email'])){ 638 msg($lang['regbadmail'],-1); 639 return false; 640 } 641 642 if ($_POST['fullname'] != $INFO['userinfo']['name'] && $auth->canDo('modName')) $changes['name'] = $_POST['fullname']; 643 if ($_POST['email'] != $INFO['userinfo']['mail'] && $auth->canDo('modMail')) $changes['mail'] = $_POST['email']; 644 if (!empty($_POST['newpass']) && $auth->canDo['modPass']) $changes['pass'] = $_POST['newpass']; 645 646 647 if (!count($changes)) { 648 msg($lang['profnochange'], -1); 649 return false; 650 } 651 652 if ($conf['profileconfirm']) { 653 if (!$auth->checkPass($_SERVER['REMOTE_USER'], $_POST['oldpass'])) { 654 msg($lang['badlogin'],-1); 655 return false; 656 } 657 } 658 659 return $auth->modifyUser($_SERVER['REMOTE_USER'], $changes); 660} 661 662/** 663 * Send a new password 664 * 665 * This function handles both phases of the password reset: 666 * 667 * - handling the first request of password reset 668 * - validating the password reset auth token 669 * 670 * @author Benoit Chesneau <benoit@bchesneau.info> 671 * @author Chris Smith <chris@jalakai.co.uk> 672 * @author Andreas Gohr <andi@splitbrain.org> 673 * 674 * @return bool true on success, false on any error 675*/ 676function act_resendpwd(){ 677 global $lang; 678 global $conf; 679 global $auth; 680 681 if(!actionOK('resendpwd')) return false; 682 683 // should not be able to get here without modPass being possible... 684 if(!$auth->canDo('modPass')) { 685 msg($lang['resendna'],-1); 686 return false; 687 } 688 689 $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']); 690 691 if($token){ 692 // we're in token phase 693 694 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; 695 if(!@file_exists($tfile)){ 696 msg($lang['resendpwdbadauth'],-1); 697 return false; 698 } 699 $user = io_readfile($tfile); 700 @unlink($tfile); 701 $userinfo = $auth->getUserData($user); 702 if(!$userinfo['mail']) { 703 msg($lang['resendpwdnouser'], -1); 704 return false; 705 } 706 707 $pass = auth_pwgen(); 708 if (!$auth->modifyUser($user,array('pass' => $pass))) { 709 msg('error modifying user data',-1); 710 return false; 711 } 712 713 if (auth_sendPassword($user,$pass)) { 714 msg($lang['resendpwdsuccess'],1); 715 } else { 716 msg($lang['regmailfail'],-1); 717 } 718 return true; 719 720 } else { 721 // we're in request phase 722 723 if(!$_POST['save']) return false; 724 725 if (empty($_POST['login'])) { 726 msg($lang['resendpwdmissing'], -1); 727 return false; 728 } else { 729 $_POST['login'] = preg_replace('/.*:/','',$_POST['login']); 730 $user = cleanID($_POST['login']); 731 } 732 733 $userinfo = $auth->getUserData($user); 734 if(!$userinfo['mail']) { 735 msg($lang['resendpwdnouser'], -1); 736 return false; 737 } 738 739 // generate auth token 740 $token = md5(auth_cookiesalt().$user); //secret but user based 741 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; 742 $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&'); 743 744 io_saveFile($tfile,$user); 745 746 $text = rawLocale('pwconfirm'); 747 $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text); 748 $text = str_replace('@FULLNAME@',$userinfo['name'],$text); 749 $text = str_replace('@LOGIN@',$user,$text); 750 $text = str_replace('@TITLE@',$conf['title'],$text); 751 $text = str_replace('@CONFIRM@',$url,$text); 752 753 if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>', 754 $lang['regpwmail'], 755 $text, 756 $conf['mailfrom'])){ 757 msg($lang['resendpwdconfirm'],1); 758 }else{ 759 msg($lang['regmailfail'],-1); 760 } 761 return true; 762 } 763 764 return false; // never reached 765} 766 767/** 768 * Uses a regular expresion to check if a given mail address is valid 769 * 770 * May not be completly RFC conform! 771 * 772 * @link http://www.webmasterworld.com/forum88/135.htm 773 * 774 * @param string $email the address to check 775 * @return bool true if address is valid 776 */ 777function isvalidemail($email){ 778 return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email); 779} 780 781/** 782 * Encrypts a password using the given method and salt 783 * 784 * If the selected method needs a salt and none was given, a random one 785 * is chosen. 786 * 787 * The following methods are understood: 788 * 789 * smd5 - Salted MD5 hashing 790 * md5 - Simple MD5 hashing 791 * sha1 - SHA1 hashing 792 * ssha - Salted SHA1 hashing 793 * crypt - Unix crypt 794 * mysql - MySQL password (old method) 795 * my411 - MySQL 4.1.1 password 796 * 797 * @author Andreas Gohr <andi@splitbrain.org> 798 * @return string The crypted password 799 */ 800function auth_cryptPassword($clear,$method='',$salt=''){ 801 global $conf; 802 if(empty($method)) $method = $conf['passcrypt']; 803 804 //prepare a salt 805 if(empty($salt)) $salt = md5(uniqid(rand(), true)); 806 807 switch(strtolower($method)){ 808 case 'smd5': 809 return crypt($clear,'$1$'.substr($salt,0,8).'$'); 810 case 'md5': 811 return md5($clear); 812 case 'sha1': 813 return sha1($clear); 814 case 'ssha': 815 $salt=substr($salt,0,4); 816 return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt); 817 case 'crypt': 818 return crypt($clear,substr($salt,0,2)); 819 case 'mysql': 820 //from http://www.php.net/mysql comment by <soren at byu dot edu> 821 $nr=0x50305735; 822 $nr2=0x12345671; 823 $add=7; 824 $charArr = preg_split("//", $clear); 825 foreach ($charArr as $char) { 826 if (($char == '') || ($char == ' ') || ($char == '\t')) continue; 827 $charVal = ord($char); 828 $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8); 829 $nr2 += ($nr2 << 8) ^ $nr; 830 $add += $charVal; 831 } 832 return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff)); 833 case 'my411': 834 return '*'.sha1(pack("H*", sha1($clear))); 835 default: 836 msg("Unsupported crypt method $method",-1); 837 } 838} 839 840/** 841 * Verifies a cleartext password against a crypted hash 842 * 843 * The method and salt used for the crypted hash is determined automatically 844 * then the clear text password is crypted using the same method. If both hashs 845 * match true is is returned else false 846 * 847 * @author Andreas Gohr <andi@splitbrain.org> 848 * @return bool 849 */ 850function auth_verifyPassword($clear,$crypt){ 851 $method=''; 852 $salt=''; 853 854 //determine the used method and salt 855 $len = strlen($crypt); 856 if(substr($crypt,0,3) == '$1$'){ 857 $method = 'smd5'; 858 $salt = substr($crypt,3,8); 859 }elseif(substr($crypt,0,6) == '{SSHA}'){ 860 $method = 'ssha'; 861 $salt = substr(base64_decode(substr($crypt, 6)),20); 862 }elseif($len == 32){ 863 $method = 'md5'; 864 }elseif($len == 40){ 865 $method = 'sha1'; 866 }elseif($len == 16){ 867 $method = 'mysql'; 868 }elseif($len == 41 && $crypt[0] == '*'){ 869 $method = 'my411'; 870 }else{ 871 $method = 'crypt'; 872 $salt = substr($crypt,0,2); 873 } 874 875 //crypt and compare 876 if(auth_cryptPassword($clear,$method,$salt) === $crypt){ 877 return true; 878 } 879 return false; 880} 881 882//Setup VIM: ex: et ts=2 enc=utf-8 : 883