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