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