[ Index ]

PHP Cross Reference of DokuWiki

title

Body

[close]

/inc/ -> auth.php (source)

   1  <?php
   2  
   3  /**
   4   * Authentication library
   5   *
   6   * Including this file will automatically try to login
   7   * a user by calling auth_login()
   8   *
   9   * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
  10   * @author     Andreas Gohr <andi@splitbrain.org>
  11   */
  12  
  13  use dokuwiki\Ip;
  14  use dokuwiki\ErrorHandler;
  15  use dokuwiki\JWT;
  16  use dokuwiki\Logger;
  17  use dokuwiki\MailUtils;
  18  use dokuwiki\Utf8\PhpString;
  19  use dokuwiki\Extension\AuthPlugin;
  20  use dokuwiki\Extension\Event;
  21  use dokuwiki\Extension\PluginController;
  22  use dokuwiki\PassHash;
  23  use dokuwiki\Subscriptions\RegistrationSubscriptionSender;
  24  use phpseclib3\Crypt\AES;
  25  use phpseclib3\Crypt\Common\SymmetricKey;
  26  use phpseclib3\Exception\BadDecryptionException;
  27  
  28  /**
  29   * Initialize the auth system.
  30   *
  31   * This function is automatically called at the end of init.php
  32   *
  33   * This used to be the main() of the auth.php
  34   *
  35   * @todo backend loading maybe should be handled by the class autoloader
  36   * @todo maybe split into multiple functions at the XXX marked positions
  37   * @triggers AUTH_LOGIN_CHECK
  38   * @return bool
  39   */
  40  function auth_setup()
  41  {
  42      global $conf;
  43      /* @var AuthPlugin $auth */
  44      global $auth;
  45      /* @var Input $INPUT */
  46      global $INPUT;
  47      global $AUTH_ACL;
  48      global $lang;
  49      /* @var PluginController $plugin_controller */
  50      global $plugin_controller;
  51      $AUTH_ACL = [];
  52  
  53      // unset REMOTE_USER if empty
  54      if ($INPUT->server->str('REMOTE_USER') === '') {
  55          $INPUT->server->remove('REMOTE_USER');
  56      }
  57  
  58      if (!$conf['useacl']) return false;
  59  
  60      // try to load auth backend from plugins
  61      foreach ($plugin_controller->getList('auth') as $plugin) {
  62          if ($conf['authtype'] === $plugin) {
  63              $auth = $plugin_controller->load('auth', $plugin);
  64              break;
  65          }
  66      }
  67  
  68      if (!$auth instanceof AuthPlugin) {
  69          msg($lang['authtempfail'], -1);
  70          return false;
  71      }
  72  
  73      if ($auth->success == false) {
  74          // degrade to unauthenticated user
  75          $auth = null;
  76          auth_logoff();
  77          msg($lang['authtempfail'], -1);
  78          return false;
  79      }
  80  
  81      // do the login either by cookie or provided credentials XXX
  82      $INPUT->set('http_credentials', false);
  83      if (!$conf['rememberme']) $INPUT->set('r', false);
  84  
  85      // Populate Basic Auth user/password from Authorization header
  86      // Note: with FastCGI, data is in REDIRECT_HTTP_AUTHORIZATION instead of HTTP_AUTHORIZATION
  87      $header = $INPUT->server->str('HTTP_AUTHORIZATION') ?: $INPUT->server->str('REDIRECT_HTTP_AUTHORIZATION');
  88      if (preg_match('~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches)) {
  89          [$_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']] = sexplode(':', base64_decode($matches[1]), 2, '');
  90      }
  91  
  92      // if no credentials were given try to use HTTP auth (for SSO)
  93      if (!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($INPUT->server->str('PHP_AUTH_USER'))) {
  94          $INPUT->set('u', $INPUT->server->str('PHP_AUTH_USER'));
  95          $INPUT->set('p', $INPUT->server->str('PHP_AUTH_PW'));
  96          $INPUT->set('http_credentials', true);
  97      }
  98  
  99      // apply cleaning (auth specific user names, remove control chars)
 100      if (true === $auth->success) {
 101          $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
 102          $INPUT->set('p', stripctl($INPUT->str('p')));
 103      }
 104  
 105      if (!auth_tokenlogin()) {
 106          $ok = null;
 107  
 108          if ($auth->canDo('external')) {
 109              $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
 110          }
 111  
 112          if ($ok === null) {
 113              // external trust mechanism not in place, or returns no result,
 114              // then attempt auth_login
 115              $evdata = [
 116                  'user' => $INPUT->str('u'),
 117                  'password' => $INPUT->str('p'),
 118                  'sticky' => $INPUT->bool('r'),
 119                  'silent' => $INPUT->bool('http_credentials')
 120              ];
 121              Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
 122          }
 123      }
 124  
 125      //load ACL into a global array XXX
 126      $AUTH_ACL = auth_loadACL();
 127  
 128      return true;
 129  }
 130  
 131  /**
 132   * Loads the ACL setup and handle user wildcards
 133   *
 134   * @author Andreas Gohr <andi@splitbrain.org>
 135   *
 136   * @return array
 137   */
 138  function auth_loadACL()
 139  {
 140      global $config_cascade;
 141      global $USERINFO;
 142      /* @var Input $INPUT */
 143      global $INPUT;
 144  
 145      if (!is_readable($config_cascade['acl']['default'])) return [];
 146  
 147      $acl = file($config_cascade['acl']['default']);
 148  
 149      $out = [];
 150      foreach ($acl as $line) {
 151          $line = trim($line);
 152          if (empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
 153          [$id, $rest] = preg_split('/[ \t]+/', $line, 2);
 154  
 155          // substitute user wildcard first (its 1:1)
 156          if (strstr($line, '%USER%')) {
 157              // if user is not logged in, this ACL line is meaningless - skip it
 158              if (!$INPUT->server->has('REMOTE_USER')) continue;
 159  
 160              $id   = str_replace('%USER%', cleanID($INPUT->server->str('REMOTE_USER')), $id);
 161              $rest = str_replace('%USER%', auth_nameencode($INPUT->server->str('REMOTE_USER')), $rest);
 162          }
 163  
 164          // substitute group wildcard (its 1:m)
 165          if (strstr($line, '%GROUP%')) {
 166              // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
 167              if (isset($USERINFO['grps'])) {
 168                  foreach ((array) $USERINFO['grps'] as $grp) {
 169                      $nid   = str_replace('%GROUP%', cleanID($grp), $id);
 170                      $nrest = str_replace('%GROUP%', '@' . auth_nameencode($grp), $rest);
 171                      $out[] = "$nid\t$nrest";
 172                  }
 173              }
 174          } else {
 175              $out[] = "$id\t$rest";
 176          }
 177      }
 178  
 179      return $out;
 180  }
 181  
 182  /**
 183   * Try a token login
 184   *
 185   * @return bool true if token login succeeded
 186   */
 187  function auth_tokenlogin()
 188  {
 189      global $USERINFO;
 190      global $INPUT;
 191      /** @var DokuWiki_Auth_Plugin $auth */
 192      global $auth;
 193      if (!$auth) return false;
 194  
 195      $headers = [];
 196  
 197      // try to get the headers from Apache
 198      if (function_exists('getallheaders')) {
 199          $headers = getallheaders();
 200          if (is_array($headers)) {
 201              $headers = array_change_key_case($headers);
 202          }
 203      }
 204  
 205      // get the headers from $_SERVER
 206      if (!$headers) {
 207          foreach ($_SERVER as $key => $value) {
 208              if (str_starts_with($key, 'HTTP_')) {
 209                  // underscores in $_SERVER keys stand for dashes in the header name
 210                  $headers[strtolower(strtr(substr($key, 5), '_', '-'))] = $value;
 211              }
 212          }
 213      }
 214  
 215      // check authorization header
 216      if (isset($headers['authorization'])) {
 217          [$type, $token] = sexplode(' ', $headers['authorization'], 2);
 218          if ($type !== 'Bearer') $token = ''; // not the token we want
 219      }
 220  
 221      // check x-dokuwiki-token header
 222      if (isset($headers['x-dokuwiki-token'])) {
 223          $token = $headers['x-dokuwiki-token'];
 224      }
 225  
 226      if (empty($token)) return false;
 227  
 228      // check token
 229      try {
 230          $authtoken = JWT::validate($token);
 231      } catch (Exception $e) {
 232          Logger::debug('Token login failed: ' . $e->getMessage(), null, $e->getFile(), $e->getLine());
 233          msg(hsc($e->getMessage()), -1);
 234          return false;
 235      }
 236  
 237      // fetch user info from backend
 238      $user = $authtoken->getUser();
 239      $USERINFO = $auth->getUserData($user);
 240      if (!$USERINFO) return false;
 241  
 242      // the code is correct, set up user
 243      $INPUT->server->set('REMOTE_USER', $user);
 244      $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
 245      $_SESSION[DOKU_COOKIE]['auth']['pass'] = 'nope';
 246      $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
 247      $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
 248  
 249      return true;
 250  }
 251  
 252  /**
 253   * Event hook callback for AUTH_LOGIN_CHECK
 254   *
 255   * @param array $evdata
 256   * @return bool
 257   * @throws Exception
 258   */
 259  function auth_login_wrapper($evdata)
 260  {
 261      return auth_login(
 262          $evdata['user'],
 263          $evdata['password'],
 264          $evdata['sticky'],
 265          $evdata['silent']
 266      );
 267  }
 268  
 269  /**
 270   * This tries to login the user based on the sent auth credentials
 271   *
 272   * The authentication works like this: if a username was given
 273   * a new login is assumed and user/password are checked. If they
 274   * are correct the password is encrypted with blowfish and stored
 275   * together with the username in a cookie - the same info is stored
 276   * in the session, too. Additonally a browserID is stored in the
 277   * session.
 278   *
 279   * If no username was given the cookie is checked: if the username,
 280   * crypted password and browserID match between session and cookie
 281   * no further testing is done and the user is accepted
 282   *
 283   * If a cookie was found but no session info was availabe the
 284   * blowfish encrypted password from the cookie is decrypted and
 285   * together with username rechecked by calling this function again.
 286   *
 287   * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
 288   * are set.
 289   *
 290   * @param string $user Username
 291   * @param string $pass Cleartext Password
 292   * @param bool $sticky Cookie should not expire
 293   * @param bool $silent Don't show error on bad auth
 294   * @return bool true on successful auth
 295   * @throws Exception
 296   *
 297   * @author  Andreas Gohr <andi@splitbrain.org>
 298   */
 299  function auth_login($user, $pass, $sticky = false, $silent = false)
 300  {
 301      global $USERINFO;
 302      global $conf;
 303      global $lang;
 304      /* @var AuthPlugin $auth */
 305      global $auth;
 306      /* @var Input $INPUT */
 307      global $INPUT;
 308  
 309      if (!$auth instanceof AuthPlugin) return false;
 310  
 311      if (!empty($user)) {
 312          //usual login
 313          if (!empty($pass)) usleep(random_int(0, 250)); // add a random delay to prevent timing attacks #4491
 314          if (!empty($pass) && $auth->checkPass($user, $pass)) {
 315              // make logininfo globally available
 316              $INPUT->server->set('REMOTE_USER', $user);
 317              $secret                 = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
 318              auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
 319              return true;
 320          }
 321          //invalid credentials - log off
 322          if (!$silent) {
 323              http_status(403, 'Login failed');
 324              msg($lang['badlogin'], -1);
 325          }
 326          auth_logoff();
 327          return false;
 328      }
 329      // read cookie information
 330      [$user, $sticky, $pass] = auth_getCookie();
 331      if ($user && $pass) {
 332          // we got a cookie - see if we can trust it
 333  
 334          // get session info
 335          if (isset($_SESSION[DOKU_COOKIE])) {
 336              $session = $_SESSION[DOKU_COOKIE]['auth'] ?? [];
 337              if (
 338                  isset($session['user']) &&
 339                  isset($session['pass']) &&
 340                  $auth->useSessionCache($user) &&
 341                  ($session['time'] >= time() - $conf['auth_security_timeout']) &&
 342                  ($session['user'] === $user) &&
 343                  ($session['pass'] === sha1($pass)) && //still crypted
 344                  ($session['buid'] === auth_browseruid())
 345              ) {
 346                  // he has session, cookie and browser right - let him in
 347                  $INPUT->server->set('REMOTE_USER', $user);
 348                  $USERINFO = $session['info']; //FIXME move all references to session
 349                  return true;
 350              }
 351          }
 352          // no we don't trust it yet - recheck pass but silent
 353          $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
 354          $pass   = auth_decrypt($pass, $secret);
 355          return auth_login($user, $pass, $sticky, true);
 356      }
 357      //just to be sure
 358      auth_logoff(true);
 359      return false;
 360  }
 361  
 362  /**
 363   * Builds a pseudo UID from browser and IP data
 364   *
 365   * This is neither unique nor unfakable - still it adds some
 366   * security. Using the first part of the IP makes sure
 367   * proxy farms like AOLs are still okay.
 368   *
 369   * @author  Andreas Gohr <andi@splitbrain.org>
 370   *
 371   * @return  string  a SHA256 sum of various browser headers
 372   */
 373  function auth_browseruid()
 374  {
 375      /* @var Input $INPUT */
 376      global $INPUT;
 377  
 378      $ip = clientIP(true);
 379      // convert IP string to packed binary representation
 380      $pip = inet_pton($ip);
 381  
 382      $uid = implode("\n", [
 383          $INPUT->server->str('HTTP_USER_AGENT'),
 384          $INPUT->server->str('HTTP_ACCEPT_LANGUAGE'),
 385          substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6)
 386      ]);
 387      return hash('sha256', $uid);
 388  }
 389  
 390  /**
 391   * Creates a random key to encrypt the password in cookies
 392   *
 393   * This function tries to read the password for encrypting
 394   * cookies from $conf['metadir'].'/_htcookiesalt'
 395   * if no such file is found a random key is created and
 396   * and stored in this file.
 397   *
 398   * @param bool $addsession if true, the sessionid is added to the salt
 399   * @param bool $secure if security is more important than keeping the old value
 400   * @return  string
 401   * @throws Exception
 402   *
 403   * @author  Andreas Gohr <andi@splitbrain.org>
 404   */
 405  function auth_cookiesalt($addsession = false, $secure = false)
 406  {
 407      if (defined('SIMPLE_TEST')) {
 408          return 'test';
 409      }
 410      global $conf;
 411      $file = $conf['metadir'] . '/_htcookiesalt';
 412      if ($secure || !file_exists($file)) {
 413          $file = $conf['metadir'] . '/_htcookiesalt2';
 414      }
 415      $salt = io_readFile($file);
 416      if (empty($salt)) {
 417          $salt = bin2hex(auth_randombytes(64));
 418          io_saveFile($file, $salt);
 419      }
 420      if ($addsession) {
 421          $salt .= session_id();
 422      }
 423      return $salt;
 424  }
 425  
 426  /**
 427   * Return cryptographically secure random bytes.
 428   *
 429   * @param int $length number of bytes
 430   * @return string cryptographically secure random bytes
 431   * @throws Exception
 432   *
 433   * @author Niklas Keller <me@kelunik.com>
 434   */
 435  function auth_randombytes($length)
 436  {
 437      return random_bytes($length);
 438  }
 439  
 440  /**
 441   * Cryptographically secure random number generator.
 442   *
 443   * @param int $min
 444   * @param int $max
 445   * @return int
 446   * @throws Exception
 447   *
 448   * @author Niklas Keller <me@kelunik.com>
 449   */
 450  function auth_random($min, $max)
 451  {
 452      return random_int($min, $max);
 453  }
 454  
 455  /**
 456   * Encrypt data using the given secret using AES
 457   *
 458   * The mode is CBC with a random initialization vector, the key is derived
 459   * using pbkdf2.
 460   *
 461   * @param string $data The data that shall be encrypted
 462   * @param string $secret The secret/password that shall be used
 463   * @return string The ciphertext
 464   * @throws Exception
 465   */
 466  function auth_encrypt($data, $secret)
 467  {
 468      $iv     = auth_randombytes(16);
 469      $cipher = new AES('cbc');
 470      $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib');
 471      $cipher->setIV($iv);
 472  
 473      /*
 474      this uses the encrypted IV as IV as suggested in
 475      http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
 476      for unique but necessarily random IVs. The resulting ciphertext is
 477      compatible to ciphertext that was created using a "normal" IV.
 478      */
 479      return $cipher->encrypt($iv . $data);
 480  }
 481  
 482  /**
 483   * Decrypt the given AES ciphertext
 484   *
 485   * The mode is CBC, the key is derived using pbkdf2
 486   *
 487   * @param string $ciphertext The encrypted data
 488   * @param string $secret     The secret/password that shall be used
 489   * @return string|null The decrypted data
 490   */
 491  function auth_decrypt($ciphertext, $secret)
 492  {
 493      $iv     = substr($ciphertext, 0, 16);
 494      $cipher = new AES('cbc');
 495      $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib');
 496      $cipher->setIV($iv);
 497  
 498      try {
 499          return $cipher->decrypt(substr($ciphertext, 16));
 500      } catch (BadDecryptionException $e) {
 501          ErrorHandler::logException($e);
 502          return null;
 503      }
 504  }
 505  
 506  /**
 507   * Log out the current user
 508   *
 509   * This clears all authentication data and thus log the user
 510   * off. It also clears session data.
 511   *
 512   * @author  Andreas Gohr <andi@splitbrain.org>
 513   *
 514   * @param bool $keepbc - when true, the breadcrumb data is not cleared
 515   */
 516  function auth_logoff($keepbc = false)
 517  {
 518      global $conf;
 519      global $USERINFO;
 520      /* @var AuthPlugin $auth */
 521      global $auth;
 522      /* @var Input $INPUT */
 523      global $INPUT;
 524  
 525      // make sure the session is writable (it usually is)
 526      @session_start();
 527  
 528      if (isset($_SESSION[DOKU_COOKIE]['auth']['user']))
 529          unset($_SESSION[DOKU_COOKIE]['auth']['user']);
 530      if (isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
 531          unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
 532      if (isset($_SESSION[DOKU_COOKIE]['auth']['info']))
 533          unset($_SESSION[DOKU_COOKIE]['auth']['info']);
 534      if (!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
 535          unset($_SESSION[DOKU_COOKIE]['bc']);
 536      $INPUT->server->remove('REMOTE_USER');
 537      $USERINFO = null; //FIXME
 538  
 539      $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
 540      setcookie(DOKU_COOKIE, '', [
 541          'expires' => time() - 600000,
 542          'path' => $cookieDir,
 543          'secure' => ($conf['securecookie'] && Ip::isSsl()),
 544          'httponly' => true,
 545          'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
 546      ]);
 547  
 548      if ($auth instanceof AuthPlugin) {
 549          $auth->logOff();
 550      }
 551  }
 552  
 553  /**
 554   * Check if a user is a manager
 555   *
 556   * Should usually be called without any parameters to check the current
 557   * user.
 558   *
 559   * The info is available through $INFO['ismanager'], too
 560   *
 561   * @param string $user Username
 562   * @param array $groups List of groups the user is in
 563   * @param bool $adminonly when true checks if user is admin
 564   * @param bool $recache set to true to refresh the cache
 565   * @return bool
 566   * @see    auth_isadmin
 567   *
 568   * @author Andreas Gohr <andi@splitbrain.org>
 569   */
 570  function auth_ismanager($user = null, $groups = null, $adminonly = false, $recache = false)
 571  {
 572      global $conf;
 573      global $USERINFO;
 574      /* @var AuthPlugin $auth */
 575      global $auth;
 576      /* @var Input $INPUT */
 577      global $INPUT;
 578  
 579  
 580      if (!$auth instanceof AuthPlugin) return false;
 581      if (is_null($user)) {
 582          if (!$INPUT->server->has('REMOTE_USER')) {
 583              return false;
 584          }
 585          $user = $INPUT->server->str('REMOTE_USER');
 586      }
 587      if (is_null($groups)) {
 588          // checking the logged in user, or another one?
 589          if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) {
 590              $groups =  (array) $USERINFO['grps'];
 591          } else {
 592              $groups = $auth->getUserData($user);
 593              $groups = $groups ? $groups['grps'] : [];
 594          }
 595      }
 596  
 597      // prefer cached result
 598      static $cache = [];
 599      $cachekey = serialize([$user, $adminonly, $groups]);
 600      if (!isset($cache[$cachekey]) || $recache) {
 601          // check superuser match
 602          $ok = auth_isMember($conf['superuser'], $user, $groups);
 603  
 604          // check managers
 605          if (!$ok && !$adminonly) {
 606              $ok = auth_isMember($conf['manager'], $user, $groups);
 607          }
 608  
 609          $cache[$cachekey] = $ok;
 610      }
 611  
 612      return $cache[$cachekey];
 613  }
 614  
 615  /**
 616   * Check if a user is admin
 617   *
 618   * Alias to auth_ismanager with adminonly=true
 619   *
 620   * The info is available through $INFO['isadmin'], too
 621   *
 622   * @param string $user Username
 623   * @param array $groups List of groups the user is in
 624   * @param bool $recache set to true to refresh the cache
 625   * @return bool
 626   * @author Andreas Gohr <andi@splitbrain.org>
 627   * @see auth_ismanager()
 628   *
 629   */
 630  function auth_isadmin($user = null, $groups = null, $recache = false)
 631  {
 632      return auth_ismanager($user, $groups, true, $recache);
 633  }
 634  
 635  /**
 636   * Match a user and his groups against a comma separated list of
 637   * users and groups to determine membership status
 638   *
 639   * Note: all input should NOT be nameencoded.
 640   *
 641   * @param string $memberlist commaseparated list of allowed users and groups
 642   * @param string $user       user to match against
 643   * @param array  $groups     groups the user is member of
 644   * @return bool       true for membership acknowledged
 645   */
 646  function auth_isMember($memberlist, $user, array $groups)
 647  {
 648      /* @var AuthPlugin $auth */
 649      global $auth;
 650      if (!$auth instanceof AuthPlugin) return false;
 651  
 652      // numeric names may arrive as integers when they were used as array keys
 653      // (PHP coerces numeric keys); cast to string so the strict comparisons
 654      // below match again without weakening them
 655      $user   = (string) $user;
 656      $groups = array_map(strval(...), $groups);
 657  
 658      // clean user and groups
 659      if (!$auth->isCaseSensitive()) {
 660          $user   = PhpString::strtolower($user);
 661          $groups = array_map(PhpString::strtolower(...), $groups);
 662      }
 663      $user   = $auth->cleanUser($user);
 664      $groups = array_map($auth->cleanGroup(...), $groups);
 665  
 666      // extract the memberlist
 667      $members = explode(',', $memberlist);
 668      $members = array_map(trim(...), $members);
 669      $members = array_unique($members);
 670      $members = array_filter($members);
 671  
 672      // compare cleaned values
 673      foreach ($members as $member) {
 674          if ($member == '@ALL') return true;
 675          if (!$auth->isCaseSensitive()) $member = PhpString::strtolower($member);
 676          if ($member[0] == '@') {
 677              $member = $auth->cleanGroup(substr($member, 1));
 678              if (in_array($member, $groups, true)) return true;
 679          } else {
 680              $member = $auth->cleanUser($member);
 681              if ($member === $user) return true;
 682          }
 683      }
 684  
 685      // still here? not a member!
 686      return false;
 687  }
 688  
 689  /**
 690   * Convinience function for auth_aclcheck()
 691   *
 692   * This checks the permissions for the current user
 693   *
 694   * @author  Andreas Gohr <andi@splitbrain.org>
 695   *
 696   * @param  string  $id  page ID (needs to be resolved and cleaned)
 697   * @return int          permission level
 698   */
 699  function auth_quickaclcheck($id)
 700  {
 701      global $conf;
 702      global $USERINFO;
 703      /* @var Input $INPUT */
 704      global $INPUT;
 705      # if no ACL is used always return upload rights
 706      if (!$conf['useacl']) return AUTH_UPLOAD;
 707      return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : []);
 708  }
 709  
 710  /**
 711   * Build the ACL path for a media file.
 712   *
 713   * Media files do not have per-file ACLs; permissions are always evaluated against the namespace
 714   * they live in. This returns the namespace wildcard path (e.g. "wiki:*" or "*" for root-namespace
 715   * media) suitable for passing to auth_quickaclcheck() or auth_aclcheck().
 716   *
 717   * @param string $id media ID (needs to be resolved and cleaned)
 718   * @return string the ACL path to check
 719   */
 720  function mediaAclPath($id)
 721  {
 722      return ltrim(getNS($id) . ':*', ':');
 723  }
 724  
 725  /**
 726   * Returns the maximum rights a user has for the given ID or its namespace
 727   *
 728   * @author  Andreas Gohr <andi@splitbrain.org>
 729   *
 730   * @triggers AUTH_ACL_CHECK
 731   * @param  string       $id     page ID (needs to be resolved and cleaned)
 732   * @param  string       $user   Username
 733   * @param  array|null   $groups Array of groups the user is in
 734   * @return int             permission level
 735   */
 736  function auth_aclcheck($id, $user, $groups)
 737  {
 738      $data = [
 739          'id'     => $id ?? '',
 740          'user'   => $user,
 741          'groups' => $groups
 742      ];
 743  
 744      return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
 745  }
 746  
 747  /**
 748   * default ACL check method
 749   *
 750   * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
 751   *
 752   * @author  Andreas Gohr <andi@splitbrain.org>
 753   *
 754   * @param  array $data event data
 755   * @return int   permission level
 756   */
 757  function auth_aclcheck_cb($data)
 758  {
 759      $id     =& $data['id'];
 760      $user   =& $data['user'];
 761      $groups =& $data['groups'];
 762  
 763      global $conf;
 764      global $AUTH_ACL;
 765      /* @var AuthPlugin $auth */
 766      global $auth;
 767  
 768      // if no ACL is used always return upload rights
 769      if (!$conf['useacl']) return AUTH_UPLOAD;
 770      if (!$auth instanceof AuthPlugin) return AUTH_NONE;
 771      if (!is_array($AUTH_ACL)) return AUTH_NONE;
 772  
 773      //make sure groups is an array
 774      if (!is_array($groups)) $groups = [];
 775  
 776      //if user is superuser or in superusergroup return 255 (acl_admin)
 777      if (auth_isadmin($user, $groups)) {
 778          return AUTH_ADMIN;
 779      }
 780  
 781      if (!$auth->isCaseSensitive()) {
 782          $user   = PhpString::strtolower($user);
 783          $groups = array_map(PhpString::strtolower(...), $groups);
 784      }
 785      $user   = auth_nameencode($auth->cleanUser($user));
 786      $groups = array_map($auth->cleanGroup(...), $groups);
 787  
 788      //prepend groups with @ and nameencode
 789      foreach ($groups as &$group) {
 790          $group = '@' . auth_nameencode($group);
 791      }
 792  
 793      $ns   = getNS($id);
 794      $perm = -1;
 795  
 796      //add ALL group
 797      $groups[] = '@ALL';
 798  
 799      //add User
 800      if ($user) $groups[] = $user;
 801  
 802      //check exact match first
 803      $matches = preg_grep('/^' . preg_quote($id, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
 804      if (count($matches)) {
 805          foreach ($matches as $match) {
 806              $match = preg_replace('/#.*$/', '', $match); //ignore comments
 807              $acl   = preg_split('/[ \t]+/', $match);
 808              if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
 809                  $acl[1] = PhpString::strtolower($acl[1]);
 810              }
 811              if (!in_array($acl[1], $groups, true)) {
 812                  continue;
 813              }
 814              if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
 815              if ($acl[2] > $perm) {
 816                  $perm = $acl[2];
 817              }
 818          }
 819          if ($perm > -1) {
 820              //we had a match - return it
 821              return (int) $perm;
 822          }
 823      }
 824  
 825      //still here? do the namespace checks
 826      if ($ns) {
 827          $path = $ns . ':*';
 828      } else {
 829          $path = '*'; //root document
 830      }
 831  
 832      do {
 833          $matches = preg_grep('/^' . preg_quote($path, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
 834          if (count($matches)) {
 835              foreach ($matches as $match) {
 836                  $match = preg_replace('/#.*$/', '', $match); //ignore comments
 837                  $acl   = preg_split('/[ \t]+/', $match);
 838                  if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
 839                      $acl[1] = PhpString::strtolower($acl[1]);
 840                  }
 841                  if (!in_array($acl[1], $groups, true)) {
 842                      continue;
 843                  }
 844                  if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
 845                  if ($acl[2] > $perm) {
 846                      $perm = $acl[2];
 847                  }
 848              }
 849              //we had a match - return it
 850              if ($perm != -1) {
 851                  return (int) $perm;
 852              }
 853          }
 854          //get next higher namespace
 855          $ns = getNS($ns);
 856  
 857          if ($path != '*') {
 858              $path = $ns . ':*';
 859              if ($path == ':*') $path = '*';
 860          } else {
 861              //we did this already
 862              //looks like there is something wrong with the ACL
 863              //break here
 864              msg('No ACL setup yet! Denying access to everyone.');
 865              return AUTH_NONE;
 866          }
 867      } while (1); //this should never loop endless
 868      return AUTH_NONE;
 869  }
 870  
 871  /**
 872   * Encode ASCII special chars
 873   *
 874   * Some auth backends allow special chars in their user and groupnames
 875   * The special chars are encoded with this function. Only ASCII chars
 876   * are encoded UTF-8 multibyte are left as is (different from usual
 877   * urlencoding!).
 878   *
 879   * Decoding can be done with rawurldecode
 880   *
 881   * @author Andreas Gohr <gohr@cosmocode.de>
 882   * @see rawurldecode()
 883   *
 884   * @param string $name
 885   * @param bool $skip_group
 886   * @return string
 887   */
 888  function auth_nameencode($name, $skip_group = false)
 889  {
 890      global $cache_authname;
 891      $cache =& $cache_authname;
 892      $name  = (string) $name;
 893  
 894      // never encode wildcard FS#1955
 895      if ($name == '%USER%') return $name;
 896      if ($name == '%GROUP%') return $name;
 897  
 898      if (!isset($cache[$name][$skip_group])) {
 899          if ($skip_group && $name[0] == '@') {
 900              $cache[$name][$skip_group] = '@' . preg_replace_callback(
 901                  '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
 902                  auth_nameencode_callback(...),
 903                  substr($name, 1)
 904              );
 905          } else {
 906              $cache[$name][$skip_group] = preg_replace_callback(
 907                  '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
 908                  auth_nameencode_callback(...),
 909                  $name
 910              );
 911          }
 912      }
 913  
 914      return $cache[$name][$skip_group];
 915  }
 916  
 917  /**
 918   * callback encodes the matches
 919   *
 920   * @param array $matches first complete match, next matching subpatterms
 921   * @return string
 922   */
 923  function auth_nameencode_callback($matches)
 924  {
 925      return '%' . dechex(ord(substr($matches[1], -1)));
 926  }
 927  
 928  /**
 929   * Create a pronouncable password
 930   *
 931   * The $foruser variable might be used by plugins to run additional password
 932   * policy checks, but is not used by the default implementation
 933   *
 934   * @param string $foruser username for which the password is generated
 935   * @return string  pronouncable password
 936   * @throws Exception
 937   *
 938   * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
 939   * @triggers AUTH_PASSWORD_GENERATE
 940   *
 941   * @author   Andreas Gohr <andi@splitbrain.org>
 942   */
 943  function auth_pwgen($foruser = '')
 944  {
 945      $data = [
 946          'password' => '',
 947          'foruser'  => $foruser
 948      ];
 949  
 950      $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
 951      if ($evt->advise_before(true)) {
 952          $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
 953          $v = 'aeiou'; //vowels
 954          $a = $c . $v; //both
 955          $s = '!$%&?+*~#-_:.;,'; // specials
 956  
 957          //use thre syllables...
 958          for ($i = 0; $i < 3; $i++) {
 959              $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
 960              $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
 961              $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
 962          }
 963          //... and add a nice number and special
 964          $data['password'] .= $s[auth_random(0, strlen($s) - 1)] . auth_random(10, 99);
 965      }
 966      $evt->advise_after();
 967  
 968      return $data['password'];
 969  }
 970  
 971  /**
 972   * Sends a password to the given user
 973   *
 974   * @author  Andreas Gohr <andi@splitbrain.org>
 975   *
 976   * @param string $user Login name of the user
 977   * @param string $password The new password in clear text
 978   * @return bool  true on success
 979   */
 980  function auth_sendPassword($user, $password)
 981  {
 982      global $lang;
 983      /* @var AuthPlugin $auth */
 984      global $auth;
 985      if (!$auth instanceof AuthPlugin) return false;
 986  
 987      $user     = $auth->cleanUser($user);
 988      $userinfo = $auth->getUserData($user, false);
 989  
 990      if (!$userinfo['mail']) return false;
 991  
 992      $text = rawLocale('password');
 993      $trep = [
 994          'FULLNAME' => $userinfo['name'],
 995          'LOGIN'    => $user,
 996          'PASSWORD' => $password
 997      ];
 998  
 999      $mail = new Mailer();
1000      $mail->to($mail->getCleanName($userinfo['name']) . ' <' . $userinfo['mail'] . '>');
1001      $mail->subject($lang['regpwmail']);
1002      $mail->setBody($text, $trep);
1003      return $mail->send();
1004  }
1005  
1006  /**
1007   * Register a new user
1008   *
1009   * This registers a new user - Data is read directly from $_POST
1010   *
1011   * @return bool  true on success, false on any error
1012   * @throws Exception
1013   *
1014   * @author  Andreas Gohr <andi@splitbrain.org>
1015   */
1016  function register()
1017  {
1018      global $lang;
1019      global $conf;
1020      /* @var AuthPlugin $auth */
1021      global $auth;
1022      global $INPUT;
1023  
1024      if (!$INPUT->post->bool('save')) return false;
1025      if (!actionOK('register')) return false;
1026  
1027      // gather input
1028      $login    = trim($auth->cleanUser($INPUT->post->str('login')));
1029      $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
1030      $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
1031      $pass     = $INPUT->post->str('pass');
1032      $passchk  = $INPUT->post->str('passchk');
1033  
1034      if (empty($login) || empty($fullname) || empty($email)) {
1035          msg($lang['regmissing'], -1);
1036          return false;
1037      }
1038  
1039      if ($conf['autopasswd']) {
1040          $pass = auth_pwgen($login); // automatically generate password
1041      } elseif (empty($pass) || empty($passchk)) {
1042          msg($lang['regmissing'], -1); // complain about missing passwords
1043          return false;
1044      } elseif ($pass != $passchk) {
1045          msg($lang['regbadpass'], -1); // complain about misspelled passwords
1046          return false;
1047      }
1048  
1049      //check mail
1050      if (!MailUtils::isValid($email)) {
1051          msg($lang['regbadmail'], -1);
1052          return false;
1053      }
1054  
1055      //okay try to create the user
1056      if (!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) {
1057          msg($lang['regfail'], -1);
1058          return false;
1059      }
1060  
1061      // send notification about the new user
1062      $subscription = new RegistrationSubscriptionSender();
1063      $subscription->sendRegister($login, $fullname, $email);
1064  
1065      // are we done?
1066      if (!$conf['autopasswd']) {
1067          msg($lang['regsuccess2'], 1);
1068          return true;
1069      }
1070  
1071      // autogenerated password? then send password to user
1072      if (auth_sendPassword($login, $pass)) {
1073          msg($lang['regsuccess'], 1);
1074          return true;
1075      }
1076      msg($lang['regmailfail'], -1);
1077      return false;
1078  }
1079  
1080  /**
1081   * Update user profile
1082   *
1083   * @throws Exception
1084   *
1085   * @author    Christopher Smith <chris@jalakai.co.uk>
1086   */
1087  function updateprofile()
1088  {
1089      global $conf;
1090      global $lang;
1091      /* @var AuthPlugin $auth */
1092      global $auth;
1093      /* @var Input $INPUT */
1094      global $INPUT;
1095  
1096      if (!$INPUT->post->bool('save')) return false;
1097      if (!checkSecurityToken()) return false;
1098  
1099      if (!actionOK('profile')) {
1100          msg($lang['profna'], -1);
1101          return false;
1102      }
1103  
1104      $changes         = [];
1105      $changes['pass'] = $INPUT->post->str('newpass');
1106      $changes['name'] = $INPUT->post->str('fullname');
1107      $changes['mail'] = $INPUT->post->str('email');
1108  
1109      // check misspelled passwords
1110      if ($changes['pass'] != $INPUT->post->str('passchk')) {
1111          msg($lang['regbadpass'], -1);
1112          return false;
1113      }
1114  
1115      // clean fullname and email
1116      $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
1117      $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
1118  
1119      // no empty name and email (except the backend doesn't support them)
1120      if (
1121          (empty($changes['name']) && $auth->canDo('modName')) ||
1122          (empty($changes['mail']) && $auth->canDo('modMail'))
1123      ) {
1124          msg($lang['profnoempty'], -1);
1125          return false;
1126      }
1127      if (!MailUtils::isValid($changes['mail']) && $auth->canDo('modMail')) {
1128          msg($lang['regbadmail'], -1);
1129          return false;
1130      }
1131  
1132      $changes = array_filter($changes);
1133  
1134      // check for unavailable capabilities
1135      if (!$auth->canDo('modName')) unset($changes['name']);
1136      if (!$auth->canDo('modMail')) unset($changes['mail']);
1137      if (!$auth->canDo('modPass')) unset($changes['pass']);
1138  
1139      // anything to do?
1140      if ($changes === []) {
1141          msg($lang['profnochange'], -1);
1142          return false;
1143      }
1144  
1145      if ($conf['profileconfirm']) {
1146          if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
1147              msg($lang['badpassconfirm'], -1);
1148              return false;
1149          }
1150      }
1151  
1152      if (!$auth->triggerUserMod('modify', [$INPUT->server->str('REMOTE_USER'), &$changes])) {
1153          msg($lang['proffail'], -1);
1154          return false;
1155      }
1156  
1157      if (array_key_exists('pass', $changes) && $changes['pass']) {
1158          // update cookie and session with the changed data
1159          [/* user */, $sticky, /* pass */] = auth_getCookie();
1160          $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1161          auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
1162      } else {
1163          // make sure the session is writable
1164          @session_start();
1165          // invalidate session cache
1166          $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
1167          session_write_close();
1168      }
1169  
1170      return true;
1171  }
1172  
1173  /**
1174   * Delete the current logged-in user
1175   *
1176   * @return bool true on success, false on any error
1177   */
1178  function auth_deleteprofile()
1179  {
1180      global $conf;
1181      global $lang;
1182      /* @var AuthPlugin $auth */
1183      global $auth;
1184      /* @var Input $INPUT */
1185      global $INPUT;
1186  
1187      if (!$INPUT->post->bool('delete')) return false;
1188      if (!checkSecurityToken()) return false;
1189  
1190      // action prevented or auth module disallows
1191      if (!actionOK('profile_delete') || !$auth->canDo('delUser')) {
1192          msg($lang['profnodelete'], -1);
1193          return false;
1194      }
1195  
1196      if (!$INPUT->post->bool('confirm_delete')) {
1197          msg($lang['profconfdeletemissing'], -1);
1198          return false;
1199      }
1200  
1201      if ($conf['profileconfirm']) {
1202          if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
1203              msg($lang['badpassconfirm'], -1);
1204              return false;
1205          }
1206      }
1207  
1208      $deleted = [];
1209      $deleted[] = $INPUT->server->str('REMOTE_USER');
1210      if ($auth->triggerUserMod('delete', [$deleted])) {
1211          // force and immediate logout including removing the sticky cookie
1212          auth_logoff();
1213          return true;
1214      }
1215  
1216      return false;
1217  }
1218  
1219  /**
1220   * Send a  new password
1221   *
1222   * This function handles both phases of the password reset:
1223   *
1224   *   - handling the first request of password reset
1225   *   - validating the password reset auth token
1226   *
1227   * @return bool true on success, false on any error
1228   * @throws Exception
1229   *
1230   * @author Andreas Gohr <andi@splitbrain.org>
1231   * @author Benoit Chesneau <benoit@bchesneau.info>
1232   * @author Chris Smith <chris@jalakai.co.uk>
1233   */
1234  function act_resendpwd()
1235  {
1236      global $lang;
1237      global $conf;
1238      /* @var AuthPlugin $auth */
1239      global $auth;
1240      /* @var Input $INPUT */
1241      global $INPUT;
1242  
1243      if (!actionOK('resendpwd')) {
1244          msg($lang['resendna'], -1);
1245          return false;
1246      }
1247  
1248      $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
1249  
1250      if ($token) {
1251          // we're in token phase - get user info from token
1252  
1253          $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
1254          if (!file_exists($tfile)) {
1255              msg($lang['resendpwdbadauth'], -1);
1256              $INPUT->remove('pwauth');
1257              return false;
1258          }
1259          // token is only valid for 3 days
1260          if ((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
1261              msg($lang['resendpwdbadauth'], -1);
1262              $INPUT->remove('pwauth');
1263              @unlink($tfile);
1264              return false;
1265          }
1266  
1267          $user     = io_readfile($tfile);
1268          $userinfo = $auth->getUserData($user, false);
1269          if (!$userinfo['mail']) {
1270              msg($lang['resendpwdnouser'], -1);
1271              return false;
1272          }
1273  
1274          if (!$conf['autopasswd']) { // we let the user choose a password
1275              $pass = $INPUT->str('pass');
1276  
1277              // password given correctly?
1278              if (!$pass) return false;
1279              if ($pass != $INPUT->str('passchk')) {
1280                  msg($lang['regbadpass'], -1);
1281                  return false;
1282              }
1283  
1284              // change it
1285              if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1286                  msg($lang['proffail'], -1);
1287                  return false;
1288              }
1289          } else { // autogenerate the password and send by mail
1290              $pass = auth_pwgen($user);
1291              if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1292                  msg($lang['proffail'], -1);
1293                  return false;
1294              }
1295  
1296              if (auth_sendPassword($user, $pass)) {
1297                  msg($lang['resendpwdsuccess'], 1);
1298              } else {
1299                  msg($lang['regmailfail'], -1);
1300              }
1301          }
1302  
1303          @unlink($tfile);
1304          return true;
1305      }
1306      // we're in request phase
1307      if (!$INPUT->post->bool('save')) return false;
1308      if (!$INPUT->post->str('login')) {
1309          msg($lang['resendpwdmissing'], -1);
1310          return false;
1311      }
1312      $user = trim($auth->cleanUser($INPUT->post->str('login')));
1313      $userinfo = $auth->getUserData($user, false);
1314      if (!$userinfo['mail']) {
1315          msg($lang['resendpwdnouser'], -1);
1316          return false;
1317      }
1318      // generate auth token
1319      $token = md5(auth_randombytes(16)); // random secret
1320      $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
1321      $url   = wl('', ['do' => 'resendpwd', 'pwauth' => $token], true, '&');
1322      io_saveFile($tfile, $user);
1323      $text = rawLocale('pwconfirm');
1324      $trep = ['FULLNAME' => $userinfo['name'], 'LOGIN'    => $user, 'CONFIRM'  => $url];
1325      $mail = new Mailer();
1326      $mail->to($userinfo['name'] . ' <' . $userinfo['mail'] . '>');
1327      $mail->subject($lang['regpwmail']);
1328      $mail->setBody($text, $trep);
1329      if ($mail->send()) {
1330          msg($lang['resendpwdconfirm'], 1);
1331      } else {
1332          msg($lang['regmailfail'], -1);
1333      }
1334      return true;
1335  }
1336  
1337  /**
1338   * Encrypts a password using the given method and salt
1339   *
1340   * If the selected method needs a salt and none was given, a random one
1341   * is chosen.
1342   *
1343   * You can pass null as the password to create an unusable hash.
1344   *
1345   * @author  Andreas Gohr <andi@splitbrain.org>
1346   *
1347   * @param string $clear The clear text password
1348   * @param string $method The hashing method
1349   * @param string $salt A salt, null for random
1350   * @return  string  The crypted password
1351   */
1352  function auth_cryptPassword($clear, $method = '', $salt = null)
1353  {
1354      global $conf;
1355  
1356      if ($clear === null) {
1357          return DOKU_UNUSABLE_PASSWORD;
1358      }
1359  
1360      if (empty($method)) $method = $conf['passcrypt'];
1361  
1362      $pass = new PassHash();
1363      $call = 'hash_' . $method;
1364  
1365      if (!method_exists($pass, $call)) {
1366          msg("Unsupported crypt method $method", -1);
1367          return false;
1368      }
1369  
1370      return $pass->$call($clear, $salt);
1371  }
1372  
1373  /**
1374   * Verifies a cleartext password against a crypted hash
1375   *
1376   * @param string $clear The clear text password
1377   * @param string $crypt The hash to compare with
1378   * @return bool true if both match
1379   * @throws Exception
1380   *
1381   * @author Andreas Gohr <andi@splitbrain.org>
1382   */
1383  function auth_verifyPassword($clear, $crypt)
1384  {
1385      if ($crypt === DOKU_UNUSABLE_PASSWORD) {
1386          return false;
1387      }
1388  
1389      $pass = new PassHash();
1390      return $pass->verify_hash($clear, $crypt);
1391  }
1392  
1393  /**
1394   * Set the authentication cookie and add user identification data to the session
1395   *
1396   * @param string  $user       username
1397   * @param string  $pass       encrypted password
1398   * @param bool    $sticky     whether or not the cookie will last beyond the session
1399   * @return bool
1400   */
1401  function auth_setCookie($user, $pass, $sticky)
1402  {
1403      global $conf;
1404      /* @var AuthPlugin $auth */
1405      global $auth;
1406      global $USERINFO;
1407  
1408      if (!$auth instanceof AuthPlugin) return false;
1409      $USERINFO = $auth->getUserData($user);
1410  
1411      // set cookie
1412      $cookie    = base64_encode($user) . '|' . ((int) $sticky) . '|' . base64_encode($pass);
1413      $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1414      $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1415      setcookie(DOKU_COOKIE, $cookie, [
1416          'expires' => $time,
1417          'path' => $cookieDir,
1418          'secure' => ($conf['securecookie'] && Ip::isSsl()),
1419          'httponly' => true,
1420          'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
1421      ]);
1422  
1423      // set session
1424      $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1425      $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1426      $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1427      $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1428      $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1429  
1430      return true;
1431  }
1432  
1433  /**
1434   * Returns the user, (encrypted) password and sticky bit from cookie
1435   *
1436   * @returns array
1437   */
1438  function auth_getCookie()
1439  {
1440      if (!isset($_COOKIE[DOKU_COOKIE])) {
1441          return [null, null, null];
1442      }
1443      [$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, '');
1444      $sticky = (bool) $sticky;
1445      $pass   = base64_decode($pass);
1446      $user   = base64_decode($user);
1447      return [$user, $sticky, $pass];
1448  }
1449  
1450  //Setup VIM: ex: et ts=2 :