4 * ldaplib.php - LDAP functions & data library
6 * Library file of miscellaneous general-purpose LDAP functions and
7 * data structures, useful for both ldap authentication (or ldap based
8 * authentication like CAS) and enrolment plugins.
10 * @author Iñaki Arenaza
13 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
14 * @copyright 2010 onwards Iñaki Arenaza
15 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
18 defined('MOODLE_INTERNAL') ||
die();
20 // rootDSE is defined as the root of the directory data tree on a directory server.
21 if (!defined('ROOTDSE')) {
22 define ('ROOTDSE', '');
25 // Default page size when using LDAP paged results
26 if (!defined('LDAP_DEFAULT_PAGESIZE')) {
27 define('LDAP_DEFAULT_PAGESIZE', 250);
31 * Returns predefined user types
33 * @return array of predefined user types
35 function ldap_supported_usertypes() {
37 $types['edir'] = 'Novell Edirectory';
38 $types['rfc2307'] = 'posixAccount (rfc2307)';
39 $types['rfc2307bis'] = 'posixAccount (rfc2307bis)';
40 $types['samba'] = 'sambaSamAccount (v.3.0.7)';
41 $types['ad'] = 'MS ActiveDirectory';
42 $types['default'] = get_string('default');
47 * Initializes needed variables for ldap-module
49 * Uses names defined in ldap_supported_usertypes.
50 * $default is first defined as:
51 * $default['pseudoname'] = array(
52 * 'typename1' => 'value',
53 * 'typename2' => 'value'
57 * @return array of default values
59 function ldap_getdefaults() {
60 // All the values have to be written in lowercase, even if the
61 // standard LDAP attributes are mixed-case
62 $default['objectclass'] = array(
64 'rfc2307' => 'posixaccount',
65 'rfc2307bis' => 'posixaccount',
66 'samba' => 'sambasamaccount',
67 'ad' => '(samaccounttype=805306368)',
70 $default['user_attribute'] = array(
73 'rfc2307bis' => 'uid',
78 $default['suspended_attribute'] = array(
86 $default['memberattribute'] = array(
88 'rfc2307' => 'member',
89 'rfc2307bis' => 'member',
94 $default['memberattribute_isdn'] = array(
98 'samba' => '0', // is this right?
102 $default['expireattr'] = array (
103 'edir' => 'passwordexpirationtime',
104 'rfc2307' => 'shadowexpire',
105 'rfc2307bis' => 'shadowexpire',
106 'samba' => '', // No support yet
107 'ad' => 'pwdlastset',
114 * Checks if user belongs to specific group(s) or is in a subtree.
116 * Returns true if user belongs to a group in grupdns string OR if the
117 * DN of the user is in a subtree of the DN provided as "group"
119 * @param mixed $ldapconnection A valid LDAP connection.
120 * @param string $userid LDAP user id (dn/cn/uid/...) to test membership for.
121 * @param array $group_dns arrary of group dn
122 * @param string $member_attrib the name of the membership attribute.
126 function ldap_isgroupmember($ldapconnection, $userid, $group_dns, $member_attrib) {
127 if (empty($ldapconnection) ||
empty($userid) ||
empty($group_dns) ||
empty($member_attrib)) {
132 foreach ($group_dns as $group) {
133 $group = trim($group);
138 // Check cheaply if the user's DN sits in a subtree of the
139 // "group" DN provided. Granted, this isn't a proper LDAP
140 // group, but it's a popular usage.
141 if (stripos(strrev(strtolower($userid)), strrev(strtolower($group))) === 0) {
146 $search = ldap_read($ldapconnection, $group,
147 '('.$member_attrib.'='.ldap_filter_addslashes($userid).')',
148 array($member_attrib));
150 if (!empty($search) && ldap_count_entries($ldapconnection, $search)) {
151 $info = ldap_get_entries_moodle($ldapconnection, $search);
152 if (count($info) > 0 ) {
153 // User is member of group
164 * Tries connect to specified ldap servers. Returns a valid LDAP
165 * connection or false.
167 * @param string $host_url
168 * @param integer $ldap_version either 2 (LDAPv2) or 3 (LDAPv3).
169 * @param string $user_type the configured user type for this connection.
170 * @param string $bind_dn the binding user dn. If an emtpy string, anonymous binding is used.
171 * @param string $bind_pw the password for the binding user. Ignored for anonymous bindings.
172 * @param boolean $opt_deref whether to set LDAP_OPT_DEREF on this connection or not.
173 * @param string &$debuginfo the debugging information in case the connection fails.
174 * @param boolean $start_tls whether to use LDAP with TLS (not to be confused with LDAP+SSL)
175 * @return mixed connection result or false.
177 function ldap_connect_moodle($host_url, $ldap_version, $user_type, $bind_dn, $bind_pw, $opt_deref, &$debuginfo, $start_tls=false) {
178 if (empty($host_url) ||
empty($ldap_version) ||
empty($user_type)) {
179 $debuginfo = 'No LDAP Host URL, Version or User Type specified in your LDAP settings';
184 $urls = explode(';', $host_url);
185 foreach ($urls as $server) {
186 $server = trim($server);
187 if (empty($server)) {
191 $connresult = ldap_connect($server); // ldap_connect returns ALWAYS true
193 if (!empty($ldap_version)) {
194 ldap_set_option($connresult, LDAP_OPT_PROTOCOL_VERSION
, $ldap_version);
198 if ($user_type === 'ad') {
199 ldap_set_option($connresult, LDAP_OPT_REFERRALS
, 0);
202 if (!empty($opt_deref)) {
203 ldap_set_option($connresult, LDAP_OPT_DEREF
, $opt_deref);
206 if ($start_tls && (!ldap_start_tls($connresult))) {
207 $debuginfo .= "Server: '$server', Connection: '$connresult', STARTTLS failed.\n";
211 if (!empty($bind_dn)) {
212 $bindresult = @ldap_bind
($connresult, $bind_dn, $bind_pw);
215 $bindresult = @ldap_bind
($connresult);
222 $debuginfo .= "Server: '$server', Connection: '$connresult', Bind result: '$bindresult'\n";
225 // If any of servers were alive we have already returned connection.
230 * Search specified contexts for username and return the user dn like:
231 * cn=username,ou=suborg,o=org
233 * @param mixed $ldapconnection a valid LDAP connection.
234 * @param mixed $username username (external LDAP encoding, no db slashes).
235 * @param array $contexts contexts to look for the user.
236 * @param string $objectclass objectlass of the user (in LDAP filter syntax).
237 * @param string $search_attrib the attribute use to look for the user.
238 * @param boolean $search_sub whether to search subcontexts or not.
239 * @return mixed the user dn (external LDAP encoding, no db slashes) or false
242 function ldap_find_userdn($ldapconnection, $username, $contexts, $objectclass, $search_attrib, $search_sub) {
243 if (empty($ldapconnection) ||
empty($username) ||
empty($contexts) ||
empty($objectclass) ||
empty($search_attrib)) {
247 // Default return value
248 $ldap_user_dn = false;
250 // Get all contexts and look for first matching user
251 foreach ($contexts as $context) {
252 $context = trim($context);
253 if (empty($context)) {
258 $ldap_result = @ldap_search
($ldapconnection, $context,
259 '(&'.$objectclass.'('.$search_attrib.'='.ldap_filter_addslashes($username).'))',
260 array($search_attrib));
262 $ldap_result = @ldap_list
($ldapconnection, $context,
263 '(&'.$objectclass.'('.$search_attrib.'='.ldap_filter_addslashes($username).'))',
264 array($search_attrib));
268 continue; // Not found in this context.
271 $entry = ldap_first_entry($ldapconnection, $ldap_result);
273 $ldap_user_dn = ldap_get_dn($ldapconnection, $entry);
278 return $ldap_user_dn;
282 * Normalise the supplied objectclass filter.
284 * This normalisation is a rudimentary attempt to format the objectclass filter correctly.
286 * @param string $objectclass The objectclass to normalise
287 * @param string $default The default objectclass value to use if no objectclass was supplied
288 * @return string The normalised objectclass.
290 function ldap_normalise_objectclass($objectclass, $default = '*') {
291 if (empty($objectclass)) {
292 // Can't send empty filter.
293 $return = sprintf('(objectClass=%s)', $default);
294 } else if (stripos($objectclass, 'objectClass=') === 0) {
295 // Value is 'objectClass=some-string-here', so just add () around the value (filter _must_ have them).
296 $return = sprintf('(%s)', $objectclass);
297 } else if (stripos($objectclass, '(') !== 0) {
298 // Value is 'some-string-not-starting-with-left-parentheses', which is assumed to be the objectClass matching value.
299 // Build a valid filter using the value it.
300 $return = sprintf('(objectClass=%s)', $objectclass);
302 // There is an additional possible value '(some-string-here)', that can be used to specify any valid filter
303 // string, to select subsets of users based on any criteria.
305 // For example, we could select the users whose objectClass is 'user' and have the 'enabledMoodleUser'
306 // attribute, with something like:
308 // (&(objectClass=user)(enabledMoodleUser=1))
310 // In this particular case we don't need to do anything, so leave $this->config->objectclass as is.
311 $return = $objectclass;
318 * Returns values like ldap_get_entries but is binary compatible and
319 * returns all attributes as array.
321 * @param mixed $ldapconnection A valid LDAP connection
322 * @param mixed $searchresult A search result from ldap_search, ldap_list, etc.
323 * @return array ldap-entries with lower-cased attributes as indexes
325 function ldap_get_entries_moodle($ldapconnection, $searchresult) {
326 if (empty($ldapconnection) ||
empty($searchresult)) {
332 $entry = ldap_first_entry($ldapconnection, $searchresult);
337 $attributes = array_change_key_case(ldap_get_attributes($ldapconnection, $entry), CASE_LOWER
);
338 for ($j = 0; $j < $attributes['count']; $j++
) {
339 $values = ldap_get_values_len($ldapconnection, $entry, $attributes[$j]);
340 if (is_array($values)) {
341 $result[$i][$attributes[$j]] = $values;
343 $result[$i][$attributes[$j]] = array($values);
347 } while ($entry = ldap_next_entry($ldapconnection, $entry));
353 * Quote control characters in texts used in LDAP filters - see RFC 4515/2254
355 * @param string filter string to quote
356 * @return string the filter string quoted
358 function ldap_filter_addslashes($text) {
359 $text = str_replace('\\', '\\5c', $text);
360 $text = str_replace(array('*', '(', ')', "\0"),
361 array('\\2a', '\\28', '\\29', '\\00'), $text);
365 if(!defined('LDAP_DN_SPECIAL_CHARS')) {
366 define('LDAP_DN_SPECIAL_CHARS', 0);
368 if(!defined('LDAP_DN_SPECIAL_CHARS_QUOTED_NUM')) {
369 define('LDAP_DN_SPECIAL_CHARS_QUOTED_NUM', 1);
371 if(!defined('LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA')) {
372 define('LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA', 2);
374 if(!defined('LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA_REGEX')) {
375 define('LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA_REGEX', 3);
379 * The order of the special characters in these arrays _IS IMPORTANT_.
380 * Make sure '\\5C' (and '\\') are the first elements of the arrays.
381 * Otherwise we'll double replace '\' with '\5C' which is Bad(tm)
383 function ldap_get_dn_special_chars() {
384 static $specialchars = null;
386 if ($specialchars !== null) {
387 return $specialchars;
390 $specialchars = array (
391 LDAP_DN_SPECIAL_CHARS
=> array('\\', ' ', '"', '#', '+', ',', ';', '<', '=', '>', "\0"),
392 LDAP_DN_SPECIAL_CHARS_QUOTED_NUM
=> array('\\5c','\\20','\\22','\\23','\\2b','\\2c','\\3b','\\3c','\\3d','\\3e','\\00'),
393 LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA
=> array('\\\\','\\ ', '\\"', '\\#', '\\+', '\\,', '\\;', '\\<', '\\=', '\\>', '\\00'),
395 $alpharegex = implode('|', array_map (function ($expr) { return preg_quote($expr); },
396 $specialchars[LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA
]));
397 $specialchars[LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA_REGEX
] = $alpharegex;
399 return $specialchars;
403 * Quote control characters in AttributeValue parts of a RelativeDistinguishedName
404 * used in LDAP distinguished names - See RFC 4514/2253
406 * @param string the AttributeValue to quote
407 * @return string the AttributeValue quoted
409 function ldap_addslashes($text) {
410 $special_dn_chars = ldap_get_dn_special_chars();
412 // Use the preferred/universal quotation method: ESC HEX HEX
413 // (i.e., the 'numerically' quoted characters)
414 $text = str_replace ($special_dn_chars[LDAP_DN_SPECIAL_CHARS
],
415 $special_dn_chars[LDAP_DN_SPECIAL_CHARS_QUOTED_NUM
],
421 * Unquote control characters in AttributeValue parts of a RelativeDistinguishedName
422 * used in LDAP distinguished names - See RFC 4514/2253
424 * @param string the AttributeValue quoted
425 * @return string the AttributeValue unquoted
427 function ldap_stripslashes($text) {
428 $specialchars = ldap_get_dn_special_chars();
430 // We can't unquote in two steps, as we end up unquoting too much in certain cases. So
431 // we need to build a regexp containing both the 'numerically' and 'alphabetically'
432 // quoted characters. We don't use LDAP_DN_SPECIAL_CHARS_QUOTED_NUM because the
433 // standard allows us to quote any character with this encoding, not just the special
435 // @TODO: This still misses some special (and rarely used) cases, but we need
436 // a full state machine to handle them.
437 $quoted = '/(\\\\[0-9A-Fa-f]{2}|' . $specialchars[LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA_REGEX
] . ')/';
438 $text = preg_replace_callback($quoted,
439 function ($match) use ($specialchars) {
440 if (ctype_xdigit(ltrim($match[1], '\\'))) {
441 return chr(hexdec($match[1]));
443 return str_replace($specialchars[LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA
],
444 $specialchars[LDAP_DN_SPECIAL_CHARS
],
455 * Check if we use LDAP version 3, otherwise the server cannot use them.
457 * @param ldapversion integer The LDAP protocol version we use.
459 * @return boolean true is paged results can be used, false otherwise.
461 function ldap_paged_results_supported($ldapversion) {
462 if ((int)$ldapversion === 3) {