MDL-36204 Improve moodle1 conversion of embedded files
[moodle.git] / lib / ldaplib.php
blobf33306888c9091532e070802967d4dc0611df1e0
1 <?php
3 /**
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
11 * @package core
12 * @subpackage lib
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);
30 /**
31 * Returns predefined user types
33 * @return array of predefined user types
35 function ldap_supported_usertypes() {
36 $types = array();
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');
43 return $types;
46 /**
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'
54 * ....
55 * );
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(
63 'edir' => 'user',
64 'rfc2307' => 'posixaccount',
65 'rfc2307bis' => 'posixaccount',
66 'samba' => 'sambasamaccount',
67 'ad' => 'user',
68 'default' => '*'
70 $default['user_attribute'] = array(
71 'edir' => 'cn',
72 'rfc2307' => 'uid',
73 'rfc2307bis' => 'uid',
74 'samba' => 'uid',
75 'ad' => 'cn',
76 'default' => 'cn'
78 $default['memberattribute'] = array(
79 'edir' => 'member',
80 'rfc2307' => 'member',
81 'rfc2307bis' => 'member',
82 'samba' => 'member',
83 'ad' => 'member',
84 'default' => 'member'
86 $default['memberattribute_isdn'] = array(
87 'edir' => '1',
88 'rfc2307' => '0',
89 'rfc2307bis' => '1',
90 'samba' => '0', // is this right?
91 'ad' => '1',
92 'default' => '0'
94 $default['expireattr'] = array (
95 'edir' => 'passwordexpirationtime',
96 'rfc2307' => 'shadowexpire',
97 'rfc2307bis' => 'shadowexpire',
98 'samba' => '', // No support yet
99 'ad' => 'pwdlastset',
100 'default' => ''
102 return $default;
106 * Checks if user belongs to specific group(s) or is in a subtree.
108 * Returns true if user belongs to a group in grupdns string OR if the
109 * DN of the user is in a subtree of the DN provided as "group"
111 * @param mixed $ldapconnection A valid LDAP connection.
112 * @param string $userid LDAP user id (dn/cn/uid/...) to test membership for.
113 * @param array $group_dns arrary of group dn
114 * @param string $member_attrib the name of the membership attribute.
115 * @return boolean
118 function ldap_isgroupmember($ldapconnection, $userid, $group_dns, $member_attrib) {
119 if (empty($ldapconnection) || empty($userid) || empty($group_dns) || empty($member_attrib)) {
120 return false;
123 $result = false;
124 foreach ($group_dns as $group) {
125 $group = trim($group);
126 if (empty($group)) {
127 continue;
130 // Check cheaply if the user's DN sits in a subtree of the
131 // "group" DN provided. Granted, this isn't a proper LDAP
132 // group, but it's a popular usage.
133 if (stripos(strrev(strtolower($userid)), strrev(strtolower($group))) === 0) {
134 $result = true;
135 break;
138 $search = ldap_read($ldapconnection, $group,
139 '('.$member_attrib.'='.ldap_filter_addslashes($userid).')',
140 array($member_attrib));
142 if (!empty($search) && ldap_count_entries($ldapconnection, $search)) {
143 $info = ldap_get_entries_moodle($ldapconnection, $search);
144 if (count($info) > 0 ) {
145 // User is member of group
146 $result = true;
147 break;
152 return $result;
156 * Tries connect to specified ldap servers. Returns a valid LDAP
157 * connection or false.
159 * @param string $host_url
160 * @param integer $ldap_version either 2 (LDAPv2) or 3 (LDAPv3).
161 * @param string $user_type the configured user type for this connection.
162 * @param string $bind_dn the binding user dn. If an emtpy string, anonymous binding is used.
163 * @param string $bind_pw the password for the binding user. Ignored for anonymous bindings.
164 * @param boolean $opt_deref whether to set LDAP_OPT_DEREF on this connection or not.
165 * @param string &$debuginfo the debugging information in case the connection fails.
166 * @return mixed connection result or false.
168 function ldap_connect_moodle($host_url, $ldap_version, $user_type, $bind_dn, $bind_pw, $opt_deref, &$debuginfo) {
169 if (empty($host_url) || empty($ldap_version) || empty($user_type)) {
170 $debuginfo = 'No LDAP Host URL, Version or User Type specified in your LDAP settings';
171 return false;
174 $debuginfo = '';
175 $urls = explode(';', $host_url);
176 foreach ($urls as $server) {
177 $server = trim($server);
178 if (empty($server)) {
179 continue;
182 $connresult = ldap_connect($server); // ldap_connect returns ALWAYS true
184 if (!empty($ldap_version)) {
185 ldap_set_option($connresult, LDAP_OPT_PROTOCOL_VERSION, $ldap_version);
188 // Fix MDL-10921
189 if ($user_type === 'ad') {
190 ldap_set_option($connresult, LDAP_OPT_REFERRALS, 0);
193 if (!empty($opt_deref)) {
194 ldap_set_option($connresult, LDAP_OPT_DEREF, $opt_deref);
197 if (!empty($bind_dn)) {
198 $bindresult = @ldap_bind($connresult, $bind_dn, $bind_pw);
199 } else {
200 // Bind anonymously
201 $bindresult = @ldap_bind($connresult);
204 if ($bindresult) {
205 return $connresult;
208 $debuginfo .= "Server: '$server', Connection: '$connresult', Bind result: '$bindresult'\n";
211 // If any of servers were alive we have already returned connection.
212 return false;
216 * Search specified contexts for username and return the user dn like:
217 * cn=username,ou=suborg,o=org
219 * @param mixed $ldapconnection a valid LDAP connection.
220 * @param mixed $username username (external LDAP encoding, no db slashes).
221 * @param array $contexts contexts to look for the user.
222 * @param string $objectclass objectlass of the user (in LDAP filter syntax).
223 * @param string $search_attrib the attribute use to look for the user.
224 * @param boolean $search_sub whether to search subcontexts or not.
225 * @return mixed the user dn (external LDAP encoding, no db slashes) or false
228 function ldap_find_userdn($ldapconnection, $username, $contexts, $objectclass, $search_attrib, $search_sub) {
229 if (empty($ldapconnection) || empty($username) || empty($contexts) || empty($objectclass) || empty($search_attrib)) {
230 return false;
233 // Default return value
234 $ldap_user_dn = false;
236 // Get all contexts and look for first matching user
237 foreach ($contexts as $context) {
238 $context = trim($context);
239 if (empty($context)) {
240 continue;
243 if ($search_sub) {
244 $ldap_result = ldap_search($ldapconnection, $context,
245 '(&'.$objectclass.'('.$search_attrib.'='.ldap_filter_addslashes($username).'))',
246 array($search_attrib));
247 } else {
248 $ldap_result = ldap_list($ldapconnection, $context,
249 '(&'.$objectclass.'('.$search_attrib.'='.ldap_filter_addslashes($username).'))',
250 array($search_attrib));
253 $entry = ldap_first_entry($ldapconnection, $ldap_result);
254 if ($entry) {
255 $ldap_user_dn = ldap_get_dn($ldapconnection, $entry);
256 break;
260 return $ldap_user_dn;
264 * Returns values like ldap_get_entries but is binary compatible and
265 * returns all attributes as array.
267 * @param mixed $ldapconnection A valid LDAP connection
268 * @param mixed $searchresult A search result from ldap_search, ldap_list, etc.
269 * @return array ldap-entries with lower-cased attributes as indexes
271 function ldap_get_entries_moodle($ldapconnection, $searchresult) {
272 if (empty($ldapconnection) || empty($searchresult)) {
273 return array();
276 $i = 0;
277 $result = array();
278 $entry = ldap_first_entry($ldapconnection, $searchresult);
279 if (!$entry) {
280 return array();
282 do {
283 $attributes = array_change_key_case(ldap_get_attributes($ldapconnection, $entry), CASE_LOWER);
284 for ($j = 0; $j < $attributes['count']; $j++) {
285 $values = ldap_get_values_len($ldapconnection, $entry, $attributes[$j]);
286 if (is_array($values)) {
287 $result[$i][$attributes[$j]] = $values;
288 } else {
289 $result[$i][$attributes[$j]] = array($values);
292 $i++;
293 } while ($entry = ldap_next_entry($ldapconnection, $entry));
295 return ($result);
299 * Quote control characters in texts used in LDAP filters - see RFC 4515/2254
301 * @param string filter string to quote
302 * @return string the filter string quoted
304 function ldap_filter_addslashes($text) {
305 $text = str_replace('\\', '\\5c', $text);
306 $text = str_replace(array('*', '(', ')', "\0"),
307 array('\\2a', '\\28', '\\29', '\\00'), $text);
308 return $text;
311 if(!defined('LDAP_DN_SPECIAL_CHARS')) {
312 define('LDAP_DN_SPECIAL_CHARS', 0);
314 if(!defined('LDAP_DN_SPECIAL_CHARS_QUOTED_NUM')) {
315 define('LDAP_DN_SPECIAL_CHARS_QUOTED_NUM', 1);
317 if(!defined('LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA')) {
318 define('LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA', 2);
322 * The order of the special characters in these arrays _IS IMPORTANT_.
323 * Make sure '\\5C' (and '\\') are the first elements of the arrays.
324 * Otherwise we'll double replace '\' with '\5C' which is Bad(tm)
326 function ldap_get_dn_special_chars() {
327 return array (
328 LDAP_DN_SPECIAL_CHARS => array('\\', ' ', '"', '#', '+', ',', ';', '<', '=', '>', "\0"),
329 LDAP_DN_SPECIAL_CHARS_QUOTED_NUM => array('\\5c','\\20','\\22','\\23','\\2b','\\2c','\\3b','\\3c','\\3d','\\3e','\\00'),
330 LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA => array('\\\\','\\ ', '\\"', '\\#', '\\+', '\\,', '\\;', '\\<', '\\>', '\\=', '\\00'),
335 * Quote control characters in distinguished names used in LDAP - See RFC 4514/2253
337 * @param string The text to quote
338 * @return string The text quoted
340 function ldap_addslashes($text) {
341 $special_dn_chars = ldap_get_dn_special_chars();
343 $text = str_replace ($special_dn_chars[LDAP_DN_SPECIAL_CHARS],
344 $special_dn_chars[LDAP_DN_SPECIAL_CHARS_QUOTED_NUM],
345 $text);
346 return $text;
350 * Unquote control characters in distinguished names used in LDAP - See RFC 4514/2253
352 * @param string The text quoted
353 * @return string The text unquoted
355 function ldap_stripslashes($text) {
356 $special_dn_chars = ldap_get_dn_special_chars();
358 // First unquote the simply backslashed special characters. If we
359 // do it the other way, we remove too many slashes.
360 $text = str_replace($special_dn_chars[LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA],
361 $special_dn_chars[LDAP_DN_SPECIAL_CHARS],
362 $text);
364 // Next unquote the 'numerically' quoted characters. We don't use
365 // LDAP_DN_SPECIAL_CHARS_QUOTED_NUM because the standard allows us
366 // to quote any character with this encoding, not just the special
367 // ones.
368 $text = preg_replace('/\\\([0-9A-Fa-f]{2})/e', "chr(hexdec('\\1'))", $text);
370 return $text;
375 * Check if PHP supports LDAP paged results and we can use them (we have to use LDAP
376 * version 3, otherwise the server doesn't use them).
378 * @param ldapversion integer The LDAP protocol version we use.
380 * @return boolean true is paged results can be used, false otherwise.
382 function ldap_paged_results_supported($ldapversion) {
384 if (((int)$ldapversion === 3) &&
385 function_exists('ldap_control_paged_result') &&
386 function_exists('ldap_control_paged_result_response')) {
388 return true;
391 return false;