PageRenderTime 57ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/auth/ldap/auth.php

https://bitbucket.org/kudutest1/moodlegit
PHP | 1191 lines | 749 code | 146 blank | 296 comment | 174 complexity | 5fe918a8f34f9c33cfb19848040ea157 MD5 | raw file
  1. <?php
  2. /**
  3. * @author Martin Dougiamas
  4. * @author IƱaki Arenaza
  5. * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  6. * @package moodle multiauth
  7. *
  8. * Authentication Plugin: LDAP Authentication
  9. *
  10. * Authentication using LDAP (Lightweight Directory Access Protocol).
  11. *
  12. * 2006-08-28 File created.
  13. */
  14. if (!defined('MOODLE_INTERNAL')) {
  15. die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
  16. }
  17. // See http://support.microsoft.com/kb/305144 to interprete these values.
  18. if (!defined('AUTH_AD_ACCOUNTDISABLE')) {
  19. define('AUTH_AD_ACCOUNTDISABLE', 0x0002);
  20. }
  21. if (!defined('AUTH_AD_NORMAL_ACCOUNT')) {
  22. define('AUTH_AD_NORMAL_ACCOUNT', 0x0200);
  23. }
  24. if (!defined('AUTH_NTLMTIMEOUT')) { // timewindow for the NTLM SSO process, in secs...
  25. define('AUTH_NTLMTIMEOUT', 10);
  26. }
  27. // UF_DONT_EXPIRE_PASSWD value taken from MSDN directly
  28. if (!defined('UF_DONT_EXPIRE_PASSWD')) {
  29. define ('UF_DONT_EXPIRE_PASSWD', 0x00010000);
  30. }
  31. // The Posix uid and gid of the 'nobody' account and 'nogroup' group.
  32. if (!defined('AUTH_UID_NOBODY')) {
  33. define('AUTH_UID_NOBODY', -2);
  34. }
  35. if (!defined('AUTH_GID_NOGROUP')) {
  36. define('AUTH_GID_NOGROUP', -2);
  37. }
  38. // Regular expressions for a valid NTLM username and domain name.
  39. if (!defined('AUTH_NTLM_VALID_USERNAME')) {
  40. define('AUTH_NTLM_VALID_USERNAME', '[^/\\\\\\\\\[\]:;|=,+*?<>@"]+');
  41. }
  42. if (!defined('AUTH_NTLM_VALID_DOMAINNAME')) {
  43. define('AUTH_NTLM_VALID_DOMAINNAME', '[^\\\\\\\\\/:*?"<>|]+');
  44. }
  45. // Default format for remote users if using NTLM SSO
  46. if (!defined('AUTH_NTLM_DEFAULT_FORMAT')) {
  47. define('AUTH_NTLM_DEFAULT_FORMAT', '%domain%\\%username%');
  48. }
  49. // Allows us to retrieve a diagnostic message in case of LDAP operation error
  50. if (!defined('LDAP_OPT_DIAGNOSTIC_MESSAGE')) {
  51. define('LDAP_OPT_DIAGNOSTIC_MESSAGE', 0x0032);
  52. }
  53. require_once($CFG->libdir.'/authlib.php');
  54. require_once($CFG->libdir.'/ldaplib.php');
  55. /**
  56. * LDAP authentication plugin.
  57. */
  58. class auth_plugin_ldap extends auth_plugin_base {
  59. /**
  60. * Init plugin config from database settings depending on the plugin auth type.
  61. */
  62. function init_plugin($authtype) {
  63. $this->pluginconfig = 'auth/'.$authtype;
  64. $this->config = get_config($this->pluginconfig);
  65. if (empty($this->config->ldapencoding)) {
  66. $this->config->ldapencoding = 'utf-8';
  67. }
  68. if (empty($this->config->user_type)) {
  69. $this->config->user_type = 'default';
  70. }
  71. $ldap_usertypes = ldap_supported_usertypes();
  72. $this->config->user_type_name = $ldap_usertypes[$this->config->user_type];
  73. unset($ldap_usertypes);
  74. $default = ldap_getdefaults();
  75. // Use defaults if values not given
  76. foreach ($default as $key => $value) {
  77. // watch out - 0, false are correct values too
  78. if (!isset($this->config->{$key}) or $this->config->{$key} == '') {
  79. $this->config->{$key} = $value[$this->config->user_type];
  80. }
  81. }
  82. // Hack prefix to objectclass
  83. if (empty($this->config->objectclass)) {
  84. // Can't send empty filter
  85. $this->config->objectclass = '(objectClass=*)';
  86. } else if (stripos($this->config->objectclass, 'objectClass=') === 0) {
  87. // Value is 'objectClass=some-string-here', so just add ()
  88. // around the value (filter _must_ have them).
  89. $this->config->objectclass = '('.$this->config->objectclass.')';
  90. } else if (strpos($this->config->objectclass, '(') !== 0) {
  91. // Value is 'some-string-not-starting-with-left-parentheses',
  92. // which is assumed to be the objectClass matching value.
  93. // So build a valid filter with it.
  94. $this->config->objectclass = '(objectClass='.$this->config->objectclass.')';
  95. } else {
  96. // There is an additional possible value
  97. // '(some-string-here)', that can be used to specify any
  98. // valid filter string, to select subsets of users based
  99. // on any criteria. For example, we could select the users
  100. // whose objectClass is 'user' and have the
  101. // 'enabledMoodleUser' attribute, with something like:
  102. //
  103. // (&(objectClass=user)(enabledMoodleUser=1))
  104. //
  105. // In this particular case we don't need to do anything,
  106. // so leave $this->config->objectclass as is.
  107. }
  108. }
  109. /**
  110. * Constructor with initialisation.
  111. */
  112. function auth_plugin_ldap() {
  113. $this->authtype = 'ldap';
  114. $this->roleauth = 'auth_ldap';
  115. $this->errorlogtag = '[AUTH LDAP] ';
  116. $this->init_plugin($this->authtype);
  117. }
  118. /**
  119. * Returns true if the username and password work and false if they are
  120. * wrong or don't exist.
  121. *
  122. * @param string $username The username (without system magic quotes)
  123. * @param string $password The password (without system magic quotes)
  124. *
  125. * @return bool Authentication success or failure.
  126. */
  127. function user_login($username, $password) {
  128. if (! function_exists('ldap_bind')) {
  129. print_error('auth_ldapnotinstalled', 'auth_ldap');
  130. return false;
  131. }
  132. if (!$username or !$password) { // Don't allow blank usernames or passwords
  133. return false;
  134. }
  135. $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
  136. $extpassword = textlib::convert($password, 'utf-8', $this->config->ldapencoding);
  137. // Before we connect to LDAP, check if this is an AD SSO login
  138. // if we succeed in this block, we'll return success early.
  139. //
  140. $key = sesskey();
  141. if (!empty($this->config->ntlmsso_enabled) && $key === $password) {
  142. $cf = get_cache_flags($this->pluginconfig.'/ntlmsess');
  143. // We only get the cache flag if we retrieve it before
  144. // it expires (AUTH_NTLMTIMEOUT seconds).
  145. if (!isset($cf[$key]) || $cf[$key] === '') {
  146. return false;
  147. }
  148. $sessusername = $cf[$key];
  149. if ($username === $sessusername) {
  150. unset($sessusername);
  151. unset($cf);
  152. // Check that the user is inside one of the configured LDAP contexts
  153. $validuser = false;
  154. $ldapconnection = $this->ldap_connect();
  155. // if the user is not inside the configured contexts,
  156. // ldap_find_userdn returns false.
  157. if ($this->ldap_find_userdn($ldapconnection, $extusername)) {
  158. $validuser = true;
  159. }
  160. $this->ldap_close();
  161. // Shortcut here - SSO confirmed
  162. return $validuser;
  163. }
  164. } // End SSO processing
  165. unset($key);
  166. $ldapconnection = $this->ldap_connect();
  167. $ldap_user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
  168. // If ldap_user_dn is empty, user does not exist
  169. if (!$ldap_user_dn) {
  170. $this->ldap_close();
  171. return false;
  172. }
  173. // Try to bind with current username and password
  174. $ldap_login = @ldap_bind($ldapconnection, $ldap_user_dn, $extpassword);
  175. // If login fails and we are using MS Active Directory, retrieve the diagnostic
  176. // message to see if this is due to an expired password, or that the user is forced to
  177. // change the password on first login. If it is, only proceed if we can change
  178. // password from Moodle (otherwise we'll get stuck later in the login process).
  179. if (!$ldap_login && ($this->config->user_type == 'ad')
  180. && $this->can_change_password()
  181. && (!empty($this->config->expiration) and ($this->config->expiration == 1))) {
  182. // We need to get the diagnostic message right after the call to ldap_bind(),
  183. // before any other LDAP operation.
  184. ldap_get_option($ldapconnection, LDAP_OPT_DIAGNOSTIC_MESSAGE, $diagmsg);
  185. if ($this->ldap_ad_pwdexpired_from_diagmsg($diagmsg)) {
  186. // If login failed because user must change the password now or the
  187. // password has expired, let the user in. We'll catch this later in the
  188. // login process when we explicitly check for expired passwords.
  189. $ldap_login = true;
  190. }
  191. }
  192. $this->ldap_close();
  193. return $ldap_login;
  194. }
  195. /**
  196. * Reads user information from ldap and returns it in array()
  197. *
  198. * Function should return all information available. If you are saving
  199. * this information to moodle user-table you should honor syncronization flags
  200. *
  201. * @param string $username username
  202. *
  203. * @return mixed array with no magic quotes or false on error
  204. */
  205. function get_userinfo($username) {
  206. $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
  207. $ldapconnection = $this->ldap_connect();
  208. if(!($user_dn = $this->ldap_find_userdn($ldapconnection, $extusername))) {
  209. $this->ldap_close();
  210. return false;
  211. }
  212. $search_attribs = array();
  213. $attrmap = $this->ldap_attributes();
  214. foreach ($attrmap as $key => $values) {
  215. if (!is_array($values)) {
  216. $values = array($values);
  217. }
  218. foreach ($values as $value) {
  219. if (!in_array($value, $search_attribs)) {
  220. array_push($search_attribs, $value);
  221. }
  222. }
  223. }
  224. if (!$user_info_result = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs)) {
  225. $this->ldap_close();
  226. return false; // error!
  227. }
  228. $user_entry = ldap_get_entries_moodle($ldapconnection, $user_info_result);
  229. if (empty($user_entry)) {
  230. $this->ldap_close();
  231. return false; // entry not found
  232. }
  233. $result = array();
  234. foreach ($attrmap as $key => $values) {
  235. if (!is_array($values)) {
  236. $values = array($values);
  237. }
  238. $ldapval = NULL;
  239. foreach ($values as $value) {
  240. $entry = array_change_key_case($user_entry[0], CASE_LOWER);
  241. if (($value == 'dn') || ($value == 'distinguishedname')) {
  242. $result[$key] = $user_dn;
  243. continue;
  244. }
  245. if (!array_key_exists($value, $entry)) {
  246. continue; // wrong data mapping!
  247. }
  248. if (is_array($entry[$value])) {
  249. $newval = textlib::convert($entry[$value][0], $this->config->ldapencoding, 'utf-8');
  250. } else {
  251. $newval = textlib::convert($entry[$value], $this->config->ldapencoding, 'utf-8');
  252. }
  253. if (!empty($newval)) { // favour ldap entries that are set
  254. $ldapval = $newval;
  255. }
  256. }
  257. if (!is_null($ldapval)) {
  258. $result[$key] = $ldapval;
  259. }
  260. }
  261. $this->ldap_close();
  262. return $result;
  263. }
  264. /**
  265. * Reads user information from ldap and returns it in an object
  266. *
  267. * @param string $username username (with system magic quotes)
  268. * @return mixed object or false on error
  269. */
  270. function get_userinfo_asobj($username) {
  271. $user_array = $this->get_userinfo($username);
  272. if ($user_array == false) {
  273. return false; //error or not found
  274. }
  275. $user_array = truncate_userinfo($user_array);
  276. $user = new stdClass();
  277. foreach ($user_array as $key=>$value) {
  278. $user->{$key} = $value;
  279. }
  280. return $user;
  281. }
  282. /**
  283. * Returns all usernames from LDAP
  284. *
  285. * get_userlist returns all usernames from LDAP
  286. *
  287. * @return array
  288. */
  289. function get_userlist() {
  290. return $this->ldap_get_userlist("({$this->config->user_attribute}=*)");
  291. }
  292. /**
  293. * Checks if user exists on LDAP
  294. *
  295. * @param string $username
  296. */
  297. function user_exists($username) {
  298. $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
  299. // Returns true if given username exists on ldap
  300. $users = $this->ldap_get_userlist('('.$this->config->user_attribute.'='.ldap_filter_addslashes($extusername).')');
  301. return count($users);
  302. }
  303. /**
  304. * Creates a new user on LDAP.
  305. * By using information in userobject
  306. * Use user_exists to prevent duplicate usernames
  307. *
  308. * @param mixed $userobject Moodle userobject
  309. * @param mixed $plainpass Plaintext password
  310. */
  311. function user_create($userobject, $plainpass) {
  312. $extusername = textlib::convert($userobject->username, 'utf-8', $this->config->ldapencoding);
  313. $extpassword = textlib::convert($plainpass, 'utf-8', $this->config->ldapencoding);
  314. switch ($this->config->passtype) {
  315. case 'md5':
  316. $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
  317. break;
  318. case 'sha1':
  319. $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
  320. break;
  321. case 'plaintext':
  322. default:
  323. break; // plaintext
  324. }
  325. $ldapconnection = $this->ldap_connect();
  326. $attrmap = $this->ldap_attributes();
  327. $newuser = array();
  328. foreach ($attrmap as $key => $values) {
  329. if (!is_array($values)) {
  330. $values = array($values);
  331. }
  332. foreach ($values as $value) {
  333. if (!empty($userobject->$key) ) {
  334. $newuser[$value] = textlib::convert($userobject->$key, 'utf-8', $this->config->ldapencoding);
  335. }
  336. }
  337. }
  338. //Following sets all mandatory and other forced attribute values
  339. //User should be creted as login disabled untill email confirmation is processed
  340. //Feel free to add your user type and send patches to paca@sci.fi to add them
  341. //Moodle distribution
  342. switch ($this->config->user_type) {
  343. case 'edir':
  344. $newuser['objectClass'] = array('inetOrgPerson', 'organizationalPerson', 'person', 'top');
  345. $newuser['uniqueId'] = $extusername;
  346. $newuser['logindisabled'] = 'TRUE';
  347. $newuser['userpassword'] = $extpassword;
  348. $uadd = ldap_add($ldapconnection, $this->config->user_attribute.'='.ldap_addslashes($extusername).','.$this->config->create_context, $newuser);
  349. break;
  350. case 'rfc2307':
  351. case 'rfc2307bis':
  352. // posixAccount object class forces us to specify a uidNumber
  353. // and a gidNumber. That is quite complicated to generate from
  354. // Moodle without colliding with existing numbers and without
  355. // race conditions. As this user is supposed to be only used
  356. // with Moodle (otherwise the user would exist beforehand) and
  357. // doesn't need to login into a operating system, we assign the
  358. // user the uid of user 'nobody' and gid of group 'nogroup'. In
  359. // addition to that, we need to specify a home directory. We
  360. // use the root directory ('/') as the home directory, as this
  361. // is the only one can always be sure exists. Finally, even if
  362. // it's not mandatory, we specify '/bin/false' as the login
  363. // shell, to prevent the user from login in at the operating
  364. // system level (Moodle ignores this).
  365. $newuser['objectClass'] = array('posixAccount', 'inetOrgPerson', 'organizationalPerson', 'person', 'top');
  366. $newuser['cn'] = $extusername;
  367. $newuser['uid'] = $extusername;
  368. $newuser['uidNumber'] = AUTH_UID_NOBODY;
  369. $newuser['gidNumber'] = AUTH_GID_NOGROUP;
  370. $newuser['homeDirectory'] = '/';
  371. $newuser['loginShell'] = '/bin/false';
  372. // IMPORTANT:
  373. // We have to create the account locked, but posixAccount has
  374. // no attribute to achive this reliably. So we are going to
  375. // modify the password in a reversable way that we can later
  376. // revert in user_activate().
  377. //
  378. // Beware that this can be defeated by the user if we are not
  379. // using MD5 or SHA-1 passwords. After all, the source code of
  380. // Moodle is available, and the user can see the kind of
  381. // modification we are doing and 'undo' it by hand (but only
  382. // if we are using plain text passwords).
  383. //
  384. // Also bear in mind that you need to use a binding user that
  385. // can create accounts and has read/write privileges on the
  386. // 'userPassword' attribute for this to work.
  387. $newuser['userPassword'] = '*'.$extpassword;
  388. $uadd = ldap_add($ldapconnection, $this->config->user_attribute.'='.ldap_addslashes($extusername).','.$this->config->create_context, $newuser);
  389. break;
  390. case 'ad':
  391. // User account creation is a two step process with AD. First you
  392. // create the user object, then you set the password. If you try
  393. // to set the password while creating the user, the operation
  394. // fails.
  395. // Passwords in Active Directory must be encoded as Unicode
  396. // strings (UCS-2 Little Endian format) and surrounded with
  397. // double quotes. See http://support.microsoft.com/?kbid=269190
  398. if (!function_exists('mb_convert_encoding')) {
  399. print_error('auth_ldap_no_mbstring', 'auth_ldap');
  400. }
  401. // Check for invalid sAMAccountName characters.
  402. if (preg_match('#[/\\[\]:;|=,+*?<>@"]#', $extusername)) {
  403. print_error ('auth_ldap_ad_invalidchars', 'auth_ldap');
  404. }
  405. // First create the user account, and mark it as disabled.
  406. $newuser['objectClass'] = array('top', 'person', 'user', 'organizationalPerson');
  407. $newuser['sAMAccountName'] = $extusername;
  408. $newuser['userAccountControl'] = AUTH_AD_NORMAL_ACCOUNT |
  409. AUTH_AD_ACCOUNTDISABLE;
  410. $userdn = 'cn='.ldap_addslashes($extusername).','.$this->config->create_context;
  411. if (!ldap_add($ldapconnection, $userdn, $newuser)) {
  412. print_error('auth_ldap_ad_create_req', 'auth_ldap');
  413. }
  414. // Now set the password
  415. unset($newuser);
  416. $newuser['unicodePwd'] = mb_convert_encoding('"' . $extpassword . '"',
  417. 'UCS-2LE', 'UTF-8');
  418. if(!ldap_modify($ldapconnection, $userdn, $newuser)) {
  419. // Something went wrong: delete the user account and error out
  420. ldap_delete ($ldapconnection, $userdn);
  421. print_error('auth_ldap_ad_create_req', 'auth_ldap');
  422. }
  423. $uadd = true;
  424. break;
  425. default:
  426. print_error('auth_ldap_unsupportedusertype', 'auth_ldap', '', $this->config->user_type_name);
  427. }
  428. $this->ldap_close();
  429. return $uadd;
  430. }
  431. /**
  432. * Returns true if plugin allows resetting of password from moodle.
  433. *
  434. * @return bool
  435. */
  436. function can_reset_password() {
  437. return !empty($this->config->stdchangepassword);
  438. }
  439. /**
  440. * Returns true if plugin allows signup and user creation.
  441. *
  442. * @return bool
  443. */
  444. function can_signup() {
  445. return (!empty($this->config->auth_user_create) and !empty($this->config->create_context));
  446. }
  447. /**
  448. * Sign up a new user ready for confirmation.
  449. * Password is passed in plaintext.
  450. *
  451. * @param object $user new user object
  452. * @param boolean $notify print notice with link and terminate
  453. */
  454. function user_signup($user, $notify=true) {
  455. global $CFG, $DB, $PAGE, $OUTPUT;
  456. require_once($CFG->dirroot.'/user/profile/lib.php');
  457. if ($this->user_exists($user->username)) {
  458. print_error('auth_ldap_user_exists', 'auth_ldap');
  459. }
  460. $plainslashedpassword = $user->password;
  461. unset($user->password);
  462. if (! $this->user_create($user, $plainslashedpassword)) {
  463. print_error('auth_ldap_create_error', 'auth_ldap');
  464. }
  465. $user->id = $DB->insert_record('user', $user);
  466. // Save any custom profile field information
  467. profile_save_data($user);
  468. $this->update_user_record($user->username);
  469. // This will also update the stored hash to the latest algorithm
  470. // if the existing hash is using an out-of-date algorithm (or the
  471. // legacy md5 algorithm).
  472. update_internal_user_password($user, $plainslashedpassword);
  473. $user = $DB->get_record('user', array('id'=>$user->id));
  474. events_trigger('user_created', $user);
  475. if (! send_confirmation_email($user)) {
  476. print_error('noemail', 'auth_ldap');
  477. }
  478. if ($notify) {
  479. $emailconfirm = get_string('emailconfirm');
  480. $PAGE->set_url('/auth/ldap/auth.php');
  481. $PAGE->navbar->add($emailconfirm);
  482. $PAGE->set_title($emailconfirm);
  483. $PAGE->set_heading($emailconfirm);
  484. echo $OUTPUT->header();
  485. notice(get_string('emailconfirmsent', '', $user->email), "{$CFG->wwwroot}/index.php");
  486. } else {
  487. return true;
  488. }
  489. }
  490. /**
  491. * Returns true if plugin allows confirming of new users.
  492. *
  493. * @return bool
  494. */
  495. function can_confirm() {
  496. return $this->can_signup();
  497. }
  498. /**
  499. * Confirm the new user as registered.
  500. *
  501. * @param string $username
  502. * @param string $confirmsecret
  503. */
  504. function user_confirm($username, $confirmsecret) {
  505. global $DB;
  506. $user = get_complete_user_data('username', $username);
  507. if (!empty($user)) {
  508. if ($user->confirmed) {
  509. return AUTH_CONFIRM_ALREADY;
  510. } else if ($user->auth != $this->authtype) {
  511. return AUTH_CONFIRM_ERROR;
  512. } else if ($user->secret == $confirmsecret) { // They have provided the secret key to get in
  513. if (!$this->user_activate($username)) {
  514. return AUTH_CONFIRM_FAIL;
  515. }
  516. $DB->set_field('user', 'confirmed', 1, array('id'=>$user->id));
  517. if ($user->firstaccess == 0) {
  518. $DB->set_field('user', 'firstaccess', time(), array('id'=>$user->id));
  519. }
  520. return AUTH_CONFIRM_OK;
  521. }
  522. } else {
  523. return AUTH_CONFIRM_ERROR;
  524. }
  525. }
  526. /**
  527. * Return number of days to user password expires
  528. *
  529. * If userpassword does not expire it should return 0. If password is already expired
  530. * it should return negative value.
  531. *
  532. * @param mixed $username username
  533. * @return integer
  534. */
  535. function password_expire($username) {
  536. $result = 0;
  537. $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
  538. $ldapconnection = $this->ldap_connect();
  539. $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
  540. $search_attribs = array($this->config->expireattr);
  541. $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
  542. if ($sr) {
  543. $info = ldap_get_entries_moodle($ldapconnection, $sr);
  544. if (!empty ($info)) {
  545. $info = array_change_key_case($info[0], CASE_LOWER);
  546. if (isset($info[$this->config->expireattr][0])) {
  547. $expiretime = $this->ldap_expirationtime2unix($info[$this->config->expireattr][0], $ldapconnection, $user_dn);
  548. if ($expiretime != 0) {
  549. $now = time();
  550. if ($expiretime > $now) {
  551. $result = ceil(($expiretime - $now) / DAYSECS);
  552. } else {
  553. $result = floor(($expiretime - $now) / DAYSECS);
  554. }
  555. }
  556. }
  557. }
  558. } else {
  559. error_log($this->errorlogtag.get_string('didtfindexpiretime', 'auth_ldap'));
  560. }
  561. return $result;
  562. }
  563. /**
  564. * Syncronizes user fron external LDAP server to moodle user table
  565. *
  566. * Sync is now using username attribute.
  567. *
  568. * Syncing users removes or suspends users that dont exists anymore in external LDAP.
  569. * Creates new users and updates coursecreator status of users.
  570. *
  571. * @param bool $do_updates will do pull in data updates from LDAP if relevant
  572. */
  573. function sync_users($do_updates=true) {
  574. global $CFG, $DB;
  575. print_string('connectingldap', 'auth_ldap');
  576. $ldapconnection = $this->ldap_connect();
  577. $dbman = $DB->get_manager();
  578. /// Define table user to be created
  579. $table = new xmldb_table('tmp_extuser');
  580. $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
  581. $table->add_field('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
  582. $table->add_field('mnethostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
  583. $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
  584. $table->add_index('username', XMLDB_INDEX_UNIQUE, array('mnethostid', 'username'));
  585. print_string('creatingtemptable', 'auth_ldap', 'tmp_extuser');
  586. $dbman->create_temp_table($table);
  587. ////
  588. //// get user's list from ldap to sql in a scalable fashion
  589. ////
  590. // prepare some data we'll need
  591. $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
  592. $contexts = explode(';', $this->config->contexts);
  593. if (!empty($this->config->create_context)) {
  594. array_push($contexts, $this->config->create_context);
  595. }
  596. $ldap_pagedresults = ldap_paged_results_supported($this->config->ldap_version);
  597. $ldap_cookie = '';
  598. foreach ($contexts as $context) {
  599. $context = trim($context);
  600. if (empty($context)) {
  601. continue;
  602. }
  603. do {
  604. if ($ldap_pagedresults) {
  605. ldap_control_paged_result($ldapconnection, $this->config->pagesize, true, $ldap_cookie);
  606. }
  607. if ($this->config->search_sub) {
  608. // Use ldap_search to find first user from subtree.
  609. $ldap_result = ldap_search($ldapconnection, $context, $filter, array($this->config->user_attribute));
  610. } else {
  611. // Search only in this context.
  612. $ldap_result = ldap_list($ldapconnection, $context, $filter, array($this->config->user_attribute));
  613. }
  614. if(!$ldap_result) {
  615. continue;
  616. }
  617. if ($ldap_pagedresults) {
  618. ldap_control_paged_result_response($ldapconnection, $ldap_result, $ldap_cookie);
  619. }
  620. if ($entry = @ldap_first_entry($ldapconnection, $ldap_result)) {
  621. do {
  622. $value = ldap_get_values_len($ldapconnection, $entry, $this->config->user_attribute);
  623. $value = textlib::convert($value[0], $this->config->ldapencoding, 'utf-8');
  624. $this->ldap_bulk_insert($value);
  625. } while ($entry = ldap_next_entry($ldapconnection, $entry));
  626. }
  627. unset($ldap_result); // Free mem.
  628. } while ($ldap_pagedresults && !empty($ldap_cookie));
  629. }
  630. // If LDAP paged results were used, the current connection must be completely
  631. // closed and a new one created, to work without paged results from here on.
  632. if ($ldap_pagedresults) {
  633. $this->ldap_close(true);
  634. $ldapconnection = $this->ldap_connect();
  635. }
  636. /// preserve our user database
  637. /// if the temp table is empty, it probably means that something went wrong, exit
  638. /// so as to avoid mass deletion of users; which is hard to undo
  639. $count = $DB->count_records_sql('SELECT COUNT(username) AS count, 1 FROM {tmp_extuser}');
  640. if ($count < 1) {
  641. print_string('didntgetusersfromldap', 'auth_ldap');
  642. exit;
  643. } else {
  644. print_string('gotcountrecordsfromldap', 'auth_ldap', $count);
  645. }
  646. /// User removal
  647. // Find users in DB that aren't in ldap -- to be removed!
  648. // this is still not as scalable (but how often do we mass delete?)
  649. if ($this->config->removeuser != AUTH_REMOVEUSER_KEEP) {
  650. $sql = 'SELECT u.*
  651. FROM {user} u
  652. LEFT JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
  653. WHERE u.auth = ?
  654. AND u.deleted = 0
  655. AND e.username IS NULL';
  656. $remove_users = $DB->get_records_sql($sql, array($this->authtype));
  657. if (!empty($remove_users)) {
  658. print_string('userentriestoremove', 'auth_ldap', count($remove_users));
  659. foreach ($remove_users as $user) {
  660. if ($this->config->removeuser == AUTH_REMOVEUSER_FULLDELETE) {
  661. if (delete_user($user)) {
  662. echo "\t"; print_string('auth_dbdeleteuser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
  663. } else {
  664. echo "\t"; print_string('auth_dbdeleteusererror', 'auth_db', $user->username); echo "\n";
  665. }
  666. } else if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
  667. $updateuser = new stdClass();
  668. $updateuser->id = $user->id;
  669. $updateuser->auth = 'nologin';
  670. $DB->update_record('user', $updateuser);
  671. echo "\t"; print_string('auth_dbsuspenduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
  672. }
  673. }
  674. } else {
  675. print_string('nouserentriestoremove', 'auth_ldap');
  676. }
  677. unset($remove_users); // free mem!
  678. }
  679. /// Revive suspended users
  680. if (!empty($this->config->removeuser) and $this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
  681. $sql = "SELECT u.id, u.username
  682. FROM {user} u
  683. JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
  684. WHERE u.auth = 'nologin' AND u.deleted = 0";
  685. $revive_users = $DB->get_records_sql($sql);
  686. if (!empty($revive_users)) {
  687. print_string('userentriestorevive', 'auth_ldap', count($revive_users));
  688. foreach ($revive_users as $user) {
  689. $updateuser = new stdClass();
  690. $updateuser->id = $user->id;
  691. $updateuser->auth = $this->authtype;
  692. $DB->update_record('user', $updateuser);
  693. echo "\t"; print_string('auth_dbreviveduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
  694. }
  695. } else {
  696. print_string('nouserentriestorevive', 'auth_ldap');
  697. }
  698. unset($revive_users);
  699. }
  700. /// User Updates - time-consuming (optional)
  701. if ($do_updates) {
  702. // Narrow down what fields we need to update
  703. $all_keys = array_keys(get_object_vars($this->config));
  704. $updatekeys = array();
  705. foreach ($all_keys as $key) {
  706. if (preg_match('/^field_updatelocal_(.+)$/', $key, $match)) {
  707. // If we have a field to update it from
  708. // and it must be updated 'onlogin' we
  709. // update it on cron
  710. if (!empty($this->config->{'field_map_'.$match[1]})
  711. and $this->config->{$match[0]} === 'onlogin') {
  712. array_push($updatekeys, $match[1]); // the actual key name
  713. }
  714. }
  715. }
  716. unset($all_keys); unset($key);
  717. } else {
  718. print_string('noupdatestobedone', 'auth_ldap');
  719. }
  720. if ($do_updates and !empty($updatekeys)) { // run updates only if relevant
  721. $users = $DB->get_records_sql('SELECT u.username, u.id
  722. FROM {user} u
  723. WHERE u.deleted = 0 AND u.auth = ? AND u.mnethostid = ?',
  724. array($this->authtype, $CFG->mnet_localhost_id));
  725. if (!empty($users)) {
  726. print_string('userentriestoupdate', 'auth_ldap', count($users));
  727. $sitecontext = context_system::instance();
  728. if (!empty($this->config->creators) and !empty($this->config->memberattribute)
  729. and $roles = get_archetype_roles('coursecreator')) {
  730. $creatorrole = array_shift($roles); // We can only use one, let's use the first one
  731. } else {
  732. $creatorrole = false;
  733. }
  734. $transaction = $DB->start_delegated_transaction();
  735. $xcount = 0;
  736. $maxxcount = 100;
  737. foreach ($users as $user) {
  738. echo "\t"; print_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id));
  739. if (!$this->update_user_record($user->username, $updatekeys)) {
  740. echo ' - '.get_string('skipped');
  741. }
  742. echo "\n";
  743. $xcount++;
  744. // Update course creators if needed
  745. if ($creatorrole !== false) {
  746. if ($this->iscreator($user->username)) {
  747. role_assign($creatorrole->id, $user->id, $sitecontext->id, $this->roleauth);
  748. } else {
  749. role_unassign($creatorrole->id, $user->id, $sitecontext->id, $this->roleauth);
  750. }
  751. }
  752. }
  753. $transaction->allow_commit();
  754. unset($users); // free mem
  755. }
  756. } else { // end do updates
  757. print_string('noupdatestobedone', 'auth_ldap');
  758. }
  759. /// User Additions
  760. // Find users missing in DB that are in LDAP
  761. // and gives me a nifty object I don't want.
  762. // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
  763. $sql = 'SELECT e.id, e.username
  764. FROM {tmp_extuser} e
  765. LEFT JOIN {user} u ON (e.username = u.username AND e.mnethostid = u.mnethostid)
  766. WHERE u.id IS NULL';
  767. $add_users = $DB->get_records_sql($sql);
  768. if (!empty($add_users)) {
  769. print_string('userentriestoadd', 'auth_ldap', count($add_users));
  770. $sitecontext = context_system::instance();
  771. if (!empty($this->config->creators) and !empty($this->config->memberattribute)
  772. and $roles = get_archetype_roles('coursecreator')) {
  773. $creatorrole = array_shift($roles); // We can only use one, let's use the first one
  774. } else {
  775. $creatorrole = false;
  776. }
  777. $transaction = $DB->start_delegated_transaction();
  778. foreach ($add_users as $user) {
  779. $user = $this->get_userinfo_asobj($user->username);
  780. // Prep a few params
  781. $user->modified = time();
  782. $user->confirmed = 1;
  783. $user->auth = $this->authtype;
  784. $user->mnethostid = $CFG->mnet_localhost_id;
  785. // get_userinfo_asobj() might have replaced $user->username with the value
  786. // from the LDAP server (which can be mixed-case). Make sure it's lowercase
  787. $user->username = trim(textlib::strtolower($user->username));
  788. if (empty($user->lang)) {
  789. $user->lang = $CFG->lang;
  790. }
  791. $id = $DB->insert_record('user', $user);
  792. echo "\t"; print_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username, 'id'=>$id)); echo "\n";
  793. if (!empty($this->config->forcechangepassword)) {
  794. set_user_preference('auth_forcepasswordchange', 1, $id);
  795. }
  796. // Add course creators if needed
  797. if ($creatorrole !== false and $this->iscreator($user->username)) {
  798. role_assign($creatorrole->id, $id, $sitecontext->id, $this->roleauth);
  799. }
  800. }
  801. $transaction->allow_commit();
  802. unset($add_users); // free mem
  803. } else {
  804. print_string('nouserstobeadded', 'auth_ldap');
  805. }
  806. $dbman->drop_table($table);
  807. $this->ldap_close();
  808. return true;
  809. }
  810. /**
  811. * Update a local user record from an external source.
  812. * This is a lighter version of the one in moodlelib -- won't do
  813. * expensive ops such as enrolment.
  814. *
  815. * If you don't pass $updatekeys, there is a performance hit and
  816. * values removed from LDAP won't be removed from moodle.
  817. *
  818. * @param string $username username
  819. * @param boolean $updatekeys true to update the local record with the external LDAP values.
  820. */
  821. function update_user_record($username, $updatekeys = false) {
  822. global $CFG, $DB;
  823. // Just in case check text case
  824. $username = trim(textlib::strtolower($username));
  825. // Get the current user record
  826. $user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id));
  827. if (empty($user)) { // trouble
  828. error_log($this->errorlogtag.get_string('auth_dbusernotexist', 'auth_db', '', $username));
  829. print_error('auth_dbusernotexist', 'auth_db', '', $username);
  830. die;
  831. }
  832. // Protect the userid from being overwritten
  833. $userid = $user->id;
  834. if ($newinfo = $this->get_userinfo($username)) {
  835. $newinfo = truncate_userinfo($newinfo);
  836. if (empty($updatekeys)) { // all keys? this does not support removing values
  837. $updatekeys = array_keys($newinfo);
  838. }
  839. foreach ($updatekeys as $key) {
  840. if (isset($newinfo[$key])) {
  841. $value = $newinfo[$key];
  842. } else {
  843. $value = '';
  844. }
  845. if (!empty($this->config->{'field_updatelocal_' . $key})) {
  846. if ($user->{$key} != $value) { // only update if it's changed
  847. $DB->set_field('user', $key, $value, array('id'=>$userid));
  848. }
  849. }
  850. }
  851. } else {
  852. return false;
  853. }
  854. return $DB->get_record('user', array('id'=>$userid, 'deleted'=>0));
  855. }
  856. /**
  857. * Bulk insert in SQL's temp table
  858. */
  859. function ldap_bulk_insert($username) {
  860. global $DB, $CFG;
  861. $username = textlib::strtolower($username); // usernames are __always__ lowercase.
  862. $DB->insert_record_raw('tmp_extuser', array('username'=>$username,
  863. 'mnethostid'=>$CFG->mnet_localhost_id), false, true);
  864. echo '.';
  865. }
  866. /**
  867. * Activates (enables) user in external LDAP so user can login
  868. *
  869. * @param mixed $username
  870. * @return boolean result
  871. */
  872. function user_activate($username) {
  873. $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
  874. $ldapconnection = $this->ldap_connect();
  875. $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
  876. switch ($this->config->user_type) {
  877. case 'edir':
  878. $newinfo['loginDisabled'] = 'FALSE';
  879. break;
  880. case 'rfc2307':
  881. case 'rfc2307bis':
  882. // Remember that we add a '*' character in front of the
  883. // external password string to 'disable' the account. We just
  884. // need to remove it.
  885. $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
  886. array('userPassword'));
  887. $info = ldap_get_entries($ldapconnection, $sr);
  888. $info[0] = array_change_key_case($info[0], CASE_LOWER);
  889. $newinfo['userPassword'] = ltrim($info[0]['userpassword'][0], '*');
  890. break;
  891. case 'ad':
  892. // We need to unset the ACCOUNTDISABLE bit in the
  893. // userAccountControl attribute ( see
  894. // http://support.microsoft.com/kb/305144 )
  895. $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
  896. array('userAccountControl'));
  897. $info = ldap_get_entries($ldapconnection, $sr);
  898. $info[0] = array_change_key_case($info[0], CASE_LOWER);
  899. $newinfo['userAccountControl'] = $info[0]['useraccountcontrol'][0]
  900. & (~AUTH_AD_ACCOUNTDISABLE);
  901. break;
  902. default:
  903. print_error('user_activatenotsupportusertype', 'auth_ldap', '', $this->config->user_type_name);
  904. }
  905. $result = ldap_modify($ldapconnection, $userdn, $newinfo);
  906. $this->ldap_close();
  907. return $result;
  908. }
  909. /**
  910. * Returns true if user should be coursecreator.
  911. *
  912. * @param mixed $username username (without system magic quotes)
  913. * @return mixed result null if course creators is not configured, boolean otherwise.
  914. */
  915. function iscreator($username) {
  916. if (empty($this->config->creators) or empty($this->config->memberattribute)) {
  917. return null;
  918. }
  919. $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
  920. $ldapconnection = $this->ldap_connect();
  921. if ($this->config->memberattribute_isdn) {
  922. if(!($userid = $this->ldap_find_userdn($ldapconnection, $extusername))) {
  923. return false;
  924. }
  925. } else {
  926. $userid = $extusername;
  927. }
  928. $group_dns = explode(';', $this->config->creators);
  929. $creator = ldap_isgroupmember($ldapconnection, $userid, $group_dns, $this->config->memberattribute);
  930. $this->ldap_close();
  931. return $creator;
  932. }
  933. /**
  934. * Called when the user record is updated.
  935. *
  936. * Modifies user in external LDAP server. It takes olduser (before
  937. * changes) and newuser (after changes) compares information and
  938. * saves modified information to external LDAP server.
  939. *
  940. * @param mixed $olduser Userobject before modifications (without system magic quotes)
  941. * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
  942. * @return boolean result
  943. *
  944. */
  945. function user_update($olduser, $newuser) {
  946. global $USER;
  947. if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
  948. error_log($this->errorlogtag.get_string('renamingnotallowed', 'auth_ldap'));
  949. return false;
  950. }
  951. if (isset($olduser->auth) and $olduser->auth != $this->authtype) {
  952. return true; // just change auth and skip update
  953. }
  954. $attrmap = $this->ldap_attributes();
  955. // Before doing anything else, make sure we really need to update anything
  956. // in the external LDAP server.
  957. $update_external = false;
  958. foreach ($attrmap as $key => $ldapkeys) {
  959. if (!empty($this->config->{'field_updateremote_'.$key})) {
  960. $update_external = true;
  961. break;
  962. }
  963. }
  964. if (!$update_external) {
  965. return true;
  966. }
  967. $extoldusername = textlib::convert($olduser->username, 'utf-8', $this->config->ldapencoding);
  968. $ldapconnection = $this->ldap_connect();
  969. $search_attribs = array();
  970. foreach ($attrmap as $key => $values) {
  971. if (!is_array($values)) {
  972. $values = array($values);
  973. }
  974. foreach ($values as $value) {
  975. if (!in_array($value, $search_attribs)) {
  976. array_push($search_attribs, $value);
  977. }
  978. }
  979. }
  980. if(!($user_dn = $this->ldap_find_userdn($ldapconnection, $extoldusername))) {
  981. return false;
  982. }
  983. $user_info_result = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
  984. if ($user_info_result) {
  985. $user_entry = ldap_get_entries_moodle($ldapconnection, $user_info_result);
  986. if (empty($user_entry)) {
  987. $attribs = join (', ', $search_attribs);
  988. error_log($this->errorlogtag.get_string('updateusernotfound', 'auth_ldap',
  989. array('userdn'=>$user_dn,
  990. 'attribs'=>$attribs)));
  991. return false; // old user not found!
  992. } else if (count($user_entry) > 1) {
  993. error_log($this->errorlogtag.get_string('morethanoneuser', 'auth_ldap'));
  994. return false;
  995. }
  996. $user_entry = array_change_key_case($user_entry[0], CASE_LOWER);
  997. foreach ($attrmap as $key => $ldapkeys) {
  998. // Only process if the moodle field ($key) has changed and we
  999. // are set to update LDAP with it
  1000. if (isset($olduser->$key) and isset($newuser->$key)
  1001. and $olduser->$key !== $newuser->$key
  1002. and !empty($this->config->{'field_updateremote_'. $key})) {
  1003. // For ldap values that could be in more than one
  1004. // ldap key, we will do our best to match
  1005. // where they came from
  1006. $ambiguous = true;
  1007. $changed = false;
  1008. if (!is_array($ldapkeys)) {
  1009. $ldapkeys = array($ldapkeys);
  1010. }
  1011. if (count($ldapkeys) < 2) {
  1012. $ambiguous = false;
  1013. }
  1014. $nuvalue = textlib::convert($newuser->$key, 'utf-8', $this->config->ldapencoding);
  1015. empty($nuvalue) ? $nuvalue = array() : $nuvalue;
  1016. $ouvalue = textlib::convert($olduser->$key, 'utf-8', $this->config->ldapencoding);
  1017. foreach ($ldapkeys as $ldapkey) {
  1018. $ldapkey = $ldapkey;
  1019. $ldapvalue = $user_entry[$ldapkey][0];
  1020. if (!$ambiguous) {
  1021. // Skip update if the values already match
  1022. if ($nuvalue !== $ldapvalue) {
  1023. // This might fail due to schema validation
  1024. if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
  1025. continue;
  1026. } else {
  1027. error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
  1028. array('errno'=>ldap_errno($ldapconnection),
  1029. 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
  1030. 'key'=>$key,
  1031. 'ouvalue'=>$ouvalue,
  1032. 'nuvalue'=>$nuvalue)));
  1033. continue;
  1034. }
  1035. }
  1036. } else {
  1037. // Ambiguous. Value empty before in Moodle (and LDAP) - use
  1038. // 1st ldap candidate field, no need to guess
  1039. if ($ouvalue === '') { // value empty before - use 1st ldap candidate
  1040. // This might fail due to schema validation
  1041. if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
  1042. $changed = true;
  1043. continue;
  1044. } else {
  1045. error_log($this->errorlogtag.get_string ('updat