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