Move defines to their own file
[dokuwiki.git] / inc / auth.php
blob96ae7c236a53f91ae6fc3f0c8e8f7a114cf014be
1 <?php
2 /**
3 * Authentication library
5 * Including this file will automatically try to login
6 * a user by calling auth_login()
8 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
9 * @author Andreas Gohr <andi@splitbrain.org>
12 use dokuwiki\Extension\AuthPlugin;
13 use dokuwiki\Extension\Event;
14 use dokuwiki\Extension\PluginController;
15 use dokuwiki\PassHash;
16 use dokuwiki\Subscriptions\RegistrationSubscriptionSender;
18 /**
19 * Initialize the auth system.
21 * This function is automatically called at the end of init.php
23 * This used to be the main() of the auth.php
25 * @todo backend loading maybe should be handled by the class autoloader
26 * @todo maybe split into multiple functions at the XXX marked positions
27 * @triggers AUTH_LOGIN_CHECK
28 * @return bool
30 function auth_setup() {
31 global $conf;
32 /* @var AuthPlugin $auth */
33 global $auth;
34 /* @var Input $INPUT */
35 global $INPUT;
36 global $AUTH_ACL;
37 global $lang;
38 /* @var PluginController $plugin_controller */
39 global $plugin_controller;
40 $AUTH_ACL = array();
42 if(!$conf['useacl']) return false;
44 // try to load auth backend from plugins
45 foreach ($plugin_controller->getList('auth') as $plugin) {
46 if ($conf['authtype'] === $plugin) {
47 $auth = $plugin_controller->load('auth', $plugin);
48 break;
52 if(!isset($auth) || !$auth){
53 msg($lang['authtempfail'], -1);
54 return false;
57 if ($auth->success == false) {
58 // degrade to unauthenticated user
59 unset($auth);
60 auth_logoff();
61 msg($lang['authtempfail'], -1);
62 return false;
65 // do the login either by cookie or provided credentials XXX
66 $INPUT->set('http_credentials', false);
67 if(!$conf['rememberme']) $INPUT->set('r', false);
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)));
81 // if no credentials were given try to use HTTP auth (for SSO)
82 if(!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])) {
83 $INPUT->set('u', $_SERVER['PHP_AUTH_USER']);
84 $INPUT->set('p', $_SERVER['PHP_AUTH_PW']);
85 $INPUT->set('http_credentials', true);
88 // apply cleaning (auth specific user names, remove control chars)
89 if (true === $auth->success) {
90 $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
91 $INPUT->set('p', stripctl($INPUT->str('p')));
94 $ok = null;
95 if (!is_null($auth) && $auth->canDo('external')) {
96 $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
99 if ($ok === null) {
100 // external trust mechanism not in place, or returns no result,
101 // then attempt auth_login
102 $evdata = array(
103 'user' => $INPUT->str('u'),
104 'password' => $INPUT->str('p'),
105 'sticky' => $INPUT->bool('r'),
106 'silent' => $INPUT->bool('http_credentials')
108 Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
111 //load ACL into a global array XXX
112 $AUTH_ACL = auth_loadACL();
114 return true;
118 * Loads the ACL setup and handle user wildcards
120 * @author Andreas Gohr <andi@splitbrain.org>
122 * @return array
124 function auth_loadACL() {
125 global $config_cascade;
126 global $USERINFO;
127 /* @var Input $INPUT */
128 global $INPUT;
130 if(!is_readable($config_cascade['acl']['default'])) return array();
132 $acl = file($config_cascade['acl']['default']);
134 $out = array();
135 foreach($acl as $line) {
136 $line = trim($line);
137 if(empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
138 list($id,$rest) = preg_split('/[ \t]+/',$line,2);
140 // substitute user wildcard first (its 1:1)
141 if(strstr($line, '%USER%')){
142 // if user is not logged in, this ACL line is meaningless - skip it
143 if (!$INPUT->server->has('REMOTE_USER')) continue;
145 $id = str_replace('%USER%',cleanID($INPUT->server->str('REMOTE_USER')),$id);
146 $rest = str_replace('%USER%',auth_nameencode($INPUT->server->str('REMOTE_USER')),$rest);
149 // substitute group wildcard (its 1:m)
150 if(strstr($line, '%GROUP%')){
151 // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
152 if(isset($USERINFO['grps'])){
153 foreach((array) $USERINFO['grps'] as $grp){
154 $nid = str_replace('%GROUP%',cleanID($grp),$id);
155 $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest);
156 $out[] = "$nid\t$nrest";
159 } else {
160 $out[] = "$id\t$rest";
164 return $out;
168 * Event hook callback for AUTH_LOGIN_CHECK
170 * @param array $evdata
171 * @return bool
173 function auth_login_wrapper($evdata) {
174 return auth_login(
175 $evdata['user'],
176 $evdata['password'],
177 $evdata['sticky'],
178 $evdata['silent']
183 * This tries to login the user based on the sent auth credentials
185 * The authentication works like this: if a username was given
186 * a new login is assumed and user/password are checked. If they
187 * are correct the password is encrypted with blowfish and stored
188 * together with the username in a cookie - the same info is stored
189 * in the session, too. Additonally a browserID is stored in the
190 * session.
192 * If no username was given the cookie is checked: if the username,
193 * crypted password and browserID match between session and cookie
194 * no further testing is done and the user is accepted
196 * If a cookie was found but no session info was availabe the
197 * blowfish encrypted password from the cookie is decrypted and
198 * together with username rechecked by calling this function again.
200 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
201 * are set.
203 * @author Andreas Gohr <andi@splitbrain.org>
205 * @param string $user Username
206 * @param string $pass Cleartext Password
207 * @param bool $sticky Cookie should not expire
208 * @param bool $silent Don't show error on bad auth
209 * @return bool true on successful auth
211 function auth_login($user, $pass, $sticky = false, $silent = false) {
212 global $USERINFO;
213 global $conf;
214 global $lang;
215 /* @var AuthPlugin $auth */
216 global $auth;
217 /* @var Input $INPUT */
218 global $INPUT;
220 $sticky ? $sticky = true : $sticky = false; //sanity check
222 if(!$auth) return false;
224 if(!empty($user)) {
225 //usual login
226 if(!empty($pass) && $auth->checkPass($user, $pass)) {
227 // make logininfo globally available
228 $INPUT->server->set('REMOTE_USER', $user);
229 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
230 auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
231 return true;
232 } else {
233 //invalid credentials - log off
234 if(!$silent) {
235 http_status(403, 'Login failed');
236 msg($lang['badlogin'], -1);
238 auth_logoff();
239 return false;
241 } else {
242 // read cookie information
243 list($user, $sticky, $pass) = auth_getCookie();
244 if($user && $pass) {
245 // we got a cookie - see if we can trust it
247 // get session info
248 $session = $_SESSION[DOKU_COOKIE]['auth'];
249 if(isset($session) &&
250 $auth->useSessionCache($user) &&
251 ($session['time'] >= time() - $conf['auth_security_timeout']) &&
252 ($session['user'] == $user) &&
253 ($session['pass'] == sha1($pass)) && //still crypted
254 ($session['buid'] == auth_browseruid())
257 // he has session, cookie and browser right - let him in
258 $INPUT->server->set('REMOTE_USER', $user);
259 $USERINFO = $session['info']; //FIXME move all references to session
260 return true;
262 // no we don't trust it yet - recheck pass but silent
263 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
264 $pass = auth_decrypt($pass, $secret);
265 return auth_login($user, $pass, $sticky, true);
268 //just to be sure
269 auth_logoff(true);
270 return false;
274 * Builds a pseudo UID from browser and IP data
276 * This is neither unique nor unfakable - still it adds some
277 * security. Using the first part of the IP makes sure
278 * proxy farms like AOLs are still okay.
280 * @author Andreas Gohr <andi@splitbrain.org>
282 * @return string a MD5 sum of various browser headers
284 function auth_browseruid() {
285 /* @var Input $INPUT */
286 global $INPUT;
288 $ip = clientIP(true);
289 $uid = '';
290 $uid .= $INPUT->server->str('HTTP_USER_AGENT');
291 $uid .= $INPUT->server->str('HTTP_ACCEPT_CHARSET');
292 $uid .= substr($ip, 0, strpos($ip, '.'));
293 $uid = strtolower($uid);
294 return md5($uid);
298 * Creates a random key to encrypt the password in cookies
300 * This function tries to read the password for encrypting
301 * cookies from $conf['metadir'].'/_htcookiesalt'
302 * if no such file is found a random key is created and
303 * and stored in this file.
305 * @author Andreas Gohr <andi@splitbrain.org>
307 * @param bool $addsession if true, the sessionid is added to the salt
308 * @param bool $secure if security is more important than keeping the old value
309 * @return string
311 function auth_cookiesalt($addsession = false, $secure = false) {
312 if (defined('SIMPLE_TEST')) {
313 return 'test';
315 global $conf;
316 $file = $conf['metadir'].'/_htcookiesalt';
317 if ($secure || !file_exists($file)) {
318 $file = $conf['metadir'].'/_htcookiesalt2';
320 $salt = io_readFile($file);
321 if(empty($salt)) {
322 $salt = bin2hex(auth_randombytes(64));
323 io_saveFile($file, $salt);
325 if($addsession) {
326 $salt .= session_id();
328 return $salt;
332 * Return cryptographically secure random bytes.
334 * @author Niklas Keller <me@kelunik.com>
336 * @param int $length number of bytes
337 * @return string cryptographically secure random bytes
339 function auth_randombytes($length) {
340 return random_bytes($length);
344 * Cryptographically secure random number generator.
346 * @author Niklas Keller <me@kelunik.com>
348 * @param int $min
349 * @param int $max
350 * @return int
352 function auth_random($min, $max) {
353 return random_int($min, $max);
357 * Encrypt data using the given secret using AES
359 * The mode is CBC with a random initialization vector, the key is derived
360 * using pbkdf2.
362 * @param string $data The data that shall be encrypted
363 * @param string $secret The secret/password that shall be used
364 * @return string The ciphertext
366 function auth_encrypt($data, $secret) {
367 $iv = auth_randombytes(16);
368 $cipher = new \phpseclib\Crypt\AES();
369 $cipher->setPassword($secret);
372 this uses the encrypted IV as IV as suggested in
373 http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
374 for unique but necessarily random IVs. The resulting ciphertext is
375 compatible to ciphertext that was created using a "normal" IV.
377 return $cipher->encrypt($iv.$data);
381 * Decrypt the given AES ciphertext
383 * The mode is CBC, the key is derived using pbkdf2
385 * @param string $ciphertext The encrypted data
386 * @param string $secret The secret/password that shall be used
387 * @return string The decrypted data
389 function auth_decrypt($ciphertext, $secret) {
390 $iv = substr($ciphertext, 0, 16);
391 $cipher = new \phpseclib\Crypt\AES();
392 $cipher->setPassword($secret);
393 $cipher->setIV($iv);
395 return $cipher->decrypt(substr($ciphertext, 16));
399 * Log out the current user
401 * This clears all authentication data and thus log the user
402 * off. It also clears session data.
404 * @author Andreas Gohr <andi@splitbrain.org>
406 * @param bool $keepbc - when true, the breadcrumb data is not cleared
408 function auth_logoff($keepbc = false) {
409 global $conf;
410 global $USERINFO;
411 /* @var AuthPlugin $auth */
412 global $auth;
413 /* @var Input $INPUT */
414 global $INPUT;
416 // make sure the session is writable (it usually is)
417 @session_start();
419 if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
420 unset($_SESSION[DOKU_COOKIE]['auth']['user']);
421 if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
422 unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
423 if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
424 unset($_SESSION[DOKU_COOKIE]['auth']['info']);
425 if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
426 unset($_SESSION[DOKU_COOKIE]['bc']);
427 $INPUT->server->remove('REMOTE_USER');
428 $USERINFO = null; //FIXME
430 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
431 setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
433 if($auth) $auth->logOff();
437 * Check if a user is a manager
439 * Should usually be called without any parameters to check the current
440 * user.
442 * The info is available through $INFO['ismanager'], too
444 * @param string $user Username
445 * @param array $groups List of groups the user is in
446 * @param bool $adminonly when true checks if user is admin
447 * @param bool $recache set to true to refresh the cache
448 * @return bool
449 * @see auth_isadmin
451 * @author Andreas Gohr <andi@splitbrain.org>
453 function auth_ismanager($user = null, $groups = null, $adminonly = false, $recache=false) {
454 global $conf;
455 global $USERINFO;
456 /* @var AuthPlugin $auth */
457 global $auth;
458 /* @var Input $INPUT */
459 global $INPUT;
462 if(!$auth) return false;
463 if(is_null($user)) {
464 if(!$INPUT->server->has('REMOTE_USER')) {
465 return false;
466 } else {
467 $user = $INPUT->server->str('REMOTE_USER');
470 if(is_null($groups)) {
471 $groups = $USERINFO ? (array) $USERINFO['grps'] : array();
474 // prefer cached result
475 static $cache = [];
476 $cachekey = serialize([$user, $adminonly, $groups]);
477 if (!isset($cache[$cachekey]) || $recache) {
478 // check superuser match
479 $ok = auth_isMember($conf['superuser'], $user, $groups);
481 // check managers
482 if (!$ok && !$adminonly) {
483 $ok = auth_isMember($conf['manager'], $user, $groups);
486 $cache[$cachekey] = $ok;
489 return $cache[$cachekey];
493 * Check if a user is admin
495 * Alias to auth_ismanager with adminonly=true
497 * The info is available through $INFO['isadmin'], too
499 * @param string $user Username
500 * @param array $groups List of groups the user is in
501 * @param bool $recache set to true to refresh the cache
502 * @return bool
503 * @author Andreas Gohr <andi@splitbrain.org>
504 * @see auth_ismanager()
507 function auth_isadmin($user = null, $groups = null, $recache=false) {
508 return auth_ismanager($user, $groups, true, $recache);
512 * Match a user and his groups against a comma separated list of
513 * users and groups to determine membership status
515 * Note: all input should NOT be nameencoded.
517 * @param string $memberlist commaseparated list of allowed users and groups
518 * @param string $user user to match against
519 * @param array $groups groups the user is member of
520 * @return bool true for membership acknowledged
522 function auth_isMember($memberlist, $user, array $groups) {
523 /* @var AuthPlugin $auth */
524 global $auth;
525 if(!$auth) return false;
527 // clean user and groups
528 if(!$auth->isCaseSensitive()) {
529 $user = \dokuwiki\Utf8\PhpString::strtolower($user);
530 $groups = array_map('utf8_strtolower', $groups);
532 $user = $auth->cleanUser($user);
533 $groups = array_map(array($auth, 'cleanGroup'), $groups);
535 // extract the memberlist
536 $members = explode(',', $memberlist);
537 $members = array_map('trim', $members);
538 $members = array_unique($members);
539 $members = array_filter($members);
541 // compare cleaned values
542 foreach($members as $member) {
543 if($member == '@ALL' ) return true;
544 if(!$auth->isCaseSensitive()) $member = \dokuwiki\Utf8\PhpString::strtolower($member);
545 if($member[0] == '@') {
546 $member = $auth->cleanGroup(substr($member, 1));
547 if(in_array($member, $groups)) return true;
548 } else {
549 $member = $auth->cleanUser($member);
550 if($member == $user) return true;
554 // still here? not a member!
555 return false;
559 * Convinience function for auth_aclcheck()
561 * This checks the permissions for the current user
563 * @author Andreas Gohr <andi@splitbrain.org>
565 * @param string $id page ID (needs to be resolved and cleaned)
566 * @return int permission level
568 function auth_quickaclcheck($id) {
569 global $conf;
570 global $USERINFO;
571 /* @var Input $INPUT */
572 global $INPUT;
573 # if no ACL is used always return upload rights
574 if(!$conf['useacl']) return AUTH_UPLOAD;
575 return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : array());
579 * Returns the maximum rights a user has for the given ID or its namespace
581 * @author Andreas Gohr <andi@splitbrain.org>
583 * @triggers AUTH_ACL_CHECK
584 * @param string $id page ID (needs to be resolved and cleaned)
585 * @param string $user Username
586 * @param array|null $groups Array of groups the user is in
587 * @return int permission level
589 function auth_aclcheck($id, $user, $groups) {
590 $data = array(
591 'id' => $id,
592 'user' => $user,
593 'groups' => $groups
596 return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
600 * default ACL check method
602 * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
604 * @author Andreas Gohr <andi@splitbrain.org>
606 * @param array $data event data
607 * @return int permission level
609 function auth_aclcheck_cb($data) {
610 $id =& $data['id'];
611 $user =& $data['user'];
612 $groups =& $data['groups'];
614 global $conf;
615 global $AUTH_ACL;
616 /* @var AuthPlugin $auth */
617 global $auth;
619 // if no ACL is used always return upload rights
620 if(!$conf['useacl']) return AUTH_UPLOAD;
621 if(!$auth) return AUTH_NONE;
623 //make sure groups is an array
624 if(!is_array($groups)) $groups = array();
626 //if user is superuser or in superusergroup return 255 (acl_admin)
627 if(auth_isadmin($user, $groups)) {
628 return AUTH_ADMIN;
631 if(!$auth->isCaseSensitive()) {
632 $user = \dokuwiki\Utf8\PhpString::strtolower($user);
633 $groups = array_map('utf8_strtolower', $groups);
635 $user = auth_nameencode($auth->cleanUser($user));
636 $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
638 //prepend groups with @ and nameencode
639 foreach($groups as &$group) {
640 $group = '@'.auth_nameencode($group);
643 $ns = getNS($id);
644 $perm = -1;
646 //add ALL group
647 $groups[] = '@ALL';
649 //add User
650 if($user) $groups[] = $user;
652 //check exact match first
653 $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
654 if(count($matches)) {
655 foreach($matches as $match) {
656 $match = preg_replace('/#.*$/', '', $match); //ignore comments
657 $acl = preg_split('/[ \t]+/', $match);
658 if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
659 $acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]);
661 if(!in_array($acl[1], $groups)) {
662 continue;
664 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
665 if($acl[2] > $perm) {
666 $perm = $acl[2];
669 if($perm > -1) {
670 //we had a match - return it
671 return (int) $perm;
675 //still here? do the namespace checks
676 if($ns) {
677 $path = $ns.':*';
678 } else {
679 $path = '*'; //root document
682 do {
683 $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
684 if(count($matches)) {
685 foreach($matches as $match) {
686 $match = preg_replace('/#.*$/', '', $match); //ignore comments
687 $acl = preg_split('/[ \t]+/', $match);
688 if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
689 $acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]);
691 if(!in_array($acl[1], $groups)) {
692 continue;
694 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
695 if($acl[2] > $perm) {
696 $perm = $acl[2];
699 //we had a match - return it
700 if($perm != -1) {
701 return (int) $perm;
704 //get next higher namespace
705 $ns = getNS($ns);
707 if($path != '*') {
708 $path = $ns.':*';
709 if($path == ':*') $path = '*';
710 } else {
711 //we did this already
712 //looks like there is something wrong with the ACL
713 //break here
714 msg('No ACL setup yet! Denying access to everyone.');
715 return AUTH_NONE;
717 } while(1); //this should never loop endless
718 return AUTH_NONE;
722 * Encode ASCII special chars
724 * Some auth backends allow special chars in their user and groupnames
725 * The special chars are encoded with this function. Only ASCII chars
726 * are encoded UTF-8 multibyte are left as is (different from usual
727 * urlencoding!).
729 * Decoding can be done with rawurldecode
731 * @author Andreas Gohr <gohr@cosmocode.de>
732 * @see rawurldecode()
734 * @param string $name
735 * @param bool $skip_group
736 * @return string
738 function auth_nameencode($name, $skip_group = false) {
739 global $cache_authname;
740 $cache =& $cache_authname;
741 $name = (string) $name;
743 // never encode wildcard FS#1955
744 if($name == '%USER%') return $name;
745 if($name == '%GROUP%') return $name;
747 if(!isset($cache[$name][$skip_group])) {
748 if($skip_group && $name[0] == '@') {
749 $cache[$name][$skip_group] = '@'.preg_replace_callback(
750 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
751 'auth_nameencode_callback', substr($name, 1)
753 } else {
754 $cache[$name][$skip_group] = preg_replace_callback(
755 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
756 'auth_nameencode_callback', $name
761 return $cache[$name][$skip_group];
765 * callback encodes the matches
767 * @param array $matches first complete match, next matching subpatterms
768 * @return string
770 function auth_nameencode_callback($matches) {
771 return '%'.dechex(ord(substr($matches[1],-1)));
775 * Create a pronouncable password
777 * The $foruser variable might be used by plugins to run additional password
778 * policy checks, but is not used by the default implementation
780 * @author Andreas Gohr <andi@splitbrain.org>
781 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451
782 * @triggers AUTH_PASSWORD_GENERATE
784 * @param string $foruser username for which the password is generated
785 * @return string pronouncable password
787 function auth_pwgen($foruser = '') {
788 $data = array(
789 'password' => '',
790 'foruser' => $foruser
793 $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
794 if($evt->advise_before(true)) {
795 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
796 $v = 'aeiou'; //vowels
797 $a = $c.$v; //both
798 $s = '!$%&?+*~#-_:.;,'; // specials
800 //use thre syllables...
801 for($i = 0; $i < 3; $i++) {
802 $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
803 $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
804 $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
806 //... and add a nice number and special
807 $data['password'] .= $s[auth_random(0, strlen($s) - 1)].auth_random(10, 99);
809 $evt->advise_after();
811 return $data['password'];
815 * Sends a password to the given user
817 * @author Andreas Gohr <andi@splitbrain.org>
819 * @param string $user Login name of the user
820 * @param string $password The new password in clear text
821 * @return bool true on success
823 function auth_sendPassword($user, $password) {
824 global $lang;
825 /* @var AuthPlugin $auth */
826 global $auth;
827 if(!$auth) return false;
829 $user = $auth->cleanUser($user);
830 $userinfo = $auth->getUserData($user, $requireGroups = false);
832 if(!$userinfo['mail']) return false;
834 $text = rawLocale('password');
835 $trep = array(
836 'FULLNAME' => $userinfo['name'],
837 'LOGIN' => $user,
838 'PASSWORD' => $password
841 $mail = new Mailer();
842 $mail->to($mail->getCleanName($userinfo['name']).' <'.$userinfo['mail'].'>');
843 $mail->subject($lang['regpwmail']);
844 $mail->setBody($text, $trep);
845 return $mail->send();
849 * Register a new user
851 * This registers a new user - Data is read directly from $_POST
853 * @author Andreas Gohr <andi@splitbrain.org>
855 * @return bool true on success, false on any error
857 function register() {
858 global $lang;
859 global $conf;
860 /* @var \dokuwiki\Extension\AuthPlugin $auth */
861 global $auth;
862 global $INPUT;
864 if(!$INPUT->post->bool('save')) return false;
865 if(!actionOK('register')) return false;
867 // gather input
868 $login = trim($auth->cleanUser($INPUT->post->str('login')));
869 $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
870 $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
871 $pass = $INPUT->post->str('pass');
872 $passchk = $INPUT->post->str('passchk');
874 if(empty($login) || empty($fullname) || empty($email)) {
875 msg($lang['regmissing'], -1);
876 return false;
879 if($conf['autopasswd']) {
880 $pass = auth_pwgen($login); // automatically generate password
881 } elseif(empty($pass) || empty($passchk)) {
882 msg($lang['regmissing'], -1); // complain about missing passwords
883 return false;
884 } elseif($pass != $passchk) {
885 msg($lang['regbadpass'], -1); // complain about misspelled passwords
886 return false;
889 //check mail
890 if(!mail_isvalid($email)) {
891 msg($lang['regbadmail'], -1);
892 return false;
895 //okay try to create the user
896 if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) {
897 msg($lang['regfail'], -1);
898 return false;
901 // send notification about the new user
902 $subscription = new RegistrationSubscriptionSender();
903 $subscription->sendRegister($login, $fullname, $email);
905 // are we done?
906 if(!$conf['autopasswd']) {
907 msg($lang['regsuccess2'], 1);
908 return true;
911 // autogenerated password? then send password to user
912 if(auth_sendPassword($login, $pass)) {
913 msg($lang['regsuccess'], 1);
914 return true;
915 } else {
916 msg($lang['regmailfail'], -1);
917 return false;
922 * Update user profile
924 * @author Christopher Smith <chris@jalakai.co.uk>
926 function updateprofile() {
927 global $conf;
928 global $lang;
929 /* @var AuthPlugin $auth */
930 global $auth;
931 /* @var Input $INPUT */
932 global $INPUT;
934 if(!$INPUT->post->bool('save')) return false;
935 if(!checkSecurityToken()) return false;
937 if(!actionOK('profile')) {
938 msg($lang['profna'], -1);
939 return false;
942 $changes = array();
943 $changes['pass'] = $INPUT->post->str('newpass');
944 $changes['name'] = $INPUT->post->str('fullname');
945 $changes['mail'] = $INPUT->post->str('email');
947 // check misspelled passwords
948 if($changes['pass'] != $INPUT->post->str('passchk')) {
949 msg($lang['regbadpass'], -1);
950 return false;
953 // clean fullname and email
954 $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
955 $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
957 // no empty name and email (except the backend doesn't support them)
958 if((empty($changes['name']) && $auth->canDo('modName')) ||
959 (empty($changes['mail']) && $auth->canDo('modMail'))
961 msg($lang['profnoempty'], -1);
962 return false;
964 if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
965 msg($lang['regbadmail'], -1);
966 return false;
969 $changes = array_filter($changes);
971 // check for unavailable capabilities
972 if(!$auth->canDo('modName')) unset($changes['name']);
973 if(!$auth->canDo('modMail')) unset($changes['mail']);
974 if(!$auth->canDo('modPass')) unset($changes['pass']);
976 // anything to do?
977 if(!count($changes)) {
978 msg($lang['profnochange'], -1);
979 return false;
982 if($conf['profileconfirm']) {
983 if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
984 msg($lang['badpassconfirm'], -1);
985 return false;
989 if(!$auth->triggerUserMod('modify', array($INPUT->server->str('REMOTE_USER'), &$changes))) {
990 msg($lang['proffail'], -1);
991 return false;
994 if($changes['pass']) {
995 // update cookie and session with the changed data
996 list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
997 $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
998 auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
999 } else {
1000 // make sure the session is writable
1001 @session_start();
1002 // invalidate session cache
1003 $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
1004 session_write_close();
1007 return true;
1011 * Delete the current logged-in user
1013 * @return bool true on success, false on any error
1015 function auth_deleteprofile(){
1016 global $conf;
1017 global $lang;
1018 /* @var \dokuwiki\Extension\AuthPlugin $auth */
1019 global $auth;
1020 /* @var Input $INPUT */
1021 global $INPUT;
1023 if(!$INPUT->post->bool('delete')) return false;
1024 if(!checkSecurityToken()) return false;
1026 // action prevented or auth module disallows
1027 if(!actionOK('profile_delete') || !$auth->canDo('delUser')) {
1028 msg($lang['profnodelete'], -1);
1029 return false;
1032 if(!$INPUT->post->bool('confirm_delete')){
1033 msg($lang['profconfdeletemissing'], -1);
1034 return false;
1037 if($conf['profileconfirm']) {
1038 if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
1039 msg($lang['badpassconfirm'], -1);
1040 return false;
1044 $deleted = array();
1045 $deleted[] = $INPUT->server->str('REMOTE_USER');
1046 if($auth->triggerUserMod('delete', array($deleted))) {
1047 // force and immediate logout including removing the sticky cookie
1048 auth_logoff();
1049 return true;
1052 return false;
1056 * Send a new password
1058 * This function handles both phases of the password reset:
1060 * - handling the first request of password reset
1061 * - validating the password reset auth token
1063 * @author Benoit Chesneau <benoit@bchesneau.info>
1064 * @author Chris Smith <chris@jalakai.co.uk>
1065 * @author Andreas Gohr <andi@splitbrain.org>
1067 * @return bool true on success, false on any error
1069 function act_resendpwd() {
1070 global $lang;
1071 global $conf;
1072 /* @var AuthPlugin $auth */
1073 global $auth;
1074 /* @var Input $INPUT */
1075 global $INPUT;
1077 if(!actionOK('resendpwd')) {
1078 msg($lang['resendna'], -1);
1079 return false;
1082 $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
1084 if($token) {
1085 // we're in token phase - get user info from token
1087 $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
1088 if(!file_exists($tfile)) {
1089 msg($lang['resendpwdbadauth'], -1);
1090 $INPUT->remove('pwauth');
1091 return false;
1093 // token is only valid for 3 days
1094 if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
1095 msg($lang['resendpwdbadauth'], -1);
1096 $INPUT->remove('pwauth');
1097 @unlink($tfile);
1098 return false;
1101 $user = io_readfile($tfile);
1102 $userinfo = $auth->getUserData($user, $requireGroups = false);
1103 if(!$userinfo['mail']) {
1104 msg($lang['resendpwdnouser'], -1);
1105 return false;
1108 if(!$conf['autopasswd']) { // we let the user choose a password
1109 $pass = $INPUT->str('pass');
1111 // password given correctly?
1112 if(!$pass) return false;
1113 if($pass != $INPUT->str('passchk')) {
1114 msg($lang['regbadpass'], -1);
1115 return false;
1118 // change it
1119 if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1120 msg($lang['proffail'], -1);
1121 return false;
1124 } else { // autogenerate the password and send by mail
1126 $pass = auth_pwgen($user);
1127 if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1128 msg($lang['proffail'], -1);
1129 return false;
1132 if(auth_sendPassword($user, $pass)) {
1133 msg($lang['resendpwdsuccess'], 1);
1134 } else {
1135 msg($lang['regmailfail'], -1);
1139 @unlink($tfile);
1140 return true;
1142 } else {
1143 // we're in request phase
1145 if(!$INPUT->post->bool('save')) return false;
1147 if(!$INPUT->post->str('login')) {
1148 msg($lang['resendpwdmissing'], -1);
1149 return false;
1150 } else {
1151 $user = trim($auth->cleanUser($INPUT->post->str('login')));
1154 $userinfo = $auth->getUserData($user, $requireGroups = false);
1155 if(!$userinfo['mail']) {
1156 msg($lang['resendpwdnouser'], -1);
1157 return false;
1160 // generate auth token
1161 $token = md5(auth_randombytes(16)); // random secret
1162 $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
1163 $url = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
1165 io_saveFile($tfile, $user);
1167 $text = rawLocale('pwconfirm');
1168 $trep = array(
1169 'FULLNAME' => $userinfo['name'],
1170 'LOGIN' => $user,
1171 'CONFIRM' => $url
1174 $mail = new Mailer();
1175 $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1176 $mail->subject($lang['regpwmail']);
1177 $mail->setBody($text, $trep);
1178 if($mail->send()) {
1179 msg($lang['resendpwdconfirm'], 1);
1180 } else {
1181 msg($lang['regmailfail'], -1);
1183 return true;
1185 // never reached
1189 * Encrypts a password using the given method and salt
1191 * If the selected method needs a salt and none was given, a random one
1192 * is chosen.
1194 * @author Andreas Gohr <andi@splitbrain.org>
1196 * @param string $clear The clear text password
1197 * @param string $method The hashing method
1198 * @param string $salt A salt, null for random
1199 * @return string The crypted password
1201 function auth_cryptPassword($clear, $method = '', $salt = null) {
1202 global $conf;
1203 if(empty($method)) $method = $conf['passcrypt'];
1205 $pass = new PassHash();
1206 $call = 'hash_'.$method;
1208 if(!method_exists($pass, $call)) {
1209 msg("Unsupported crypt method $method", -1);
1210 return false;
1213 return $pass->$call($clear, $salt);
1217 * Verifies a cleartext password against a crypted hash
1219 * @author Andreas Gohr <andi@splitbrain.org>
1221 * @param string $clear The clear text password
1222 * @param string $crypt The hash to compare with
1223 * @return bool true if both match
1225 function auth_verifyPassword($clear, $crypt) {
1226 $pass = new PassHash();
1227 return $pass->verify_hash($clear, $crypt);
1231 * Set the authentication cookie and add user identification data to the session
1233 * @param string $user username
1234 * @param string $pass encrypted password
1235 * @param bool $sticky whether or not the cookie will last beyond the session
1236 * @return bool
1238 function auth_setCookie($user, $pass, $sticky) {
1239 global $conf;
1240 /* @var AuthPlugin $auth */
1241 global $auth;
1242 global $USERINFO;
1244 if(!$auth) return false;
1245 $USERINFO = $auth->getUserData($user);
1247 // set cookie
1248 $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
1249 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1250 $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1251 setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
1253 // set session
1254 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1255 $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1256 $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1257 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1258 $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1260 return true;
1264 * Returns the user, (encrypted) password and sticky bit from cookie
1266 * @returns array
1268 function auth_getCookie() {
1269 if(!isset($_COOKIE[DOKU_COOKIE])) {
1270 return array(null, null, null);
1272 list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
1273 $sticky = (bool) $sticky;
1274 $pass = base64_decode($pass);
1275 $user = base64_decode($user);
1276 return array($user, $sticky, $pass);
1279 //Setup VIM: ex: et ts=2 :