Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.
/auth/ldap/ -> auth.php (source)

Differences Between: [Versions 310 and 311] [Versions 311 and 400] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403] [Versions 39 and 311]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * Authentication Plugin: LDAP Authentication
  19   * Authentication using LDAP (Lightweight Directory Access Protocol).
  20   *
  21   * @package auth_ldap
  22   * @author Martin Dougiamas
  23   * @author IƱaki Arenaza
  24   * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  25   */
  26  
  27  defined('MOODLE_INTERNAL') || die();
  28  
  29  // See http://support.microsoft.com/kb/305144 to interprete these values.
  30  if (!defined('AUTH_AD_ACCOUNTDISABLE')) {
  31      define('AUTH_AD_ACCOUNTDISABLE', 0x0002);
  32  }
  33  if (!defined('AUTH_AD_NORMAL_ACCOUNT')) {
  34      define('AUTH_AD_NORMAL_ACCOUNT', 0x0200);
  35  }
  36  if (!defined('AUTH_NTLMTIMEOUT')) {  // timewindow for the NTLM SSO process, in secs...
  37      define('AUTH_NTLMTIMEOUT', 10);
  38  }
  39  
  40  // UF_DONT_EXPIRE_PASSWD value taken from MSDN directly
  41  if (!defined('UF_DONT_EXPIRE_PASSWD')) {
  42      define ('UF_DONT_EXPIRE_PASSWD', 0x00010000);
  43  }
  44  
  45  // The Posix uid and gid of the 'nobody' account and 'nogroup' group.
  46  if (!defined('AUTH_UID_NOBODY')) {
  47      define('AUTH_UID_NOBODY', -2);
  48  }
  49  if (!defined('AUTH_GID_NOGROUP')) {
  50      define('AUTH_GID_NOGROUP', -2);
  51  }
  52  
  53  // Regular expressions for a valid NTLM username and domain name.
  54  if (!defined('AUTH_NTLM_VALID_USERNAME')) {
  55      define('AUTH_NTLM_VALID_USERNAME', '[^/\\\\\\\\\[\]:;|=,+*?<>@"]+');
  56  }
  57  if (!defined('AUTH_NTLM_VALID_DOMAINNAME')) {
  58      define('AUTH_NTLM_VALID_DOMAINNAME', '[^\\\\\\\\\/:*?"<>|]+');
  59  }
  60  // Default format for remote users if using NTLM SSO
  61  if (!defined('AUTH_NTLM_DEFAULT_FORMAT')) {
  62      define('AUTH_NTLM_DEFAULT_FORMAT', '%domain%\\%username%');
  63  }
  64  if (!defined('AUTH_NTLM_FASTPATH_ATTEMPT')) {
  65      define('AUTH_NTLM_FASTPATH_ATTEMPT', 0);
  66  }
  67  if (!defined('AUTH_NTLM_FASTPATH_YESFORM')) {
  68      define('AUTH_NTLM_FASTPATH_YESFORM', 1);
  69  }
  70  if (!defined('AUTH_NTLM_FASTPATH_YESATTEMPT')) {
  71      define('AUTH_NTLM_FASTPATH_YESATTEMPT', 2);
  72  }
  73  
  74  // Allows us to retrieve a diagnostic message in case of LDAP operation error
  75  if (!defined('LDAP_OPT_DIAGNOSTIC_MESSAGE')) {
  76      define('LDAP_OPT_DIAGNOSTIC_MESSAGE', 0x0032);
  77  }
  78  
  79  require_once($CFG->libdir.'/authlib.php');
  80  require_once($CFG->libdir.'/ldaplib.php');
  81  require_once($CFG->dirroot.'/user/lib.php');
  82  require_once($CFG->dirroot.'/auth/ldap/locallib.php');
  83  
  84  /**
  85   * LDAP authentication plugin.
  86   */
  87  class auth_plugin_ldap extends auth_plugin_base {
  88  
  89      /**
  90       * Init plugin config from database settings depending on the plugin auth type.
  91       */
  92      function init_plugin($authtype) {
  93          $this->pluginconfig = 'auth_'.$authtype;
  94          $this->config = get_config($this->pluginconfig);
  95          if (empty($this->config->ldapencoding)) {
  96              $this->config->ldapencoding = 'utf-8';
  97          }
  98          if (empty($this->config->user_type)) {
  99              $this->config->user_type = 'default';
 100          }
 101  
 102          $ldap_usertypes = ldap_supported_usertypes();
 103          $this->config->user_type_name = $ldap_usertypes[$this->config->user_type];
 104          unset($ldap_usertypes);
 105  
 106          $default = ldap_getdefaults();
 107  
 108          // Use defaults if values not given
 109          foreach ($default as $key => $value) {
 110              // watch out - 0, false are correct values too
 111              if (!isset($this->config->{$key}) or $this->config->{$key} == '') {
 112                  $this->config->{$key} = $value[$this->config->user_type];
 113              }
 114          }
 115  
 116          // Hack prefix to objectclass
 117          $this->config->objectclass = ldap_normalise_objectclass($this->config->objectclass);
 118      }
 119  
 120      /**
 121       * Constructor with initialisation.
 122       */
 123      public function __construct() {
 124          $this->authtype = 'ldap';
 125          $this->roleauth = 'auth_ldap';
 126          $this->errorlogtag = '[AUTH LDAP] ';
 127          $this->init_plugin($this->authtype);
 128      }
 129  
 130      /**
 131       * Old syntax of class constructor. Deprecated in PHP7.
 132       *
 133       * @deprecated since Moodle 3.1
 134       */
 135      public function auth_plugin_ldap() {
 136          debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
 137          self::__construct();
 138      }
 139  
 140      /**
 141       * Returns true if the username and password work and false if they are
 142       * wrong or don't exist.
 143       *
 144       * @param string $username The username (without system magic quotes)
 145       * @param string $password The password (without system magic quotes)
 146       *
 147       * @return bool Authentication success or failure.
 148       */
 149      function user_login($username, $password) {
 150          if (! function_exists('ldap_bind')) {
 151              print_error('auth_ldapnotinstalled', 'auth_ldap');
 152              return false;
 153          }
 154  
 155          if (!$username or !$password) {    // Don't allow blank usernames or passwords
 156              return false;
 157          }
 158  
 159          $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
 160          $extpassword = core_text::convert($password, 'utf-8', $this->config->ldapencoding);
 161  
 162          // Before we connect to LDAP, check if this is an AD SSO login
 163          // if we succeed in this block, we'll return success early.
 164          //
 165          $key = sesskey();
 166          if (!empty($this->config->ntlmsso_enabled) && $key === $password) {
 167              $sessusername = get_cache_flag($this->pluginconfig.'/ntlmsess', $key);
 168              // We only get the cache flag if we retrieve it before
 169              // it expires (AUTH_NTLMTIMEOUT seconds).
 170              if (empty($sessusername)) {
 171                  return false;
 172              }
 173  
 174              if ($username === $sessusername) {
 175                  unset($sessusername);
 176  
 177                  // Check that the user is inside one of the configured LDAP contexts
 178                  $validuser = false;
 179                  $ldapconnection = $this->ldap_connect();
 180                  // if the user is not inside the configured contexts,
 181                  // ldap_find_userdn returns false.
 182                  if ($this->ldap_find_userdn($ldapconnection, $extusername)) {
 183                      $validuser = true;
 184                  }
 185                  $this->ldap_close();
 186  
 187                  // Shortcut here - SSO confirmed
 188                  return $validuser;
 189              }
 190          } // End SSO processing
 191          unset($key);
 192  
 193          $ldapconnection = $this->ldap_connect();
 194          $ldap_user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
 195  
 196          // If ldap_user_dn is empty, user does not exist
 197          if (!$ldap_user_dn) {
 198              $this->ldap_close();
 199              return false;
 200          }
 201  
 202          // Try to bind with current username and password
 203          $ldap_login = @ldap_bind($ldapconnection, $ldap_user_dn, $extpassword);
 204  
 205          // If login fails and we are using MS Active Directory, retrieve the diagnostic
 206          // message to see if this is due to an expired password, or that the user is forced to
 207          // change the password on first login. If it is, only proceed if we can change
 208          // password from Moodle (otherwise we'll get stuck later in the login process).
 209          if (!$ldap_login && ($this->config->user_type == 'ad')
 210              && $this->can_change_password()
 211              && (!empty($this->config->expiration) and ($this->config->expiration == 1))) {
 212  
 213              // We need to get the diagnostic message right after the call to ldap_bind(),
 214              // before any other LDAP operation.
 215              ldap_get_option($ldapconnection, LDAP_OPT_DIAGNOSTIC_MESSAGE, $diagmsg);
 216  
 217              if ($this->ldap_ad_pwdexpired_from_diagmsg($diagmsg)) {
 218                  // If login failed because user must change the password now or the
 219                  // password has expired, let the user in. We'll catch this later in the
 220                  // login process when we explicitly check for expired passwords.
 221                  $ldap_login = true;
 222              }
 223          }
 224          $this->ldap_close();
 225          return $ldap_login;
 226      }
 227  
 228      /**
 229       * Reads user information from ldap and returns it in array()
 230       *
 231       * Function should return all information available. If you are saving
 232       * this information to moodle user-table you should honor syncronization flags
 233       *
 234       * @param string $username username
 235       *
 236       * @return mixed array with no magic quotes or false on error
 237       */
 238      function get_userinfo($username) {
 239          $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
 240  
 241          $ldapconnection = $this->ldap_connect();
 242          if(!($user_dn = $this->ldap_find_userdn($ldapconnection, $extusername))) {
 243              $this->ldap_close();
 244              return false;
 245          }
 246  
 247          $search_attribs = array();
 248          $attrmap = $this->ldap_attributes();
 249          foreach ($attrmap as $key => $values) {
 250              if (!is_array($values)) {
 251                  $values = array($values);
 252              }
 253              foreach ($values as $value) {
 254                  if (!in_array($value, $search_attribs)) {
 255                      array_push($search_attribs, $value);
 256                  }
 257              }
 258          }
 259  
 260          if (!$user_info_result = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs)) {
 261              $this->ldap_close();
 262              return false; // error!
 263          }
 264  
 265          $user_entry = ldap_get_entries_moodle($ldapconnection, $user_info_result);
 266          if (empty($user_entry)) {
 267              $this->ldap_close();
 268              return false; // entry not found
 269          }
 270  
 271          $result = array();
 272          foreach ($attrmap as $key => $values) {
 273              if (!is_array($values)) {
 274                  $values = array($values);
 275              }
 276              $ldapval = NULL;
 277              foreach ($values as $value) {
 278                  $entry = $user_entry[0];
 279                  if (($value == 'dn') || ($value == 'distinguishedname')) {
 280                      $result[$key] = $user_dn;
 281                      continue;
 282                  }
 283                  if (!array_key_exists($value, $entry)) {
 284                      continue; // wrong data mapping!
 285                  }
 286                  if (is_array($entry[$value])) {
 287                      $newval = core_text::convert($entry[$value][0], $this->config->ldapencoding, 'utf-8');
 288                  } else {
 289                      $newval = core_text::convert($entry[$value], $this->config->ldapencoding, 'utf-8');
 290                  }
 291                  if (!empty($newval)) { // favour ldap entries that are set
 292                      $ldapval = $newval;
 293                  }
 294              }
 295              if (!is_null($ldapval)) {
 296                  $result[$key] = $ldapval;
 297              }
 298          }
 299  
 300          $this->ldap_close();
 301          return $result;
 302      }
 303  
 304      /**
 305       * Reads user information from ldap and returns it in an object
 306       *
 307       * @param string $username username (with system magic quotes)
 308       * @return mixed object or false on error
 309       */
 310      function get_userinfo_asobj($username) {
 311          $user_array = $this->get_userinfo($username);
 312          if ($user_array == false) {
 313              return false; //error or not found
 314          }
 315          $user_array = truncate_userinfo($user_array);
 316          $user = new stdClass();
 317          foreach ($user_array as $key=>$value) {
 318              $user->{$key} = $value;
 319          }
 320          return $user;
 321      }
 322  
 323      /**
 324       * Returns all usernames from LDAP
 325       *
 326       * get_userlist returns all usernames from LDAP
 327       *
 328       * @return array
 329       */
 330      function get_userlist() {
 331          return $this->ldap_get_userlist("({$this->config->user_attribute}=*)");
 332      }
 333  
 334      /**
 335       * Checks if user exists on LDAP
 336       *
 337       * @param string $username
 338       */
 339      function user_exists($username) {
 340          $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
 341  
 342          // Returns true if given username exists on ldap
 343          $users = $this->ldap_get_userlist('('.$this->config->user_attribute.'='.ldap_filter_addslashes($extusername).')');
 344          return count($users);
 345      }
 346  
 347      /**
 348       * Creates a new user on LDAP.
 349       * By using information in userobject
 350       * Use user_exists to prevent duplicate usernames
 351       *
 352       * @param mixed $userobject  Moodle userobject
 353       * @param mixed $plainpass   Plaintext password
 354       */
 355      function user_create($userobject, $plainpass) {
 356          $extusername = core_text::convert($userobject->username, 'utf-8', $this->config->ldapencoding);
 357          $extpassword = core_text::convert($plainpass, 'utf-8', $this->config->ldapencoding);
 358  
 359          switch ($this->config->passtype) {
 360              case 'md5':
 361                  $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
 362                  break;
 363              case 'sha1':
 364                  $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
 365                  break;
 366              case 'plaintext':
 367              default:
 368                  break; // plaintext
 369          }
 370  
 371          $ldapconnection = $this->ldap_connect();
 372          $attrmap = $this->ldap_attributes();
 373  
 374          $newuser = array();
 375  
 376          foreach ($attrmap as $key => $values) {
 377              if (!is_array($values)) {
 378                  $values = array($values);
 379              }
 380              foreach ($values as $value) {
 381                  if (!empty($userobject->$key) ) {
 382                      $newuser[$value] = core_text::convert($userobject->$key, 'utf-8', $this->config->ldapencoding);
 383                  }
 384              }
 385          }
 386  
 387          //Following sets all mandatory and other forced attribute values
 388          //User should be creted as login disabled untill email confirmation is processed
 389          //Feel free to add your user type and send patches to paca@sci.fi to add them
 390          //Moodle distribution
 391  
 392          switch ($this->config->user_type)  {
 393              case 'edir':
 394                  $newuser['objectClass']   = array('inetOrgPerson', 'organizationalPerson', 'person', 'top');
 395                  $newuser['uniqueId']      = $extusername;
 396                  $newuser['logindisabled'] = 'TRUE';
 397                  $newuser['userpassword']  = $extpassword;
 398                  $uadd = ldap_add($ldapconnection, $this->config->user_attribute.'='.ldap_addslashes($extusername).','.$this->config->create_context, $newuser);
 399                  break;
 400              case 'rfc2307':
 401              case 'rfc2307bis':
 402                  // posixAccount object class forces us to specify a uidNumber
 403                  // and a gidNumber. That is quite complicated to generate from
 404                  // Moodle without colliding with existing numbers and without
 405                  // race conditions. As this user is supposed to be only used
 406                  // with Moodle (otherwise the user would exist beforehand) and
 407                  // doesn't need to login into a operating system, we assign the
 408                  // user the uid of user 'nobody' and gid of group 'nogroup'. In
 409                  // addition to that, we need to specify a home directory. We
 410                  // use the root directory ('/') as the home directory, as this
 411                  // is the only one can always be sure exists. Finally, even if
 412                  // it's not mandatory, we specify '/bin/false' as the login
 413                  // shell, to prevent the user from login in at the operating
 414                  // system level (Moodle ignores this).
 415  
 416                  $newuser['objectClass']   = array('posixAccount', 'inetOrgPerson', 'organizationalPerson', 'person', 'top');
 417                  $newuser['cn']            = $extusername;
 418                  $newuser['uid']           = $extusername;
 419                  $newuser['uidNumber']     = AUTH_UID_NOBODY;
 420                  $newuser['gidNumber']     = AUTH_GID_NOGROUP;
 421                  $newuser['homeDirectory'] = '/';
 422                  $newuser['loginShell']    = '/bin/false';
 423  
 424                  // IMPORTANT:
 425                  // We have to create the account locked, but posixAccount has
 426                  // no attribute to achive this reliably. So we are going to
 427                  // modify the password in a reversable way that we can later
 428                  // revert in user_activate().
 429                  //
 430                  // Beware that this can be defeated by the user if we are not
 431                  // using MD5 or SHA-1 passwords. After all, the source code of
 432                  // Moodle is available, and the user can see the kind of
 433                  // modification we are doing and 'undo' it by hand (but only
 434                  // if we are using plain text passwords).
 435                  //
 436                  // Also bear in mind that you need to use a binding user that
 437                  // can create accounts and has read/write privileges on the
 438                  // 'userPassword' attribute for this to work.
 439  
 440                  $newuser['userPassword']  = '*'.$extpassword;
 441                  $uadd = ldap_add($ldapconnection, $this->config->user_attribute.'='.ldap_addslashes($extusername).','.$this->config->create_context, $newuser);
 442                  break;
 443              case 'ad':
 444                  // User account creation is a two step process with AD. First you
 445                  // create the user object, then you set the password. If you try
 446                  // to set the password while creating the user, the operation
 447                  // fails.
 448  
 449                  // Passwords in Active Directory must be encoded as Unicode
 450                  // strings (UCS-2 Little Endian format) and surrounded with
 451                  // double quotes. See http://support.microsoft.com/?kbid=269190
 452                  if (!function_exists('mb_convert_encoding')) {
 453                      print_error('auth_ldap_no_mbstring', 'auth_ldap');
 454                  }
 455  
 456                  // Check for invalid sAMAccountName characters.
 457                  if (preg_match('#[/\\[\]:;|=,+*?<>@"]#', $extusername)) {
 458                      print_error ('auth_ldap_ad_invalidchars', 'auth_ldap');
 459                  }
 460  
 461                  // First create the user account, and mark it as disabled.
 462                  $newuser['objectClass'] = array('top', 'person', 'user', 'organizationalPerson');
 463                  $newuser['sAMAccountName'] = $extusername;
 464                  $newuser['userAccountControl'] = AUTH_AD_NORMAL_ACCOUNT |
 465                                                   AUTH_AD_ACCOUNTDISABLE;
 466                  $userdn = 'cn='.ldap_addslashes($extusername).','.$this->config->create_context;
 467                  if (!ldap_add($ldapconnection, $userdn, $newuser)) {
 468                      print_error('auth_ldap_ad_create_req', 'auth_ldap');
 469                  }
 470  
 471                  // Now set the password
 472                  unset($newuser);
 473                  $newuser['unicodePwd'] = mb_convert_encoding('"' . $extpassword . '"',
 474                                                               'UCS-2LE', 'UTF-8');
 475                  if(!ldap_modify($ldapconnection, $userdn, $newuser)) {
 476                      // Something went wrong: delete the user account and error out
 477                      ldap_delete ($ldapconnection, $userdn);
 478                      print_error('auth_ldap_ad_create_req', 'auth_ldap');
 479                  }
 480                  $uadd = true;
 481                  break;
 482              default:
 483                 print_error('auth_ldap_unsupportedusertype', 'auth_ldap', '', $this->config->user_type_name);
 484          }
 485          $this->ldap_close();
 486          return $uadd;
 487      }
 488  
 489      /**
 490       * Returns true if plugin allows resetting of password from moodle.
 491       *
 492       * @return bool
 493       */
 494      function can_reset_password() {
 495          return !empty($this->config->stdchangepassword);
 496      }
 497  
 498      /**
 499       * Returns true if plugin can be manually set.
 500       *
 501       * @return bool
 502       */
 503      function can_be_manually_set() {
 504          return true;
 505      }
 506  
 507      /**
 508       * Returns true if plugin allows signup and user creation.
 509       *
 510       * @return bool
 511       */
 512      function can_signup() {
 513          return (!empty($this->config->auth_user_create) and !empty($this->config->create_context));
 514      }
 515  
 516      /**
 517       * Sign up a new user ready for confirmation.
 518       * Password is passed in plaintext.
 519       *
 520       * @param object $user new user object
 521       * @param boolean $notify print notice with link and terminate
 522       * @return boolean success
 523       */
 524      function user_signup($user, $notify=true) {
 525          global $CFG, $DB, $PAGE, $OUTPUT;
 526  
 527          require_once($CFG->dirroot.'/user/profile/lib.php');
 528          require_once($CFG->dirroot.'/user/lib.php');
 529  
 530          if ($this->user_exists($user->username)) {
 531              print_error('auth_ldap_user_exists', 'auth_ldap');
 532          }
 533  
 534          $plainslashedpassword = $user->password;
 535          unset($user->password);
 536  
 537          if (! $this->user_create($user, $plainslashedpassword)) {
 538              print_error('auth_ldap_create_error', 'auth_ldap');
 539          }
 540  
 541          $user->id = user_create_user($user, false, false);
 542  
 543          user_add_password_history($user->id, $plainslashedpassword);
 544  
 545          // Save any custom profile field information
 546          profile_save_data($user);
 547  
 548          $userinfo = $this->get_userinfo($user->username);
 549          $this->update_user_record($user->username, false, false, $this->is_user_suspended((object) $userinfo));
 550  
 551          // This will also update the stored hash to the latest algorithm
 552          // if the existing hash is using an out-of-date algorithm (or the
 553          // legacy md5 algorithm).
 554          update_internal_user_password($user, $plainslashedpassword);
 555  
 556          $user = $DB->get_record('user', array('id'=>$user->id));
 557  
 558          \core\event\user_created::create_from_userid($user->id)->trigger();
 559  
 560          if (! send_confirmation_email($user)) {
 561              print_error('noemail', 'auth_ldap');
 562          }
 563  
 564          if ($notify) {
 565              $emailconfirm = get_string('emailconfirm');
 566              $PAGE->set_url('/auth/ldap/auth.php');
 567              $PAGE->navbar->add($emailconfirm);
 568              $PAGE->set_title($emailconfirm);
 569              $PAGE->set_heading($emailconfirm);
 570              echo $OUTPUT->header();
 571              notice(get_string('emailconfirmsent', '', $user->email), "{$CFG->wwwroot}/index.php");
 572          } else {
 573              return true;
 574          }
 575      }
 576  
 577      /**
 578       * Returns true if plugin allows confirming of new users.
 579       *
 580       * @return bool
 581       */
 582      function can_confirm() {
 583          return $this->can_signup();
 584      }
 585  
 586      /**
 587       * Confirm the new user as registered.
 588       *
 589       * @param string $username
 590       * @param string $confirmsecret
 591       */
 592      function user_confirm($username, $confirmsecret) {
 593          global $DB;
 594  
 595          $user = get_complete_user_data('username', $username);
 596  
 597          if (!empty($user)) {
 598              if ($user->auth != $this->authtype) {
 599                  return AUTH_CONFIRM_ERROR;
 600  
 601              } else if ($user->secret === $confirmsecret && $user->confirmed) {
 602                  return AUTH_CONFIRM_ALREADY;
 603  
 604              } else if ($user->secret === $confirmsecret) {   // They have provided the secret key to get in
 605                  if (!$this->user_activate($username)) {
 606                      return AUTH_CONFIRM_FAIL;
 607                  }
 608                  $user->confirmed = 1;
 609                  user_update_user($user, false);
 610                  return AUTH_CONFIRM_OK;
 611              }
 612          } else {
 613              return AUTH_CONFIRM_ERROR;
 614          }
 615      }
 616  
 617      /**
 618       * Return number of days to user password expires
 619       *
 620       * If userpassword does not expire it should return 0. If password is already expired
 621       * it should return negative value.
 622       *
 623       * @param mixed $username username
 624       * @return integer
 625       */
 626      function password_expire($username) {
 627          $result = 0;
 628  
 629          $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
 630  
 631          $ldapconnection = $this->ldap_connect();
 632          $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
 633          $search_attribs = array($this->config->expireattr);
 634          $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
 635          if ($sr)  {
 636              $info = ldap_get_entries_moodle($ldapconnection, $sr);
 637              if (!empty ($info)) {
 638                  $info = $info[0];
 639                  if (isset($info[$this->config->expireattr][0])) {
 640                      $expiretime = $this->ldap_expirationtime2unix($info[$this->config->expireattr][0], $ldapconnection, $user_dn);
 641                      if ($expiretime != 0) {
 642                          $now = time();
 643                          if ($expiretime > $now) {
 644                              $result = ceil(($expiretime - $now) / DAYSECS);
 645                          } else {
 646                              $result = floor(($expiretime - $now) / DAYSECS);
 647                          }
 648                      }
 649                  }
 650              }
 651          } else {
 652              error_log($this->errorlogtag.get_string('didtfindexpiretime', 'auth_ldap'));
 653          }
 654  
 655          return $result;
 656      }
 657  
 658      /**
 659       * Syncronizes user fron external LDAP server to moodle user table
 660       *
 661       * Sync is now using username attribute.
 662       *
 663       * Syncing users removes or suspends users that dont exists anymore in external LDAP.
 664       * Creates new users and updates coursecreator status of users.
 665       *
 666       * @param bool $do_updates will do pull in data updates from LDAP if relevant
 667       */
 668      function sync_users($do_updates=true) {
 669          global $CFG, $DB;
 670  
 671          require_once($CFG->dirroot . '/user/profile/lib.php');
 672  
 673          print_string('connectingldap', 'auth_ldap');
 674          $ldapconnection = $this->ldap_connect();
 675  
 676          $dbman = $DB->get_manager();
 677  
 678      /// Define table user to be created
 679          $table = new xmldb_table('tmp_extuser');
 680          $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
 681          $table->add_field('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
 682          $table->add_field('mnethostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
 683          $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
 684          $table->add_index('username', XMLDB_INDEX_UNIQUE, array('mnethostid', 'username'));
 685  
 686          print_string('creatingtemptable', 'auth_ldap', 'tmp_extuser');
 687          $dbman->create_temp_table($table);
 688  
 689          ////
 690          //// get user's list from ldap to sql in a scalable fashion
 691          ////
 692          // prepare some data we'll need
 693          $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
 694          $servercontrols = array();
 695  
 696          $contexts = explode(';', $this->config->contexts);
 697  
 698          if (!empty($this->config->create_context)) {
 699              array_push($contexts, $this->config->create_context);
 700          }
 701  
 702          $ldappagedresults = ldap_paged_results_supported($this->config->ldap_version, $ldapconnection);
 703          $ldapcookie = '';
 704          foreach ($contexts as $context) {
 705              $context = trim($context);
 706              if (empty($context)) {
 707                  continue;
 708              }
 709  
 710              do {
 711                  if ($ldappagedresults) {
 712                      $servercontrols = array(array(
 713                          'oid' => LDAP_CONTROL_PAGEDRESULTS, 'value' => array(
 714                              'size' => $this->config->pagesize, 'cookie' => $ldapcookie)));
 715                  }
 716                  if ($this->config->search_sub) {
 717                      // Use ldap_search to find first user from subtree.
 718                      $ldapresult = ldap_search($ldapconnection, $context, $filter, array($this->config->user_attribute),
 719                          0, -1, -1, LDAP_DEREF_NEVER, $servercontrols);
 720                  } else {
 721                      // Search only in this context.
 722                      $ldapresult = ldap_list($ldapconnection, $context, $filter, array($this->config->user_attribute),
 723                          0, -1, -1, LDAP_DEREF_NEVER, $servercontrols);
 724                  }
 725                  if (!$ldapresult) {
 726                      continue;
 727                  }
 728                  if ($ldappagedresults) {
 729                      // Get next server cookie to know if we'll need to continue searching.
 730                      $ldapcookie = '';
 731                      // Get next cookie from controls.
 732                      ldap_parse_result($ldapconnection, $ldapresult, $errcode, $matcheddn,
 733                          $errmsg, $referrals, $controls);
 734                      if (isset($controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'])) {
 735                          $ldapcookie = $controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'];
 736                      }
 737                  }
 738                  if ($entry = @ldap_first_entry($ldapconnection, $ldapresult)) {
 739                      do {
 740                          $value = ldap_get_values_len($ldapconnection, $entry, $this->config->user_attribute);
 741                          $value = core_text::convert($value[0], $this->config->ldapencoding, 'utf-8');
 742                          $value = trim($value);
 743                          $this->ldap_bulk_insert($value);
 744                      } while ($entry = ldap_next_entry($ldapconnection, $entry));
 745                  }
 746                  unset($ldapresult); // Free mem.
 747              } while ($ldappagedresults && $ldapcookie !== null && $ldapcookie != '');
 748          }
 749  
 750          // If LDAP paged results were used, the current connection must be completely
 751          // closed and a new one created, to work without paged results from here on.
 752          if ($ldappagedresults) {
 753              $this->ldap_close(true);
 754              $ldapconnection = $this->ldap_connect();
 755          }
 756  
 757          /// preserve our user database
 758          /// if the temp table is empty, it probably means that something went wrong, exit
 759          /// so as to avoid mass deletion of users; which is hard to undo
 760          $count = $DB->count_records_sql('SELECT COUNT(username) AS count, 1 FROM {tmp_extuser}');
 761          if ($count < 1) {
 762              print_string('didntgetusersfromldap', 'auth_ldap');
 763              $dbman->drop_table($table);
 764              $this->ldap_close();
 765              return false;
 766          } else {
 767              print_string('gotcountrecordsfromldap', 'auth_ldap', $count);
 768          }
 769  
 770  
 771  /// User removal
 772          // Find users in DB that aren't in ldap -- to be removed!
 773          // this is still not as scalable (but how often do we mass delete?)
 774  
 775          if ($this->config->removeuser == AUTH_REMOVEUSER_FULLDELETE) {
 776              $sql = "SELECT u.*
 777                        FROM {user} u
 778                   LEFT JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
 779                       WHERE u.auth = :auth
 780                             AND u.deleted = 0
 781                             AND e.username IS NULL";
 782              $remove_users = $DB->get_records_sql($sql, array('auth'=>$this->authtype));
 783  
 784              if (!empty($remove_users)) {
 785                  print_string('userentriestoremove', 'auth_ldap', count($remove_users));
 786                  foreach ($remove_users as $user) {
 787                      if (delete_user($user)) {
 788                          echo "\t"; print_string('auth_dbdeleteuser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
 789                      } else {
 790                          echo "\t"; print_string('auth_dbdeleteusererror', 'auth_db', $user->username); echo "\n";
 791                      }
 792                  }
 793              } else {
 794                  print_string('nouserentriestoremove', 'auth_ldap');
 795              }
 796              unset($remove_users); // Free mem!
 797  
 798          } else if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
 799              $sql = "SELECT u.*
 800                        FROM {user} u
 801                   LEFT JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
 802                       WHERE u.auth = :auth
 803                             AND u.deleted = 0
 804                             AND u.suspended = 0
 805                             AND e.username IS NULL";
 806              $remove_users = $DB->get_records_sql($sql, array('auth'=>$this->authtype));
 807  
 808              if (!empty($remove_users)) {
 809                  print_string('userentriestoremove', 'auth_ldap', count($remove_users));
 810  
 811                  foreach ($remove_users as $user) {
 812                      $updateuser = new stdClass();
 813                      $updateuser->id = $user->id;
 814                      $updateuser->suspended = 1;
 815                      user_update_user($updateuser, false);
 816                      echo "\t"; print_string('auth_dbsuspenduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
 817                      \core\session\manager::kill_user_sessions($user->id);
 818                  }
 819              } else {
 820                  print_string('nouserentriestoremove', 'auth_ldap');
 821              }
 822              unset($remove_users); // Free mem!
 823          }
 824  
 825  /// Revive suspended users
 826          if (!empty($this->config->removeuser) and $this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
 827              $sql = "SELECT u.id, u.username
 828                        FROM {user} u
 829                        JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
 830                       WHERE (u.auth = 'nologin' OR (u.auth = ? AND u.suspended = 1)) AND u.deleted = 0";
 831              // Note: 'nologin' is there for backwards compatibility.
 832              $revive_users = $DB->get_records_sql($sql, array($this->authtype));
 833  
 834              if (!empty($revive_users)) {
 835                  print_string('userentriestorevive', 'auth_ldap', count($revive_users));
 836  
 837                  foreach ($revive_users as $user) {
 838                      $updateuser = new stdClass();
 839                      $updateuser->id = $user->id;
 840                      $updateuser->auth = $this->authtype;
 841                      $updateuser->suspended = 0;
 842                      user_update_user($updateuser, false);
 843                      echo "\t"; print_string('auth_dbreviveduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
 844                  }
 845              } else {
 846                  print_string('nouserentriestorevive', 'auth_ldap');
 847              }
 848  
 849              unset($revive_users);
 850          }
 851  
 852  
 853  /// User Updates - time-consuming (optional)
 854          if ($do_updates) {
 855              // Narrow down what fields we need to update
 856              $updatekeys = $this->get_profile_keys();
 857  
 858          } else {
 859              print_string('noupdatestobedone', 'auth_ldap');
 860          }
 861          if ($do_updates and !empty($updatekeys)) { // run updates only if relevant
 862              $users = $DB->get_records_sql('SELECT u.username, u.id
 863                                               FROM {user} u
 864                                              WHERE u.deleted = 0 AND u.auth = ? AND u.mnethostid = ?',
 865                                            array($this->authtype, $CFG->mnet_localhost_id));
 866              if (!empty($users)) {
 867                  print_string('userentriestoupdate', 'auth_ldap', count($users));
 868  
 869                  foreach ($users as $user) {
 870                      $transaction = $DB->start_delegated_transaction();
 871                      echo "\t"; print_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id));
 872                      $userinfo = $this->get_userinfo($user->username);
 873                      if (!$this->update_user_record($user->username, $updatekeys, true,
 874                              $this->is_user_suspended((object) $userinfo))) {
 875                          echo ' - '.get_string('skipped');
 876                      }
 877                      echo "\n";
 878  
 879                      // Update system roles, if needed.
 880                      $this->sync_roles($user);
 881                      $transaction->allow_commit();
 882                  }
 883                  unset($users); // free mem
 884              }
 885          } else { // end do updates
 886              print_string('noupdatestobedone', 'auth_ldap');
 887          }
 888  
 889  /// User Additions
 890          // Find users missing in DB that are in LDAP
 891          // and gives me a nifty object I don't want.
 892          // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
 893          $sql = 'SELECT e.id, e.username
 894                    FROM {tmp_extuser} e
 895                    LEFT JOIN {user} u ON (e.username = u.username AND e.mnethostid = u.mnethostid)
 896                   WHERE u.id IS NULL';
 897          $add_users = $DB->get_records_sql($sql);
 898  
 899          if (!empty($add_users)) {
 900              print_string('userentriestoadd', 'auth_ldap', count($add_users));
 901  
 902              foreach ($add_users as $user) {
 903                  $transaction = $DB->start_delegated_transaction();
 904                  $user = $this->get_userinfo_asobj($user->username);
 905  
 906                  // Prep a few params
 907                  $user->modified   = time();
 908                  $user->confirmed  = 1;
 909                  $user->auth       = $this->authtype;
 910                  $user->mnethostid = $CFG->mnet_localhost_id;
 911                  // get_userinfo_asobj() might have replaced $user->username with the value
 912                  // from the LDAP server (which can be mixed-case). Make sure it's lowercase
 913                  $user->username = trim(core_text::strtolower($user->username));
 914                  // It isn't possible to just rely on the configured suspension attribute since
 915                  // things like active directory use bit masks, other things using LDAP might
 916                  // do different stuff as well.
 917                  //
 918                  // The cast to int is a workaround for MDL-53959.
 919                  $user->suspended = (int)$this->is_user_suspended($user);
 920  
 921                  if (empty($user->calendartype)) {
 922                      $user->calendartype = $CFG->calendartype;
 923                  }
 924  
 925                  $id = user_create_user($user, false);
 926                  echo "\t"; print_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username, 'id'=>$id)); echo "\n";
 927                  $euser = $DB->get_record('user', array('id' => $id));
 928  
 929                  if (!empty($this->config->forcechangepassword)) {
 930                      set_user_preference('auth_forcepasswordchange', 1, $id);
 931                  }
 932  
 933                  // Save custom profile fields.
 934                  $this->update_user_record($user->username, $this->get_profile_keys(true), false);
 935  
 936                  // Add roles if needed.
 937                  $this->sync_roles($euser);
 938                  $transaction->allow_commit();
 939              }
 940              unset($add_users); // free mem
 941          } else {
 942              print_string('nouserstobeadded', 'auth_ldap');
 943          }
 944  
 945          $dbman->drop_table($table);
 946          $this->ldap_close();
 947  
 948          return true;
 949      }
 950  
 951      /**
 952       * Bulk insert in SQL's temp table
 953       */
 954      function ldap_bulk_insert($username) {
 955          global $DB, $CFG;
 956  
 957          $username = core_text::strtolower($username); // usernames are __always__ lowercase.
 958          $DB->insert_record_raw('tmp_extuser', array('username'=>$username,
 959                                                      'mnethostid'=>$CFG->mnet_localhost_id), false, true);
 960          echo '.';
 961      }
 962  
 963      /**
 964       * Activates (enables) user in external LDAP so user can login
 965       *
 966       * @param mixed $username
 967       * @return boolean result
 968       */
 969      function user_activate($username) {
 970          $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
 971  
 972          $ldapconnection = $this->ldap_connect();
 973  
 974          $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
 975          switch ($this->config->user_type)  {
 976              case 'edir':
 977                  $newinfo['loginDisabled'] = 'FALSE';
 978                  break;
 979              case 'rfc2307':
 980              case 'rfc2307bis':
 981                  // Remember that we add a '*' character in front of the
 982                  // external password string to 'disable' the account. We just
 983                  // need to remove it.
 984                  $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
 985                                  array('userPassword'));
 986                  $info = ldap_get_entries($ldapconnection, $sr);
 987                  $info[0] = array_change_key_case($info[0], CASE_LOWER);
 988                  $newinfo['userPassword'] = ltrim($info[0]['userpassword'][0], '*');
 989                  break;
 990              case 'ad':
 991                  // We need to unset the ACCOUNTDISABLE bit in the
 992                  // userAccountControl attribute ( see
 993                  // http://support.microsoft.com/kb/305144 )
 994                  $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
 995                                  array('userAccountControl'));
 996                  $info = ldap_get_entries($ldapconnection, $sr);
 997                  $info[0] = array_change_key_case($info[0], CASE_LOWER);
 998                  $newinfo['userAccountControl'] = $info[0]['useraccountcontrol'][0]
 999                                                   & (~AUTH_AD_ACCOUNTDISABLE);
1000                  break;
1001              default:
1002                  print_error('user_activatenotsupportusertype', 'auth_ldap', '', $this->config->user_type_name);
1003          }
1004          $result = ldap_modify($ldapconnection, $userdn, $newinfo);
1005          $this->ldap_close();
1006          return $result;
1007      }
1008  
1009      /**
1010       * Returns true if user should be coursecreator.
1011       *
1012       * @param mixed $username    username (without system magic quotes)
1013       * @return mixed result      null if course creators is not configured, boolean otherwise.
1014       *
1015       * @deprecated since Moodle 3.4 MDL-30634 - please do not use this function any more.
1016       */
1017      function iscreator($username) {
1018          debugging('iscreator() is deprecated. Please use auth_plugin_ldap::is_role() instead.', DEBUG_DEVELOPER);
1019  
1020          if (empty($this->config->creators) or empty($this->config->memberattribute)) {
1021              return null;
1022          }
1023  
1024          $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
1025  
1026          $ldapconnection = $this->ldap_connect();
1027  
1028          if ($this->config->memberattribute_isdn) {
1029              if(!($userid = $this->ldap_find_userdn($ldapconnection, $extusername))) {
1030                  return false;
1031              }
1032          } else {
1033              $userid = $extusername;
1034          }
1035  
1036          $group_dns = explode(';', $this->config->creators);
1037          $creator = ldap_isgroupmember($ldapconnection, $userid, $group_dns, $this->config->memberattribute);
1038  
1039          $this->ldap_close();
1040  
1041          return $creator;
1042      }
1043  
1044      /**
1045       * Check if user has LDAP group membership.
1046       *
1047       * Returns true if user should be assigned role.
1048       *
1049       * @param mixed $username username (without system magic quotes).
1050       * @param array $role Array of role's shortname, localname, and settingname for the config value.
1051       * @return mixed result null if role/LDAP context is not configured, boolean otherwise.
1052       */
1053      private function is_role($username, $role) {
1054          if (empty($this->config->{$role['settingname']}) or empty($this->config->memberattribute)) {
1055              return null;
1056          }
1057  
1058          $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
1059  
1060          $ldapconnection = $this->ldap_connect();
1061  
1062          if ($this->config->memberattribute_isdn) {
1063              if (!($userid = $this->ldap_find_userdn($ldapconnection, $extusername))) {
1064                  return false;
1065              }
1066          } else {
1067              $userid = $extusername;
1068          }
1069  
1070          $groupdns = explode(';', $this->config->{$role['settingname']});
1071          $isrole = ldap_isgroupmember($ldapconnection, $userid, $groupdns, $this->config->memberattribute);
1072  
1073          $this->ldap_close();
1074  
1075          return $isrole;
1076      }
1077  
1078      /**
1079       * Called when the user record is updated.
1080       *
1081       * Modifies user in external LDAP server. It takes olduser (before
1082       * changes) and newuser (after changes) compares information and
1083       * saves modified information to external LDAP server.
1084       *
1085       * @param mixed $olduser     Userobject before modifications    (without system magic quotes)
1086       * @param mixed $newuser     Userobject new modified userobject (without system magic quotes)
1087       * @return boolean result
1088       *
1089       */
1090      function user_update($olduser, $newuser) {
1091          global $CFG;
1092  
1093          require_once($CFG->dirroot . '/user/profile/lib.php');
1094  
1095          if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
1096              error_log($this->errorlogtag.get_string('renamingnotallowed', 'auth_ldap'));
1097              return false;
1098          }
1099  
1100          if (isset($olduser->auth) and $olduser->auth != $this->authtype) {
1101              return true; // just change auth and skip update
1102          }
1103  
1104          $attrmap = $this->ldap_attributes();
1105          // Before doing anything else, make sure we really need to update anything
1106          // in the external LDAP server.
1107          $update_external = false;
1108          foreach ($attrmap as $key => $ldapkeys) {
1109              if (!empty($this->config->{'field_updateremote_'.$key})) {
1110                  $update_external = true;
1111                  break;
1112              }
1113          }
1114          if (!$update_external) {
1115              return true;
1116          }
1117  
1118          $extoldusername = core_text::convert($olduser->username, 'utf-8', $this->config->ldapencoding);
1119  
1120          $ldapconnection = $this->ldap_connect();
1121  
1122          $search_attribs = array();
1123          foreach ($attrmap as $key => $values) {
1124              if (!is_array($values)) {
1125                  $values = array($values);
1126              }
1127              foreach ($values as $value) {
1128                  if (!in_array($value, $search_attribs)) {
1129                      array_push($search_attribs, $value);
1130                  }
1131              }
1132          }
1133  
1134          if(!($user_dn = $this->ldap_find_userdn($ldapconnection, $extoldusername))) {
1135              return false;
1136          }
1137  
1138          // Load old custom fields.
1139          $olduserprofilefields = (array) profile_user_record($olduser->id, false);
1140  
1141          $fields = array();
1142          foreach (profile_get_custom_fields(false) as $field) {
1143              $fields[$field->shortname] = $field;
1144          }
1145  
1146          $success = true;
1147          $user_info_result = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
1148          if ($user_info_result) {
1149              $user_entry = ldap_get_entries_moodle($ldapconnection, $user_info_result);
1150              if (empty($user_entry)) {
1151                  $attribs = join (', ', $search_attribs);
1152                  error_log($this->errorlogtag.get_string('updateusernotfound', 'auth_ldap',
1153                                                            array('userdn'=>$user_dn,
1154                                                                  'attribs'=>$attribs)));
1155                  return false; // old user not found!
1156              } else if (count($user_entry) > 1) {
1157                  error_log($this->errorlogtag.get_string('morethanoneuser', 'auth_ldap'));
1158                  return false;
1159              }
1160  
1161              $user_entry = $user_entry[0];
1162  
1163              foreach ($attrmap as $key => $ldapkeys) {
1164                  if (preg_match('/^profile_field_(.*)$/', $key, $match)) {
1165                      // Custom field.
1166                      $fieldname = $match[1];
1167                      if (isset($fields[$fieldname])) {
1168                          $class = 'profile_field_' . $fields[$fieldname]->datatype;
1169                          $formfield = new $class($fields[$fieldname]->id, $olduser->id);
1170                          $oldvalue = isset($olduserprofilefields[$fieldname]) ? $olduserprofilefields[$fieldname] : null;
1171                      } else {
1172                          $oldvalue = null;
1173                      }
1174                      $newvalue = $formfield->edit_save_data_preprocess($newuser->{$formfield->inputname}, new stdClass);
1175                  } else {
1176                      // Standard field.
1177                      $oldvalue = isset($olduser->$key) ? $olduser->$key : null;
1178                      $newvalue = isset($newuser->$key) ? $newuser->$key : null;
1179                  }
1180  
1181                  if ($newvalue !== null and $newvalue !== $oldvalue and !empty($this->config->{'field_updateremote_' . $key})) {
1182                      // For ldap values that could be in more than one
1183                      // ldap key, we will do our best to match
1184                      // where they came from
1185                      $ambiguous = true;
1186                      $changed   = false;
1187                      if (!is_array($ldapkeys)) {
1188                          $ldapkeys = array($ldapkeys);
1189                      }
1190                      if (count($ldapkeys) < 2) {
1191                          $ambiguous = false;
1192                      }
1193  
1194                      $nuvalue = core_text::convert($newvalue, 'utf-8', $this->config->ldapencoding);
1195                      empty($nuvalue) ? $nuvalue = array() : $nuvalue;
1196                      $ouvalue = core_text::convert($oldvalue, 'utf-8', $this->config->ldapencoding);
1197                      foreach ($ldapkeys as $ldapkey) {
1198                          // If the field is empty in LDAP there are two options:
1199                          // 1. We get the LDAP field using ldap_first_attribute.
1200                          // 2. LDAP don't send the field using  ldap_first_attribute.
1201                          // So, for option 1 we check the if the field is retrieve it.
1202                          // And get the original value of field in LDAP if the field.
1203                          // Otherwise, let value in blank and delegate the check in ldap_modify.
1204                          if (isset($user_entry[$ldapkey][0])) {
1205                              $ldapvalue = $user_entry[$ldapkey][0];
1206                          } else {
1207                              $ldapvalue = '';
1208                          }
1209  
1210                          if (!$ambiguous) {
1211                              // Skip update if the values already match
1212                              if ($nuvalue !== $ldapvalue) {
1213                                  // This might fail due to schema validation
1214                                  if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1215                                      $changed = true;
1216                                      continue;
1217                                  } else {
1218                                      $success = false;
1219                                      error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1220                                                                               array('errno'=>ldap_errno($ldapconnection),
1221                                                                                     'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1222                                                                                     'key'=>$key,
1223                                                                                     'ouvalue'=>$ouvalue,
1224                                                                                     'nuvalue'=>$nuvalue)));
1225                                      continue;
1226                                  }
1227                              }
1228                          } else {
1229                              // Ambiguous. Value empty before in Moodle (and LDAP) - use
1230                              // 1st ldap candidate field, no need to guess
1231                              if ($ouvalue === '') { // value empty before - use 1st ldap candidate
1232                                  // This might fail due to schema validation
1233                                  if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1234                                      $changed = true;
1235                                      continue;
1236                                  } else {
1237                                      $success = false;
1238                                      error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1239                                                                               array('errno'=>ldap_errno($ldapconnection),
1240                                                                                     'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1241                                                                                     'key'=>$key,
1242                                                                                     'ouvalue'=>$ouvalue,
1243                                                                                     'nuvalue'=>$nuvalue)));
1244                                      continue;
1245                                  }
1246                              }
1247  
1248                              // We found which ldap key to update!
1249                              if ($ouvalue !== '' and $ouvalue === $ldapvalue ) {
1250                                  // This might fail due to schema validation
1251                                  if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1252                                      $changed = true;
1253                                      continue;
1254                                  } else {
1255                                      $success = false;
1256                                      error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1257                                                                               array('errno'=>ldap_errno($ldapconnection),
1258                                                                                     'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1259                                                                                     'key'=>$key,
1260                                                                                     'ouvalue'=>$ouvalue,
1261                                                                                     'nuvalue'=>$nuvalue)));
1262                                      continue;
1263                                  }
1264                              }
1265                          }
1266                      }
1267  
1268                      if ($ambiguous and !$changed) {
1269                          $success = false;
1270                          error_log($this->errorlogtag.get_string ('updateremfailamb', 'auth_ldap',
1271                                                                   array('key'=>$key,
1272                                                                         'ouvalue'=>$ouvalue,
1273                                                                         'nuvalue'=>$nuvalue)));
1274                      }
1275                  }
1276              }
1277          } else {
1278              error_log($this->errorlogtag.get_string ('usernotfound', 'auth_ldap'));
1279              $success = false;
1280          }
1281  
1282          $this->ldap_close();
1283          return $success;
1284  
1285      }
1286  
1287      /**
1288       * Changes userpassword in LDAP
1289       *
1290       * Called when the user password is updated. It assumes it is
1291       * called by an admin or that you've otherwise checked the user's
1292       * credentials
1293       *
1294       * @param  object  $user        User table object
1295       * @param  string  $newpassword Plaintext password (not crypted/md5'ed)
1296       * @return boolean result
1297       *
1298       */
1299      function user_update_password($user, $newpassword) {
1300          global $USER;
1301  
1302          $result = false;
1303          $username = $user->username;
1304  
1305          $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
1306          $extpassword = core_text::convert($newpassword, 'utf-8', $this->config->ldapencoding);
1307  
1308          switch ($this->config->passtype) {
1309              case 'md5':
1310                  $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
1311                  break;
1312              case 'sha1':
1313                  $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
1314                  break;
1315              case 'plaintext':
1316              default:
1317                  break; // plaintext
1318          }
1319  
1320          $ldapconnection = $this->ldap_connect();
1321  
1322          $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
1323  
1324          if (!$user_dn) {
1325              error_log($this->errorlogtag.get_string ('nodnforusername', 'auth_ldap', $user->username));
1326              return false;
1327          }
1328  
1329          switch ($this->config->user_type) {
1330              case 'edir':
1331                  // Change password
1332                  $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1333                  if (!$result) {
1334                      error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1335                                                                 array('errno'=>ldap_errno($ldapconnection),
1336                                                                       'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1337                  }
1338                  // Update password expiration time, grace logins count
1339                  $search_attribs = array($this->config->expireattr, 'passwordExpirationInterval', 'loginGraceLimit');
1340                  $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
1341                  if ($sr) {
1342                      $entry = ldap_get_entries_moodle($ldapconnection, $sr);
1343                      $info = $entry[0];
1344                      $newattrs = array();
1345                      if (!empty($info[$this->config->expireattr][0])) {
1346                          // Set expiration time only if passwordExpirationInterval is defined
1347                          if (!empty($info['passwordexpirationinterval'][0])) {
1348                             $expirationtime = time() + $info['passwordexpirationinterval'][0];
1349                             $ldapexpirationtime = $this->ldap_unix2expirationtime($expirationtime);
1350                             $newattrs['passwordExpirationTime'] = $ldapexpirationtime;
1351                          }
1352  
1353                          // Set gracelogin count
1354                          if (!empty($info['logingracelimit'][0])) {
1355                             $newattrs['loginGraceRemaining']= $info['logingracelimit'][0];
1356                          }
1357  
1358                          // Store attribute changes in LDAP
1359                          $result = ldap_modify($ldapconnection, $user_dn, $newattrs);
1360                          if (!$result) {
1361                              error_log($this->errorlogtag.get_string ('updatepasserrorexpiregrace', 'auth_ldap',
1362                                                                         array('errno'=>ldap_errno($ldapconnection),
1363                                                                               'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1364                          }
1365                      }
1366                  }
1367                  else {
1368                      error_log($this->errorlogtag.get_string ('updatepasserrorexpire', 'auth_ldap',
1369                                                               array('errno'=>ldap_errno($ldapconnection),
1370                                                                     'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1371                  }
1372                  break;
1373  
1374              case 'ad':
1375                  // Passwords in Active Directory must be encoded as Unicode
1376                  // strings (UCS-2 Little Endian format) and surrounded with
1377                  // double quotes. See http://support.microsoft.com/?kbid=269190
1378                  if (!function_exists('mb_convert_encoding')) {
1379                      error_log($this->errorlogtag.get_string ('needmbstring', 'auth_ldap'));
1380                      return false;
1381                  }
1382                  $extpassword = mb_convert_encoding('"'.$extpassword.'"', "UCS-2LE", $this->config->ldapencoding);
1383                  $result = ldap_modify($ldapconnection, $user_dn, array('unicodePwd' => $extpassword));
1384                  if (!$result) {
1385                      error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1386                                                               array('errno'=>ldap_errno($ldapconnection),
1387                                                                     'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1388                  }
1389                  break;
1390  
1391              default:
1392                  // Send LDAP the password in cleartext, it will md5 it itself
1393                  $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1394                  if (!$result) {
1395                      error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1396                                                               array('errno'=>ldap_errno($ldapconnection),
1397                                                                     'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1398                  }
1399  
1400          }
1401  
1402          $this->ldap_close();
1403          return $result;
1404      }
1405  
1406      /**
1407       * Take expirationtime and return it as unix timestamp in seconds
1408       *
1409       * Takes expiration timestamp as read from LDAP and returns it as unix timestamp in seconds
1410       * Depends on $this->config->user_type variable
1411       *
1412       * @param mixed time   Time stamp read from LDAP as it is.
1413       * @param string $ldapconnection Only needed for Active Directory.
1414       * @param string $user_dn User distinguished name for the user we are checking password expiration (only needed for Active Directory).
1415       * @return timestamp
1416       */
1417      function ldap_expirationtime2unix ($time, $ldapconnection, $user_dn) {
1418          $result = false;
1419          switch ($this->config->user_type) {
1420              case 'edir':
1421                  $yr=substr($time, 0, 4);
1422                  $mo=substr($time, 4, 2);
1423                  $dt=substr($time, 6, 2);
1424                  $hr=substr($time, 8, 2);
1425                  $min=substr($time, 10, 2);
1426                  $sec=substr($time, 12, 2);
1427                  $result = mktime($hr, $min, $sec, $mo, $dt, $yr);
1428                  break;
1429              case 'rfc2307':
1430              case 'rfc2307bis':
1431                  $result = $time * DAYSECS; // The shadowExpire contains the number of DAYS between 01/01/1970 and the actual expiration date
1432                  break;
1433              case 'ad':
1434                  $result = $this->ldap_get_ad_pwdexpire($time, $ldapconnection, $user_dn);
1435                  break;
1436              default:
1437                  print_error('auth_ldap_usertypeundefined', 'auth_ldap');
1438          }
1439          return $result;
1440      }
1441  
1442      /**
1443       * Takes unix timestamp and returns it formated for storing in LDAP
1444       *
1445       * @param integer unix time stamp
1446       */
1447      function ldap_unix2expirationtime($time) {
1448          $result = false;
1449          switch ($this->config->user_type) {
1450              case 'edir':
1451                  $result=date('YmdHis', $time).'Z';
1452                  break;
1453              case 'rfc2307':
1454              case 'rfc2307bis':
1455                  $result = $time ; // Already in correct format
1456                  break;
1457              default:
1458                  print_error('auth_ldap_usertypeundefined2', 'auth_ldap');
1459          }
1460          return $result;
1461  
1462      }
1463  
1464      /**
1465       * Returns user attribute mappings between moodle and LDAP
1466       *
1467       * @return array
1468       */
1469  
1470      function ldap_attributes () {
1471          $moodleattributes = array();
1472          // If we have custom fields then merge them with user fields.
1473          $customfields = $this->get_custom_user_profile_fields();
1474          if (!empty($customfields) && !empty($this->userfields)) {
1475              $userfields = array_merge($this->userfields, $customfields);
1476          } else {
1477              $userfields = $this->userfields;
1478          }
1479  
1480          foreach ($userfields as $field) {
1481              if (!empty($this->config->{"field_map_$field"})) {
1482                  $moodleattributes[$field] = core_text::strtolower(trim($this->config->{"field_map_$field"}));
1483                  if (preg_match('/,/', $moodleattributes[$field])) {
1484                      $moodleattributes[$field] = explode(',', $moodleattributes[$field]); // split ?
1485                  }
1486              }
1487          }
1488          $moodleattributes['username'] = core_text::strtolower(trim($this->config->user_attribute));
1489          $moodleattributes['suspended'] = core_text::strtolower(trim($this->config->suspended_attribute));
1490          return $moodleattributes;
1491      }
1492  
1493      /**
1494       * Returns all usernames from LDAP
1495       *
1496       * @param $filter An LDAP search filter to select desired users
1497       * @return array of LDAP user names converted to UTF-8
1498       */
1499      function ldap_get_userlist($filter='*') {
1500          $fresult = array();
1501  
1502          $ldapconnection = $this->ldap_connect();
1503  
1504          if ($filter == '*') {
1505             $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
1506          }
1507          $servercontrols = array();
1508  
1509          $contexts = explode(';', $this->config->contexts);
1510          if (!empty($this->config->create_context)) {
1511              array_push($contexts, $this->config->create_context);
1512          }
1513  
1514          $ldap_cookie = '';
1515          $ldap_pagedresults = ldap_paged_results_supported($this->config->ldap_version, $ldapconnection);
1516          foreach ($contexts as $context) {
1517              $context = trim($context);
1518              if (empty($context)) {
1519                  continue;
1520              }
1521  
1522              do {
1523                  if ($ldap_pagedresults) {
1524                      $servercontrols = array(array(
1525                          'oid' => LDAP_CONTROL_PAGEDRESULTS, 'value' => array(
1526                              'size' => $this->config->pagesize, 'cookie' => $ldap_cookie)));
1527                  }
1528                  if ($this->config->search_sub) {
1529                      // Use ldap_search to find first user from subtree.
1530                      $ldap_result = ldap_search($ldapconnection, $context, $filter, array($this->config->user_attribute),
1531                          0, -1, -1, LDAP_DEREF_NEVER, $servercontrols);
1532                  } else {
1533                      // Search only in this context.
1534                      $ldap_result = ldap_list($ldapconnection, $context, $filter, array($this->config->user_attribute),
1535                          0, -1, -1, LDAP_DEREF_NEVER, $servercontrols);
1536                  }
1537                  if(!$ldap_result) {
1538                      continue;
1539                  }
1540                  if ($ldap_pagedresults) {
1541                      // Get next server cookie to know if we'll need to continue searching.
1542                      $ldap_cookie = '';
1543                      // Get next cookie from controls.
1544                      ldap_parse_result($ldapconnection, $ldap_result, $errcode, $matcheddn,
1545                          $errmsg, $referrals, $controls);
1546                      if (isset($controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'])) {
1547                          $ldap_cookie = $controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'];
1548                      }
1549                  }
1550                  $users = ldap_get_entries_moodle($ldapconnection, $ldap_result);
1551                  // Add found users to list.
1552                  for ($i = 0; $i < count($users); $i++) {
1553                      $extuser = core_text::convert($users[$i][$this->config->user_attribute][0],
1554                                                  $this->config->ldapencoding, 'utf-8');
1555                      array_push($fresult, $extuser);
1556                  }
1557                  unset($ldap_result); // Free mem.
1558              } while ($ldap_pagedresults && !empty($ldap_cookie));
1559          }
1560  
1561          // If paged results were used, make sure the current connection is completely closed
1562          $this->ldap_close($ldap_pagedresults);
1563          return $fresult;
1564      }
1565  
1566      /**
1567       * Indicates if password hashes should be stored in local moodle database.
1568       *
1569       * @return bool true means flag 'not_cached' stored instead of password hash
1570       */
1571      function prevent_local_passwords() {
1572          return !empty($this->config->preventpassindb);
1573      }
1574  
1575      /**
1576       * Returns true if this authentication plugin is 'internal'.
1577       *
1578       * @return bool
1579       */
1580      function is_internal() {
1581          return false;
1582      }
1583  
1584      /**
1585       * Returns true if this authentication plugin can change the user's
1586       * password.
1587       *
1588       * @return bool
1589       */
1590      function can_change_password() {
1591          return !empty($this->config->stdchangepassword) or !empty($this->config->changepasswordurl);
1592      }
1593  
1594      /**
1595       * Returns the URL for changing the user's password, or empty if the default can
1596       * be used.
1597       *
1598       * @return moodle_url
1599       */
1600      function change_password_url() {
1601          if (empty($this->config->stdchangepassword)) {
1602              if (!empty($this->config->changepasswordurl)) {
1603                  return new moodle_url($this->config->changepasswordurl);
1604              } else {
1605                  return null;
1606              }
1607          } else {
1608              return null;
1609          }
1610      }
1611  
1612      /**
1613       * Will get called before the login page is shownr. Ff NTLM SSO
1614       * is enabled, and the user is in the right network, we'll redirect
1615       * to the magic NTLM page for SSO...
1616       *
1617       */
1618      function loginpage_hook() {
1619          global $CFG, $SESSION;
1620  
1621          // HTTPS is potentially required
1622          //httpsrequired(); - this must be used before setting the URL, it is already done on the login/index.php
1623  
1624          if (($_SERVER['REQUEST_METHOD'] === 'GET'         // Only on initial GET of loginpage
1625               || ($_SERVER['REQUEST_METHOD'] === 'POST'
1626                   && (get_local_referer() != strip_querystring(qualified_me()))))
1627                                                            // Or when POSTed from another place
1628                                                            // See MDL-14071
1629              && !empty($this->config->ntlmsso_enabled)     // SSO enabled
1630              && !empty($this->config->ntlmsso_subnet)      // have a subnet to test for
1631              && empty($_GET['authldap_skipntlmsso'])       // haven't failed it yet
1632              && (isguestuser() || !isloggedin())           // guestuser or not-logged-in users
1633              && address_in_subnet(getremoteaddr(), $this->config->ntlmsso_subnet)) {
1634  
1635              // First, let's remember where we were trying to get to before we got here
1636              if (empty($SESSION->wantsurl)) {
1637                  $SESSION->wantsurl = null;
1638                  $referer = get_local_referer(false);
1639                  if ($referer &&
1640                          $referer != $CFG->wwwroot &&
1641                          $referer != $CFG->wwwroot . '/' &&
1642                          $referer != $CFG->wwwroot . '/login/' &&
1643                          $referer != $CFG->wwwroot . '/login/index.php') {
1644                      $SESSION->wantsurl = $referer;
1645                  }
1646              }
1647  
1648              // Now start the whole NTLM machinery.
1649              if($this->config->ntlmsso_ie_fastpath == AUTH_NTLM_FASTPATH_YESATTEMPT ||
1650                  $this->config->ntlmsso_ie_fastpath == AUTH_NTLM_FASTPATH_YESFORM) {
1651                  if (core_useragent::is_ie()) {
1652                      $sesskey = sesskey();
1653                      redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_magic.php?sesskey='.$sesskey);
1654                  } else if ($this->config->ntlmsso_ie_fastpath == AUTH_NTLM_FASTPATH_YESFORM) {
1655                      redirect($CFG->wwwroot.'/login/index.php?authldap_skipntlmsso=1');
1656                  }
1657              }
1658              redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_attempt.php');
1659          }
1660  
1661          // No NTLM SSO, Use the normal login page instead.
1662  
1663          // If $SESSION->wantsurl is empty and we have a 'Referer:' header, the login
1664          // page insists on redirecting us to that page after user validation. If
1665          // we clicked on the redirect link at the ntlmsso_finish.php page (instead
1666          // of waiting for the redirection to happen) then we have a 'Referer:' header
1667          // we don't want to use at all. As we can't get rid of it, just point
1668          // $SESSION->wantsurl to $CFG->wwwroot (after all, we came from there).
1669          if (empty($SESSION->wantsurl)
1670              && (get_local_referer() == $CFG->wwwroot.'/auth/ldap/ntlmsso_finish.php')) {
1671  
1672              $SESSION->wantsurl = $CFG->wwwroot;
1673          }
1674      }
1675  
1676      /**
1677       * To be called from a page running under NTLM's
1678       * "Integrated Windows Authentication".
1679       *
1680       * If successful, it will set a special "cookie" (not an HTTP cookie!)
1681       * in cache_flags under the $this->pluginconfig/ntlmsess "plugin" and return true.
1682       * The "cookie" will be picked up by ntlmsso_finish() to complete the
1683       * process.
1684       *
1685       * On failure it will return false for the caller to display an appropriate
1686       * error message (probably saying that Integrated Windows Auth isn't enabled!)
1687       *
1688       * NOTE that this code will execute under the OS user credentials,
1689       * so we MUST avoid dealing with files -- such as session files.
1690       * (The caller should define('NO_MOODLE_COOKIES', true) before including config.php)
1691       *
1692       */
1693      function ntlmsso_magic($sesskey) {
1694          if (isset($_SERVER['REMOTE_USER']) && !empty($_SERVER['REMOTE_USER'])) {
1695  
1696              // HTTP __headers__ seem to be sent in ISO-8859-1 encoding
1697              // (according to my reading of RFC-1945, RFC-2616 and RFC-2617 and
1698              // my local tests), so we need to convert the REMOTE_USER value
1699              // (i.e., what we got from the HTTP WWW-Authenticate header) into UTF-8
1700              $username = core_text::convert($_SERVER['REMOTE_USER'], 'iso-8859-1', 'utf-8');
1701  
1702              switch ($this->config->ntlmsso_type) {
1703                  case 'ntlm':
1704                      // The format is now configurable, so try to extract the username
1705                      $username = $this->get_ntlm_remote_user($username);
1706                      if (empty($username)) {
1707                          return false;
1708                      }
1709                      break;
1710                  case 'kerberos':
1711                      // Format is username@DOMAIN
1712                      $username = substr($username, 0, strpos($username, '@'));
1713                      break;
1714                  default:
1715                      error_log($this->errorlogtag.get_string ('ntlmsso_unknowntype', 'auth_ldap'));
1716                      return false; // Should never happen!
1717              }
1718  
1719              $username = core_text::strtolower($username); // Compatibility hack
1720              set_cache_flag($this->pluginconfig.'/ntlmsess', $sesskey, $username, AUTH_NTLMTIMEOUT);
1721              return true;
1722          }
1723          return false;
1724      }
1725  
1726      /**
1727       * Find the session set by ntlmsso_magic(), validate it and
1728       * call authenticate_user_login() to authenticate the user through
1729       * the auth machinery.
1730       *
1731       * It is complemented by a similar check in user_login().
1732       *
1733       * If it succeeds, it never returns.
1734       *
1735       */
1736      function ntlmsso_finish() {
1737          global $CFG, $USER, $SESSION;
1738  
1739          $key = sesskey();
1740          $username = get_cache_flag($this->pluginconfig.'/ntlmsess', $key);
1741          if (empty($username)) {
1742              return false;
1743          }
1744  
1745          // Here we want to trigger the whole authentication machinery
1746          // to make sure no step is bypassed...
1747          $reason = null;
1748          $user = authenticate_user_login($username, $key, false, $reason, false);
1749          if ($user) {
1750              complete_user_login($user);
1751  
1752              // Cleanup the key to prevent reuse...
1753              // and to allow re-logins with normal credentials
1754              unset_cache_flag($this->pluginconfig.'/ntlmsess', $key);
1755  
1756              // Redirection
1757              if (user_not_fully_set_up($USER, true)) {
1758                  $urltogo = $CFG->wwwroot.'/user/edit.php';
1759                  // We don't delete $SESSION->wantsurl yet, so we get there later
1760              } else if (isset($SESSION->wantsurl) and (strpos($SESSION->wantsurl, $CFG->wwwroot) === 0)) {
1761                  $urltogo = $SESSION->wantsurl;    // Because it's an address in this site
1762                  unset($SESSION->wantsurl);
1763              } else {
1764                  // No wantsurl stored or external - go to homepage
1765                  $urltogo = $CFG->wwwroot.'/';
1766                  unset($SESSION->wantsurl);
1767              }
1768              // We do not want to redirect if we are in a PHPUnit test.
1769              if (!PHPUNIT_TEST) {
1770                  redirect($urltogo);
1771              }
1772          }
1773          // Should never reach here.
1774          return false;
1775      }
1776  
1777      /**
1778       * Sync roles for this user.
1779       *
1780       * @param object $user The user to sync (without system magic quotes).
1781       */
1782      function sync_roles($user) {
1783          global $DB;
1784  
1785          $roles = get_ldap_assignable_role_names(2); // Admin user.
1786  
1787          foreach ($roles as $role) {
1788              $isrole = $this->is_role($user->username, $role);
1789              if ($isrole === null) {
1790                  continue; // Nothing to sync - role/LDAP contexts not configured.
1791              }
1792  
1793              // Sync user.
1794              $systemcontext = context_system::instance();
1795              if ($isrole) {
1796                  // Following calls will not create duplicates.
1797                  role_assign($role['id'], $user->id, $systemcontext->id, $this->roleauth);
1798              } else {
1799                  // Unassign only if previously assigned by this plugin.
1800                  role_unassign($role['id'], $user->id, $systemcontext->id, $this->roleauth);
1801              }
1802          }
1803      }
1804  
1805      /**
1806       * Get password expiration time for a given user from Active Directory
1807       *
1808       * @param string $pwdlastset The time last time we changed the password.
1809       * @param resource $lcapconn The open LDAP connection.
1810       * @param string $user_dn The distinguished name of the user we are checking.
1811       *
1812       * @return string $unixtime
1813       */
1814      function ldap_get_ad_pwdexpire($pwdlastset, $ldapconn, $user_dn){
1815          global $CFG;
1816  
1817          if (!function_exists('bcsub')) {
1818              error_log($this->errorlogtag.get_string ('needbcmath', 'auth_ldap'));
1819              return 0;
1820          }
1821  
1822          // If UF_DONT_EXPIRE_PASSWD flag is set in user's
1823          // userAccountControl attribute, the password doesn't expire.
1824          $sr = ldap_read($ldapconn, $user_dn, '(objectClass=*)',
1825                          array('userAccountControl'));
1826          if (!$sr) {
1827              error_log($this->errorlogtag.get_string ('useracctctrlerror', 'auth_ldap', $user_dn));
1828              // Don't expire password, as we are not sure if it has to be
1829              // expired or not.
1830              return 0;
1831          }
1832  
1833          $entry = ldap_get_entries_moodle($ldapconn, $sr);
1834          $info = $entry[0];
1835          $useraccountcontrol = $info['useraccountcontrol'][0];
1836          if ($useraccountcontrol & UF_DONT_EXPIRE_PASSWD) {
1837              // Password doesn't expire.
1838              return 0;
1839          }
1840  
1841          // If pwdLastSet is zero, the user must change his/her password now
1842          // (unless UF_DONT_EXPIRE_PASSWD flag is set, but we already
1843          // tested this above)
1844          if ($pwdlastset === '0') {
1845              // Password has expired
1846              return -1;
1847          }
1848  
1849          // ----------------------------------------------------------------
1850          // Password expiration time in Active Directory is the composition of
1851          // two values:
1852          //
1853          //   - User's pwdLastSet attribute, that stores the last time
1854          //     the password was changed.
1855          //
1856          //   - Domain's maxPwdAge attribute, that sets how long
1857          //     passwords last in this domain.
1858          //
1859          // We already have the first value (passed in as a parameter). We
1860          // need to get the second one. As we don't know the domain DN, we
1861          // have to query rootDSE's defaultNamingContext attribute to get
1862          // it. Then we have to query that DN's maxPwdAge attribute to get
1863          // the real value.
1864          //
1865          // Once we have both values, we just need to combine them. But MS
1866          // chose to use a different base and unit for time measurements.
1867          // So we need to convert the values to Unix timestamps (see
1868          // details below).
1869          // ----------------------------------------------------------------
1870  
1871          $sr = ldap_read($ldapconn, ROOTDSE, '(objectClass=*)',
1872                          array('defaultNamingContext'));
1873          if (!$sr) {
1874              error_log($this->errorlogtag.get_string ('rootdseerror', 'auth_ldap'));
1875              return 0;
1876          }
1877  
1878          $entry = ldap_get_entries_moodle($ldapconn, $sr);
1879          $info = $entry[0];
1880          $domaindn = $info['defaultnamingcontext'][0];
1881  
1882          $sr = ldap_read ($ldapconn, $domaindn, '(objectClass=*)',
1883                           array('maxPwdAge'));
1884          $entry = ldap_get_entries_moodle($ldapconn, $sr);
1885          $info = $entry[0];
1886          $maxpwdage = $info['maxpwdage'][0];
1887          if ($sr = ldap_read($ldapconn, $user_dn, '(objectClass=*)', array('msDS-ResultantPSO'))) {
1888              if ($entry = ldap_get_entries_moodle($ldapconn, $sr)) {
1889                  $info = $entry[0];
1890                  $userpso = $info['msds-resultantpso'][0];
1891  
1892                  // If a PSO exists, FGPP is being utilized.
1893                  // Grab the new maxpwdage from the msDS-MaximumPasswordAge attribute of the PSO.
1894                  if (!empty($userpso)) {
1895                      $sr = ldap_read($ldapconn, $userpso, '(objectClass=*)', array('msDS-MaximumPasswordAge'));
1896                      if ($entry = ldap_get_entries_moodle($ldapconn, $sr)) {
1897                          $info = $entry[0];
1898                          // Default value of msds-maximumpasswordage is 42 and is always set.
1899                          $maxpwdage = $info['msds-maximumpasswordage'][0];
1900                      }
1901                  }
1902              }
1903          }
1904          // ----------------------------------------------------------------
1905          // MSDN says that "pwdLastSet contains the number of 100 nanosecond
1906          // intervals since January 1, 1601 (UTC), stored in a 64 bit integer".
1907          //
1908          // According to Perl's Date::Manip, the number of seconds between
1909          // this date and Unix epoch is 11644473600. So we have to
1910          // substract this value to calculate a Unix time, once we have
1911          // scaled pwdLastSet to seconds. This is the script used to
1912          // calculate the value shown above:
1913          //
1914          //    #!/usr/bin/perl -w
1915          //
1916          //    use Date::Manip;
1917          //
1918          //    $date1 = ParseDate ("160101010000 UTC");
1919          //    $date2 = ParseDate ("197001010000 UTC");
1920          //    $delta = DateCalc($date1, $date2, \$err);
1921          //    $secs = Delta_Format($delta, 0, "%st");
1922          //    print "$secs \n";
1923          //
1924          // MSDN also says that "maxPwdAge is stored as a large integer that
1925          // represents the number of 100 nanosecond intervals from the time
1926          // the password was set before the password expires." We also need
1927          // to scale this to seconds. Bear in mind that this value is stored
1928          // as a _negative_ quantity (at least in my AD domain).
1929          //
1930          // As a last remark, if the low 32 bits of maxPwdAge are equal to 0,
1931          // the maximum password age in the domain is set to 0, which means
1932          // passwords do not expire (see
1933          // http://msdn2.microsoft.com/en-us/library/ms974598.aspx)
1934          //
1935          // As the quantities involved are too big for PHP integers, we
1936          // need to use BCMath functions to work with arbitrary precision
1937          // numbers.
1938          // ----------------------------------------------------------------
1939  
1940          // If the low order 32 bits are 0, then passwords do not expire in
1941          // the domain. Just do '$maxpwdage mod 2^32' and check the result
1942          // (2^32 = 4294967296)
1943          if (bcmod ($maxpwdage, 4294967296) === '0') {
1944              return 0;
1945          }
1946  
1947          // Add up pwdLastSet and maxPwdAge to get password expiration
1948          // time, in MS time units. Remember maxPwdAge is stored as a
1949          // _negative_ quantity, so we need to substract it in fact.
1950          $pwdexpire = bcsub ($pwdlastset, $maxpwdage);
1951  
1952          // Scale the result to convert it to Unix time units and return
1953          // that value.
1954          return bcsub( bcdiv($pwdexpire, '10000000'), '11644473600');
1955      }
1956  
1957      /**
1958       * Connect to the LDAP server, using the plugin configured
1959       * settings. It's actually a wrapper around ldap_connect_moodle()
1960       *
1961       * @return resource A valid LDAP connection (or dies if it can't connect)
1962       */
1963      function ldap_connect() {
1964          // Cache ldap connections. They are expensive to set up
1965          // and can drain the TCP/IP ressources on the server if we
1966          // are syncing a lot of users (as we try to open a new connection
1967          // to get the user details). This is the least invasive way
1968          // to reuse existing connections without greater code surgery.
1969          if(!empty($this->ldapconnection)) {
1970              $this->ldapconns++;
1971              return $this->ldapconnection;
1972          }
1973  
1974          if($ldapconnection = ldap_connect_moodle($this->config->host_url, $this->config->ldap_version,
1975                                                   $this->config->user_type, $this->config->bind_dn,
1976                                                   $this->config->bind_pw, $this->config->opt_deref,
1977                                                   $debuginfo, $this->config->start_tls)) {
1978              $this->ldapconns = 1;
1979              $this->ldapconnection = $ldapconnection;
1980              return $ldapconnection;
1981          }
1982  
1983          print_error('auth_ldap_noconnect_all', 'auth_ldap', '', $debuginfo);
1984      }
1985  
1986      /**
1987       * Disconnects from a LDAP server
1988       *
1989       * @param force boolean Forces closing the real connection to the LDAP server, ignoring any
1990       *                      cached connections. This is needed when we've used paged results
1991       *                      and want to use normal results again.
1992       */
1993      function ldap_close($force=false) {
1994          $this->ldapconns--;
1995          if (($this->ldapconns == 0) || ($force)) {
1996              $this->ldapconns = 0;
1997              @ldap_close($this->ldapconnection);
1998              unset($this->ldapconnection);
1999          }
2000      }
2001  
2002      /**
2003       * Search specified contexts for username and return the user dn
2004       * like: cn=username,ou=suborg,o=org. It's actually a wrapper
2005       * around ldap_find_userdn().
2006       *
2007       * @param resource $ldapconnection a valid LDAP connection
2008       * @param string $extusername the username to search (in external LDAP encoding, no db slashes)
2009       * @return mixed the user dn (external LDAP encoding) or false
2010       */
2011      function ldap_find_userdn($ldapconnection, $extusername) {
2012          $ldap_contexts = explode(';', $this->config->contexts);
2013          if (!empty($this->config->create_context)) {
2014              array_push($ldap_contexts, $this->config->create_context);
2015          }
2016  
2017          return ldap_find_userdn($ldapconnection, $extusername, $ldap_contexts, $this->config->objectclass,
2018                                  $this->config->user_attribute, $this->config->search_sub);
2019      }
2020  
2021      /**
2022       * When using NTLM SSO, the format of the remote username we get in
2023       * $_SERVER['REMOTE_USER'] may vary, depending on where from and how the web
2024       * server gets the data. So we let the admin configure the format using two
2025       * place holders (%domain% and %username%). This function tries to extract
2026       * the username (stripping the domain part and any separators if they are
2027       * present) from the value present in $_SERVER['REMOTE_USER'], using the
2028       * configured format.
2029       *
2030       * @param string $remoteuser The value from $_SERVER['REMOTE_USER'] (converted to UTF-8)
2031       *
2032       * @return string The remote username (without domain part or
2033       *                separators). Empty string if we can't extract the username.
2034       */
2035      protected function get_ntlm_remote_user($remoteuser) {
2036          if (empty($this->config->ntlmsso_remoteuserformat)) {
2037              $format = AUTH_NTLM_DEFAULT_FORMAT;
2038          } else {
2039              $format = $this->config->ntlmsso_remoteuserformat;
2040          }
2041  
2042          $format = preg_quote($format);
2043          $formatregex = preg_replace(array('#%domain%#', '#%username%#'),
2044                                      array('('.AUTH_NTLM_VALID_DOMAINNAME.')', '('.AUTH_NTLM_VALID_USERNAME.')'),
2045                                      $format);
2046          if (preg_match('#^'.$formatregex.'$#', $remoteuser, $matches)) {
2047              $user = end($matches);
2048              return $user;
2049          }
2050  
2051          /* We are unable to extract the username with the configured format. Probably
2052           * the format specified is wrong, so log a warning for the admin and return
2053           * an empty username.
2054           */
2055          error_log($this->errorlogtag.get_string ('auth_ntlmsso_maybeinvalidformat', 'auth_ldap'));
2056          return '';
2057      }
2058  
2059      /**
2060       * Check if the diagnostic message for the LDAP login error tells us that the
2061       * login is denied because the user password has expired or the password needs
2062       * to be changed on first login (using interactive SMB/Windows logins, not
2063       * LDAP logins).
2064       *
2065       * @param string the diagnostic message for the LDAP login error
2066       * @return bool true if the password has expired or the password must be changed on first login
2067       */
2068      protected function ldap_ad_pwdexpired_from_diagmsg($diagmsg) {
2069          // The format of the diagnostic message is (actual examples from W2003 and W2008):
2070          // "80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece"  (W2003)
2071          // "80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 773, vece"  (W2003)
2072          // "80090308: LdapErr: DSID-0C0903AA, comment: AcceptSecurityContext error, data 52e, v1771" (W2008)
2073          // "80090308: LdapErr: DSID-0C0903AA, comment: AcceptSecurityContext error, data 773, v1771" (W2008)
2074          // We are interested in the 'data nnn' part.
2075          //   if nnn == 773 then user must change password on first login
2076          //   if nnn == 532 then user password has expired
2077          $diagmsg = explode(',', $diagmsg);
2078          if (preg_match('/data (773|532)/i', trim($diagmsg[2]))) {
2079              return true;
2080          }
2081          return false;
2082      }
2083  
2084      /**
2085       * Check if a user is suspended. This function is intended to be used after calling
2086       * get_userinfo_asobj. This is needed because LDAP doesn't have a notion of disabled
2087       * users, however things like MS Active Directory support it and expose information
2088       * through a field.
2089       *
2090       * @param object $user the user object returned by get_userinfo_asobj
2091       * @return boolean
2092       */
2093      protected function is_user_suspended($user) {
2094          if (!$this->config->suspended_attribute || !isset($user->suspended)) {
2095              return false;
2096          }
2097          if ($this->config->suspended_attribute == 'useraccountcontrol' && $this->config->user_type == 'ad') {
2098              return (bool)($user->suspended & AUTH_AD_ACCOUNTDISABLE);
2099          }
2100  
2101          return (bool)$user->suspended;
2102      }
2103  
2104      /**
2105       * Test a DN
2106       *
2107       * @param resource $ldapconn
2108       * @param string $dn The DN to check for existence
2109       * @param string $message The identifier of a string as in get_string()
2110       * @param string|object|array $a An object, string or number that can be used
2111       *      within translation strings as in get_string()
2112       * @return true or a message in case of error
2113       */
2114      private function test_dn($ldapconn, $dn, $message, $a = null) {
2115          $ldapresult = @ldap_read($ldapconn, $dn, '(objectClass=*)', array());
2116          if (!$ldapresult) {
2117              if (ldap_errno($ldapconn) == 32) {
2118                  // No such object.
2119                  return get_string($message, 'auth_ldap', $a);
2120              }
2121  
2122              $a = array('code' => ldap_errno($ldapconn), 'subject' => $a, 'message' => ldap_error($ldapconn));
2123              return get_string('diag_genericerror', 'auth_ldap', $a);
2124          }
2125  
2126          return true;
2127      }
2128  
2129      /**
2130       * Test if settings are correct, print info to output.
2131       */
2132      public function test_settings() {
2133          global $OUTPUT;
2134  
2135          if (!function_exists('ldap_connect')) { // Is php-ldap really there?
2136              echo $OUTPUT->notification(get_string('auth_ldap_noextension', 'auth_ldap'), \core\output\notification::NOTIFY_ERROR);
2137              return;
2138          }
2139  
2140          // Check to see if this is actually configured.
2141          if (empty($this->config->host_url)) {
2142              // LDAP is not even configured.
2143              echo $OUTPUT->notification(get_string('ldapnotconfigured', 'auth_ldap'), \core\output\notification::NOTIFY_ERROR);
2144              return;
2145          }
2146  
2147          if ($this->config->ldap_version != 3) {
2148              echo $OUTPUT->notification(get_string('diag_toooldversion', 'auth_ldap'), \core\output\notification::NOTIFY_WARNING);
2149          }
2150  
2151          try {
2152              $ldapconn = $this->ldap_connect();
2153          } catch (Exception $e) {
2154              echo $OUTPUT->notification($e->getMessage(), \core\output\notification::NOTIFY_ERROR);
2155              return;
2156          }
2157  
2158          // Display paged file results.
2159          if (!ldap_paged_results_supported($this->config->ldap_version, $ldapconn)) {
2160              echo $OUTPUT->notification(get_string('pagedresultsnotsupp', 'auth_ldap'), \core\output\notification::NOTIFY_INFO);
2161          }
2162  
2163          // Check contexts.
2164          foreach (explode(';', $this->config->contexts) as $context) {
2165              $context = trim($context);
2166              if (empty($context)) {
2167                  echo $OUTPUT->notification(get_string('diag_emptycontext', 'auth_ldap'), \core\output\notification::NOTIFY_WARNING);
2168                  continue;
2169              }
2170  
2171              $message = $this->test_dn($ldapconn, $context, 'diag_contextnotfound', $context);
2172              if ($message !== true) {
2173                  echo $OUTPUT->notification($message, \core\output\notification::NOTIFY_WARNING);
2174              }
2175          }
2176  
2177          // Create system role mapping field for each assignable system role.
2178          $roles = get_ldap_assignable_role_names();
2179          foreach ($roles as $role) {
2180              foreach (explode(';', $this->config->{$role['settingname']}) as $groupdn) {
2181                  if (empty($groupdn)) {
2182                      continue;
2183                  }
2184  
2185                  $role['group'] = $groupdn;
2186                  $message = $this->test_dn($ldapconn, $groupdn, 'diag_rolegroupnotfound', $role);
2187                  if ($message !== true) {
2188                      echo $OUTPUT->notification($message, \core\output\notification::NOTIFY_WARNING);
2189                  }
2190              }
2191          }
2192  
2193          $this->ldap_close(true);
2194          // We were able to connect successfuly.
2195          echo $OUTPUT->notification(get_string('connectingldapsuccess', 'auth_ldap'), \core\output\notification::NOTIFY_SUCCESS);
2196      }
2197  
2198      /**
2199       * Get the list of profile fields.
2200       *
2201       * @param   bool    $fetchall   Fetch all, not just those for update.
2202       * @return  array
2203       */
2204      protected function get_profile_keys($fetchall = false) {
2205          $keys = array_keys(get_object_vars($this->config));
2206          $updatekeys = [];
2207          foreach ($keys as $key) {
2208              if (preg_match('/^field_updatelocal_(.+)$/', $key, $match)) {
2209                  // If we have a field to update it from and it must be updated 'onlogin' we update it on cron.
2210                  if (!empty($this->config->{'field_map_'.$match[1]})) {
2211                      if ($fetchall || $this->config->{$match[0]} === 'onlogin') {
2212                          array_push($updatekeys, $match[1]); // the actual key name
2213                      }
2214                  }
2215              }
2216          }
2217  
2218          if ($this->config->suspended_attribute && $this->config->sync_suspended) {
2219              $updatekeys[] = 'suspended';
2220          }
2221  
2222          return $updatekeys;
2223      }
2224  }