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