PageRenderTime 56ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/auth/ldap/auth.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 2261 lines | 1395 code | 243 blank | 623 comment | 320 complexity | 54b0b212440c6fc603d9e14761f3172a MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-3.0

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

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

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