MDL-13572 message: added validation of the email address in the messaging preferences
[moodle.git] / lib / ldaplib.php
blobf1d048ec04158ea88d9a95004327e8ae6363ae21
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 /**
26 * Returns predefined user types
28 * @return array of predefined user types
30 function ldap_supported_usertypes() {
31 $types = array();
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');
38 return $types;
41 /**
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'
49 * ....
50 * );
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(
58 'edir' => 'user',
59 'rfc2307' => 'posixaccount',
60 'rfc2307bis' => 'posixaccount',
61 'samba' => 'sambasamaccount',
62 'ad' => 'user',
63 'default' => '*'
65 $default['user_attribute'] = array(
66 'edir' => 'cn',
67 'rfc2307' => 'uid',
68 'rfc2307bis' => 'uid',
69 'samba' => 'uid',
70 'ad' => 'cn',
71 'default' => 'cn'
73 $default['memberattribute'] = array(
74 'edir' => 'member',
75 'rfc2307' => 'member',
76 'rfc2307bis' => 'member',
77 'samba' => 'member',
78 'ad' => 'member',
79 'default' => 'member'
81 $default['memberattribute_isdn'] = array(
82 'edir' => '1',
83 'rfc2307' => '0',
84 'rfc2307bis' => '1',
85 'samba' => '0', // is this right?
86 'ad' => '1',
87 'default' => '0'
89 $default['expireattr'] = array (
90 'edir' => 'passwordexpirationtime',
91 'rfc2307' => 'shadowexpire',
92 'rfc2307bis' => 'shadowexpire',
93 'samba' => '', // No support yet
94 'ad' => 'pwdlastset',
95 'default' => ''
97 return $default;
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.
110 * @return boolean
113 function ldap_isgroupmember($ldapconnection, $userid, $group_dns, $member_attrib) {
114 if (empty($ldapconnection) || empty($userid) || empty($group_dns) || empty($member_attrib)) {
115 return false;
118 $result = false;
119 foreach ($group_dns as $group) {
120 $group = trim($group);
121 if (empty($group)) {
122 continue;
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) {
129 $result = true;
130 break;
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
141 $result = true;
142 break;
147 return $result;
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';
166 return false;
169 $debuginfo = '';
170 $urls = explode(';', $host_url);
171 foreach ($urls as $server) {
172 $server = trim($server);
173 if (empty($server)) {
174 continue;
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);
183 // Fix MDL-10921
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);
194 } else {
195 // Bind anonymously
196 $bindresult = @ldap_bind($connresult);
199 if ($bindresult) {
200 return $connresult;
203 $debuginfo .= "Server: '$server', Connection: '$connresult', Bind result: '$bindresult'\n";
206 // If any of servers were alive we have already returned connection.
207 return false;
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)) {
225 return false;
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)) {
235 continue;
238 if ($search_sub) {
239 $ldap_result = ldap_search($ldapconnection, $context,
240 '(&'.$objectclass.'('.$search_attrib.'='.ldap_filter_addslashes($username).'))',
241 array($search_attrib));
242 } else {
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);
249 if ($entry) {
250 $ldap_user_dn = ldap_get_dn($ldapconnection, $entry);
251 break;
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)) {
268 return array();
271 $i = 0;
272 $result = array();
273 $entry = ldap_first_entry($ldapconnection, $searchresult);
274 if (!$entry) {
275 return array();
277 do {
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;
283 } else {
284 $result[$i][$attributes[$j]] = array($values);
287 $i++;
288 } while ($entry = ldap_next_entry($ldapconnection, $entry));
290 return ($result);
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);
303 return $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() {
322 return array (
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],
340 $text);
341 return $text;
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],
357 $text);
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
362 // ones.
363 $text = preg_replace('/\\\([0-9A-Fa-f]{2})/e', "chr(hexdec('\\1'))", $text);
365 return $text;