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