PageRenderTime 53ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/auth/ldap/auth.php

https://bitbucket.org/ngmares/moodle
PHP | 2019 lines | 1276 code | 219 blank | 524 comment | 263 complexity | 06548fcd0852aebd2acaec4e0c266d50 MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-3.0, MPL-2.0-no-copyleft-exception, GPL-3.0, Apache-2.0, BSD-3-Clause

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

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