PageRenderTime 58ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/elgg/mod/dokuwiki/lib/dokuwiki/inc/auth.php

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