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', '');
26 * Returns predefined user types
28 * @return array of predefined user types
30 function ldap_supported_usertypes() {
32 $types['edir'] = 'Novell Edirectory';
33 $types['rfc2307'] = 'posixAccount (rfc2307)';
34 $types['rfc2307bis'] = 'posixAccount (rfc2307bis)';
35 $types['samba'] = 'sambaSamAccount (v.3.0.7)';
36 $types['ad'] = 'MS ActiveDirectory';
37 $types['default'] = get_string('default');
42 * Initializes needed variables for ldap-module
44 * Uses names defined in ldap_supported_usertypes.
45 * $default is first defined as:
46 * $default['pseudoname'] = array(
47 * 'typename1' => 'value',
48 * 'typename2' => 'value'
52 * @return array of default values
54 function ldap_getdefaults() {
55 // All the values have to be written in lowercase, even if the
56 // standard LDAP attributes are mixed-case
57 $default['objectclass'] = array(
59 'rfc2307' => 'posixaccount',
60 'rfc2307bis' => 'posixaccount',
61 'samba' => 'sambasamaccount',
65 $default['user_attribute'] = array(
68 'rfc2307bis' => 'uid',
73 $default['memberattribute'] = array(
75 'rfc2307' => 'member',
76 'rfc2307bis' => 'member',
81 $default['memberattribute_isdn'] = array(
85 'samba' => '0', // is this right?
89 $default['expireattr'] = array (
90 'edir' => 'passwordexpirationtime',
91 'rfc2307' => 'shadowexpire',
92 'rfc2307bis' => 'shadowexpire',
93 'samba' => '', // No support yet
101 * Checks if user belongs to specific group(s) or is in a subtree.
103 * Returns true if user belongs to a group in grupdns string OR if the
104 * DN of the user is in a subtree of the DN provided as "group"
106 * @param mixed $ldapconnection A valid LDAP connection.
107 * @param string $userid LDAP user id (dn/cn/uid/...) to test membership for.
108 * @param array $group_dns arrary of group dn
109 * @param string $member_attrib the name of the membership attribute.
113 function ldap_isgroupmember($ldapconnection, $userid, $group_dns, $member_attrib) {
114 if (empty($ldapconnection) ||
empty($userid) ||
empty($group_dns) ||
empty($member_attrib)) {
119 foreach ($group_dns as $group) {
120 $group = trim($group);
125 // Check cheaply if the user's DN sits in a subtree of the
126 // "group" DN provided. Granted, this isn't a proper LDAP
127 // group, but it's a popular usage.
128 if (stripos(strrev(strtolower($userid)), strrev(strtolower($group))) === 0) {
133 $search = ldap_read($ldapconnection, $group,
134 '('.$member_attrib.'='.ldap_filter_addslashes($userid).')',
135 array($member_attrib));
137 if (!empty($search) && ldap_count_entries($ldapconnection, $search)) {
138 $info = ldap_get_entries_moodle($ldapconnection, $search);
139 if (count($info) > 0 ) {
140 // User is member of group
151 * Tries connect to specified ldap servers. Returns a valid LDAP
152 * connection or false.
154 * @param string $host_url
155 * @param integer $ldap_version either 2 (LDAPv2) or 3 (LDAPv3).
156 * @param string $user_type the configured user type for this connection.
157 * @param string $bind_dn the binding user dn. If an emtpy string, anonymous binding is used.
158 * @param string $bind_pw the password for the binding user. Ignored for anonymous bindings.
159 * @param boolean $opt_deref whether to set LDAP_OPT_DEREF on this connection or not.
160 * @param string &$debuginfo the debugging information in case the connection fails.
161 * @return mixed connection result or false.
163 function ldap_connect_moodle($host_url, $ldap_version, $user_type, $bind_dn, $bind_pw, $opt_deref, &$debuginfo) {
164 if (empty($host_url) ||
empty($ldap_version) ||
empty($user_type)) {
165 $debuginfo = 'No LDAP Host URL, Version or User Type specified in your LDAP settings';
170 $urls = explode(';', $host_url);
171 foreach ($urls as $server) {
172 $server = trim($server);
173 if (empty($server)) {
177 $connresult = ldap_connect($server); // ldap_connect returns ALWAYS true
179 if (!empty($ldap_version)) {
180 ldap_set_option($connresult, LDAP_OPT_PROTOCOL_VERSION
, $ldap_version);
184 if ($user_type === 'ad') {
185 ldap_set_option($connresult, LDAP_OPT_REFERRALS
, 0);
188 if (!empty($opt_deref)) {
189 ldap_set_option($connresult, LDAP_OPT_DEREF
, $opt_deref);
192 if (!empty($bind_dn)) {
193 $bindresult = @ldap_bind
($connresult, $bind_dn, $bind_pw);
196 $bindresult = @ldap_bind
($connresult);
203 $debuginfo .= "Server: '$server', Connection: '$connresult', Bind result: '$bindresult'\n";
206 // If any of servers were alive we have already returned connection.
211 * Search specified contexts for username and return the user dn like:
212 * cn=username,ou=suborg,o=org
214 * @param mixed $ldapconnection a valid LDAP connection.
215 * @param mixed $username username (external LDAP encoding, no db slashes).
216 * @param array $contexts contexts to look for the user.
217 * @param string $objectclass objectlass of the user (in LDAP filter syntax).
218 * @param string $search_attrib the attribute use to look for the user.
219 * @param boolean $search_sub whether to search subcontexts or not.
220 * @return mixed the user dn (external LDAP encoding, no db slashes) or false
223 function ldap_find_userdn($ldapconnection, $username, $contexts, $objectclass, $search_attrib, $search_sub) {
224 if (empty($ldapconnection) ||
empty($username) ||
empty($contexts) ||
empty($objectclass) ||
empty($search_attrib)) {
228 // Default return value
229 $ldap_user_dn = false;
231 // Get all contexts and look for first matching user
232 foreach ($contexts as $context) {
233 $context = trim($context);
234 if (empty($context)) {
239 $ldap_result = ldap_search($ldapconnection, $context,
240 '(&'.$objectclass.'('.$search_attrib.'='.ldap_filter_addslashes($username).'))',
241 array($search_attrib));
243 $ldap_result = ldap_list($ldapconnection, $context,
244 '(&'.$objectclass.'('.$search_attrib.'='.ldap_filter_addslashes($username).'))',
245 array($search_attrib));
248 $entry = ldap_first_entry($ldapconnection, $ldap_result);
250 $ldap_user_dn = ldap_get_dn($ldapconnection, $entry);
255 return $ldap_user_dn;
259 * Returns values like ldap_get_entries but is binary compatible and
260 * returns all attributes as array.
262 * @param mixed $ldapconnection A valid LDAP connection
263 * @param mixed $searchresult A search result from ldap_search, ldap_list, etc.
264 * @return array ldap-entries with lower-cased attributes as indexes
266 function ldap_get_entries_moodle($ldapconnection, $searchresult) {
267 if (empty($ldapconnection) ||
empty($searchresult)) {
273 $entry = ldap_first_entry($ldapconnection, $searchresult);
278 $attributes = array_change_key_case(ldap_get_attributes($ldapconnection, $entry), CASE_LOWER
);
279 for ($j = 0; $j < $attributes['count']; $j++
) {
280 $values = ldap_get_values_len($ldapconnection, $entry, $attributes[$j]);
281 if (is_array($values)) {
282 $result[$i][$attributes[$j]] = $values;
284 $result[$i][$attributes[$j]] = array($values);
288 } while ($entry = ldap_next_entry($ldapconnection, $entry));
294 * Quote control characters in texts used in LDAP filters - see RFC 4515/2254
296 * @param string filter string to quote
297 * @return string the filter string quoted
299 function ldap_filter_addslashes($text) {
300 $text = str_replace('\\', '\\5c', $text);
301 $text = str_replace(array('*', '(', ')', "\0"),
302 array('\\2a', '\\28', '\\29', '\\00'), $text);
306 if(!defined('LDAP_DN_SPECIAL_CHARS')) {
307 define('LDAP_DN_SPECIAL_CHARS', 0);
309 if(!defined('LDAP_DN_SPECIAL_CHARS_QUOTED_NUM')) {
310 define('LDAP_DN_SPECIAL_CHARS_QUOTED_NUM', 1);
312 if(!defined('LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA')) {
313 define('LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA', 2);
317 * The order of the special characters in these arrays _IS IMPORTANT_.
318 * Make sure '\\5C' (and '\\') are the first elements of the arrays.
319 * Otherwise we'll double replace '\' with '\5C' which is Bad(tm)
321 function ldap_get_dn_special_chars() {
323 LDAP_DN_SPECIAL_CHARS
=> array('\\', ' ', '"', '#', '+', ',', ';', '<', '=', '>', "\0"),
324 LDAP_DN_SPECIAL_CHARS_QUOTED_NUM
=> array('\\5c','\\20','\\22','\\23','\\2b','\\2c','\\3b','\\3c','\\3d','\\3e','\\00'),
325 LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA
=> array('\\\\','\\ ', '\\"', '\\#', '\\+', '\\,', '\\;', '\\<', '\\>', '\\=', '\\00'),
330 * Quote control characters in distinguished names used in LDAP - See RFC 4514/2253
332 * @param string The text to quote
333 * @return string The text quoted
335 function ldap_addslashes($text) {
336 $special_dn_chars = ldap_get_dn_special_chars();
338 $text = str_replace ($special_dn_chars[LDAP_DN_SPECIAL_CHARS
],
339 $special_dn_chars[LDAP_DN_SPECIAL_CHARS_QUOTED_NUM
],
345 * Unquote control characters in distinguished names used in LDAP - See RFC 4514/2253
347 * @param string The text quoted
348 * @return string The text unquoted
350 function ldap_stripslashes($text) {
351 $special_dn_chars = ldap_get_dn_special_chars();
353 // First unquote the simply backslashed special characters. If we
354 // do it the other way, we remove too many slashes.
355 $text = str_replace($special_dn_chars[LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA
],
356 $special_dn_chars[LDAP_DN_SPECIAL_CHARS
],
359 // Next unquote the 'numerically' quoted characters. We don't use
360 // LDAP_DN_SPECIAL_CHARS_QUOTED_NUM because the standard allows us
361 // to quote any character with this encoding, not just the special
363 $text = preg_replace('/\\\([0-9A-Fa-f]{2})/e', "chr(hexdec('\\1'))", $text);