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

/moodle/auth/ldap/auth.php

#
PHP | 2025 lines | 1284 code | 218 blank | 523 comment | 263 complexity | 69b390157c4b3ce77e7d9c7cc9523eb9 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, Apache-2.0

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

Large files files are truncated, but you can click here to view the full file