ILIAS  release_5-3 Revision v5.3.23-19-g915713cf615
class.ilLDAPQuery.php
Go to the documentation of this file.
1 <?php
2 /*
3  +-----------------------------------------------------------------------------+
4  | ILIAS open source |
5  +-----------------------------------------------------------------------------+
6  | Copyright (c) 1998-2006 ILIAS open source, University of Cologne |
7  | |
8  | This program is free software; you can redistribute it and/or |
9  | modify it under the terms of the GNU General Public License |
10  | as published by the Free Software Foundation; either version 2 |
11  | of the License, or (at your option) any later version. |
12  | |
13  | This program is distributed in the hope that it will be useful, |
14  | but WITHOUT ANY WARRANTY; without even the implied warranty of |
15  | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
16  | GNU General Public License for more details. |
17  | |
18  | You should have received a copy of the GNU General Public License |
19  | along with this program; if not, write to the Free Software |
20  | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
21  +-----------------------------------------------------------------------------+
22 */
23 
24 define('IL_LDAP_BIND_DEFAULT', 0);
25 define('IL_LDAP_BIND_ADMIN', 1);
26 define('IL_LDAP_BIND_TEST', 2);
27 define('IL_LDAP_BIND_AUTH', 10);
28 
29 include_once('Services/LDAP/classes/class.ilLDAPAttributeMapping.php');
30 include_once('Services/LDAP/classes/class.ilLDAPResult.php');
31 include_once('Services/LDAP/classes/class.ilLDAPQueryException.php');
32 
43 {
44  private $ldap_server_url = null;
45  private $settings = null;
46 
50  private $log = null;
51 
52  private $user_fields = array();
53 
62  public function __construct(ilLDAPServer $a_server, $a_url = '')
63  {
64  $this->settings = $a_server;
65 
66  if (strlen($a_url)) {
67  $this->ldap_server_url = $a_url;
68  } else {
69  $this->ldap_server_url = $this->settings->getUrl();
70  }
71 
72  $this->mapping = ilLDAPAttributeMapping::_getInstanceByServerId($this->settings->getServerId());
73  $this->log = $GLOBALS['DIC']->logger()->auth();
74 
75  $this->fetchUserProfileFields();
76  $this->connect();
77  }
78 
79  // begin-patch ldap_multiple
84  public function getServer()
85  {
86  return $this->settings;
87  }
88 
93  public function getLogger()
94  {
95  return $this->log;
96  }
97 
105  public function fetchUser($a_name)
106  {
107  if (!$this->readUserData($a_name)) {
108  return array();
109  } else {
110  return $this->users;
111  }
112  }
113 
114 
121  public function fetchUsers()
122  {
123  // First of all check if a group restriction is enabled
124  // YES: => fetch all group members
125  // No: => fetch all users
126  if (strlen($this->settings->getGroupName())) {
127  $this->log->debug('Searching for group members.');
128 
129  $groups = $this->settings->getGroupNames();
130  if (count($groups) <= 1) {
131  $this->fetchGroupMembers();
132  } else {
133  foreach ($groups as $group) {
134  $this->fetchGroupMembers($group);
135  }
136  }
137  }
138  if (!strlen($this->settings->getGroupName()) or $this->settings->isMembershipOptional()) {
139  $this->log->info('Start reading all users...');
140  $this->readAllUsers();
141  #throw new ilLDAPQueryException('LDAP: Called import of users without specifying group restrictions. NOT IMPLEMENTED YET!');
142  }
143  return $this->users ? $this->users : array();
144  }
145 
157  public function query($a_search_base, $a_filter, $a_scope, $a_attributes)
158  {
159  $res = $this->queryByScope($a_scope, $a_search_base, $a_filter, $a_attributes);
160  if ($res === false) {
161  throw new ilLDAPQueryException(__METHOD__ . ' ' . ldap_error($this->lh) . ' ' .
162  sprintf(
163  'DN: %s, Filter: %s, Scope: %s',
164  $a_search_base,
165  $a_filter,
166  $a_scope
167  ));
168  }
169  return new ilLDAPResult($this->lh, $res);
170  }
171 
178  public function modAdd($a_dn, $a_attribute)
179  {
180  if (@ldap_mod_add($this->lh, $a_dn, $a_attribute)) {
181  return true;
182  }
183  throw new ilLDAPQueryException(__METHOD__ . ' ' . ldap_error($this->lh));
184  }
185 
192  public function modDelete($a_dn, $a_attribute)
193  {
194  if (@ldap_mod_del($this->lh, $a_dn, $a_attribute)) {
195  return true;
196  }
197  throw new ilLDAPQueryException(__METHOD__ . ' ' . ldap_error($this->lh));
198  }
199 
208  private function readAllUsers()
209  {
210  // Build search base
211  if (($dn = $this->settings->getSearchBase()) && substr($dn, -1) != ',') {
212  $dn .= ',';
213  }
214  $dn .= $this->settings->getBaseDN();
215 
216  // page results
217  $filter = $this->settings->getFilter();
218  $page_filter = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','-');
219  $chars = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
220 
221  foreach ($page_filter as $letter) {
222  $new_filter = '(&';
223  $new_filter .= $filter;
224 
225  switch ($letter) {
226  case '-':
227  $new_filter .= ('(!(|');
228  foreach ($chars as $char) {
229  $new_filter .= ('(' . $this->settings->getUserAttribute() . '=' . $char . '*)');
230  }
231  $new_filter .= ')))';
232  break;
233 
234  default:
235  $new_filter .= ('(' . $this->settings->getUserAttribute() . '=' . $letter . '*))');
236  break;
237  }
238 
239  $this->log->info('Searching with ldap search and filter ' . $new_filter . ' in ' . $dn);
240  $res = $this->queryByScope(
241  $this->settings->getUserScope(),
242  $dn,
243  $new_filter,
244  array($this->settings->getUserAttribute())
245  );
246 
247  $tmp_result = new ilLDAPResult($this->lh, $res);
248  if (!$tmp_result->numRows()) {
249  $this->log->notice('No users found. Aborting.');
250  continue;
251  }
252  $this->log->info('Found ' . $tmp_result->numRows() . ' users.');
253  $attribute = strtolower($this->settings->getUserAttribute());
254  foreach ($tmp_result->getRows() as $data) {
255  if (isset($data[$attribute])) {
256  $this->readUserData($data[$attribute], false, false);
257  } else {
258  $this->log->warning('Unknown error. No user attribute found.');
259  }
260  }
261  unset($tmp_result);
262  }
263  return true;
264  }
265 
272  public function checkGroupMembership($a_ldap_user_name, $ldap_user_data)
273  {
274  $group_names = $this->getServer()->getGroupNames();
275 
276  if (!count($group_names)) {
277  $this->getLogger()->debug('No LDAP group restrictions found');
278  return true;
279  }
280 
281  $group_dn = $this->getServer()->getGroupDN();
282  if (
283  $group_dn &&
284  (substr($group_dn, -1) != ',')
285  ) {
286  $group_dn .= ',';
287  }
288  $group_dn .= $this->getServer()->getBaseDN();
289 
290  foreach ($group_names as $group) {
291  $user = $a_ldap_user_name;
292  if ($this->getServer()->enabledGroupMemberIsDN()) {
293  $user = $ldap_user_data['dn'];
294  }
295 
296  $filter = sprintf(
297  '(&(%s=%s)(%s=%s)%s)',
298  $this->getServer()->getGroupAttribute(),
299  $group,
300  $this->getServer()->getGroupMember(),
301  $user,
302  $this->getServer()->getGroupFilter()
303  );
304  $this->getLogger()->debug('Current group search base: ' . $group_dn);
305  $this->getLogger()->debug('Current group filter: ' . $filter);
306 
307  $res = $this->queryByScope(
308  $this->getServer()->getGroupScope(),
309  $group_dn,
310  $filter,
311  [$this->getServer()->getGroupMember()]
312  );
313 
314  $this->getLogger()->dump($res);
315 
316  $tmp_result = new ilLDAPResult($this->lh, $res);
317  $group_result = $tmp_result->getRows();
318 
319  $this->getLogger()->debug('Group query returned: ');
320  $this->getLogger()->dump($group_result, ilLogLevel::DEBUG);
321 
322  if (count($group_result)) {
323  return true;
324  }
325  }
326 
327  // group restrictions failed check optional membership
328  if ($this->getServer()->isMembershipOptional()) {
329  $this->getLogger()->debug('Group restrictions failed, checking user filter.');
330  if ($this->readUserData($a_ldap_user_name, true, true)) {
331  $this->getLogger()->debug('User filter matches.');
332  return true;
333  }
334  }
335  $this->getLogger()->debug('Group restrictions failed.');
336  return false;
337  }
338 
339 
346  private function fetchGroupMembers($a_name = '')
347  {
348  $group_name = strlen($a_name) ? $a_name : $this->settings->getGroupName();
349 
350  // Build filter
351  $filter = sprintf(
352  '(&(%s=%s)%s)',
353  $this->settings->getGroupAttribute(),
354  $group_name,
355  $this->settings->getGroupFilter()
356  );
357 
358 
359  // Build search base
360  if (($gdn = $this->settings->getGroupDN()) && substr($gdn, -1) != ',') {
361  $gdn .= ',';
362  }
363  $gdn .= $this->settings->getBaseDN();
364 
365  $this->log->debug('Using filter ' . $filter);
366  $this->log->debug('Using DN ' . $gdn);
367  $res = $this->queryByScope(
368  $this->settings->getGroupScope(),
369  $gdn,
370  $filter,
371  array($this->settings->getGroupMember())
372  );
373 
374  $tmp_result = new ilLDAPResult($this->lh, $res);
375  $group_data = $tmp_result->getRows();
376 
377 
378  if (!$tmp_result->numRows()) {
379  $this->log->info('No group found.');
380  return false;
381  }
382 
383  $attribute_name = strtolower($this->settings->getGroupMember());
384 
385  // All groups
386  foreach ($group_data as $data) {
387  if (is_array($data[$attribute_name])) {
388  $this->log->debug('Found ' . count($data[$attribute_name]) . ' group members for group ' . $data['dn']);
389  foreach ($data[$attribute_name] as $name) {
390  $this->readUserData($name, true, true);
391  }
392  } else {
393  $this->readUserData($data[$attribute_name], true, true);
394  }
395  }
396  unset($tmp_result);
397  return;
398  }
399 
406  private function readUserData($a_name, $a_check_dn = false, $a_try_group_user_filter = false)
407  {
408  $filter = $this->settings->getFilter();
409  if ($a_try_group_user_filter) {
410  if ($this->settings->isMembershipOptional()) {
411  $filter = $this->settings->getGroupUserFilter();
412  }
413  }
414 
415  // Build filter
416  if ($this->settings->enabledGroupMemberIsDN() and $a_check_dn) {
417  $dn = $a_name;
418  #$res = $this->queryByScope(IL_LDAP_SCOPE_BASE,$dn,$filter,$this->user_fields);
419 
420  $fields = array_merge($this->user_fields, array('useraccountcontrol'));
421  $res = $this->queryByScope(IL_LDAP_SCOPE_BASE, strtolower($dn), $filter, $fields);
422  } else {
423  $filter = sprintf(
424  '(&(%s=%s)%s)',
425  $this->settings->getUserAttribute(),
426  $a_name,
427  $filter
428  );
429 
430  // Build search base
431  if (($dn = $this->settings->getSearchBase()) && substr($dn, -1) != ',') {
432  $dn .= ',';
433  }
434  $dn .= $this->settings->getBaseDN();
435  $fields = array_merge($this->user_fields, array('useraccountcontrol'));
436  $res = $this->queryByScope($this->settings->getUserScope(), strtolower($dn), $filter, $fields);
437  }
438 
439 
440  $tmp_result = new ilLDAPResult($this->lh, $res);
441  if (!$tmp_result->numRows()) {
442  $this->log->info('LDAP: No user data found for: ' . $a_name);
443  unset($tmp_result);
444  return false;
445  }
446 
447  if ($user_data = $tmp_result->get()) {
448  if (isset($user_data['useraccountcontrol'])) {
449  if (($user_data['useraccountcontrol'] & 0x02)) {
450  $this->log->notice('LDAP: ' . $a_name . ' account disabled.');
451  return;
452  }
453  }
454 
455  $account = $user_data[strtolower($this->settings->getUserAttribute())];
456  if (is_array($account)) {
457  $user_ext = strtolower(array_shift($account));
458  } else {
459  $user_ext = strtolower($account);
460  }
461 
462  // auth mode depends on ldap server settings
463  $auth_mode = $this->settings->getAuthenticationMappingKey();
464  $user_data['ilInternalAccount'] = ilObjUser::_checkExternalAuthAccount($auth_mode, $user_ext);
465  $this->users[$user_ext] = $user_data;
466  }
467  return true;
468  }
469 
474  private function parseAuthMode()
475  {
476  return $this->settings->getAuthenticationMappingKey();
477  }
478 
488  private function queryByScope($a_scope, $a_base_dn, $a_filter, $a_attributes)
489  {
490  $a_filter = $a_filter ? $a_filter : "(objectclass=*)";
491 
492  switch ($a_scope) {
493  case IL_LDAP_SCOPE_SUB:
494  $res = @ldap_search($this->lh, $a_base_dn, $a_filter, $a_attributes);
495  break;
496 
497  case IL_LDAP_SCOPE_ONE:
498  $res = @ldap_list($this->lh, $a_base_dn, $a_filter, $a_attributes);
499  break;
500 
501  case IL_LDAP_SCOPE_BASE:
502 
503  $res = @ldap_read($this->lh, $a_base_dn, $a_filter, $a_attributes);
504  break;
505 
506  default:
507  $this->log->warning("LDAP: LDAPQuery: Unknown search scope");
508  }
509 
510  $error = ldap_error($this->lh);
511  if (strcmp('Success', $error) !== 0) {
512  $this->getLogger()->warning($error);
513  $this->getLogger()->warning('Base DN:' . $a_base_dn);
514  $this->getLogger()->warning('Filter: ' . $a_filter);
515  }
516 
517  return $res;
518  }
519 
527  private function connect()
528  {
529  $this->lh = @ldap_connect($this->ldap_server_url);
530 
531  // LDAP Connect
532  if (!$this->lh) {
533  throw new ilLDAPQueryException("LDAP: Cannot connect to LDAP Server: " . $this->settings->getUrl());
534  }
535  // LDAP Version
536  if (!ldap_set_option($this->lh, LDAP_OPT_PROTOCOL_VERSION, $this->settings->getVersion())) {
537  throw new ilLDAPQueryException("LDAP: Cannot set version to: " . $this->settings->getVersion());
538  }
539  // Switch on referrals
540  if ($this->settings->isActiveReferrer()) {
541  if (!ldap_set_option($this->lh, LDAP_OPT_REFERRALS, true)) {
542  throw new ilLDAPQueryException("LDAP: Cannot switch on LDAP referrals");
543  }
544  #@ldap_set_rebind_proc($this->lh,'referralRebind');
545  } else {
546  ldap_set_option($this->lh, LDAP_OPT_REFERRALS, false);
547  $this->log->debug('Switching referrals to false.');
548  }
549  // Start TLS
550  if ($this->settings->isActiveTLS()) {
551  if (!ldap_start_tls($this->lh)) {
552  throw new ilLDAPQueryException("LDAP: Cannot start LDAP TLS");
553  }
554  }
555  }
556 
565  public function bind($a_binding_type = IL_LDAP_BIND_DEFAULT, $a_user_dn = '', $a_password = '')
566  {
567  switch ($a_binding_type) {
568  case IL_LDAP_BIND_TEST:
569  ldap_set_option($this->lh, LDAP_OPT_NETWORK_TIMEOUT, ilLDAPServer::DEFAULT_NETWORK_TIMEOUT);
570  // fall through
571  // no break
573  // Now bind anonymously or as user
574  if (
575  IL_LDAP_BIND_USER == $this->settings->getBindingType() &&
576  strlen($this->settings->getBindUser())
577  ) {
578  $user = $this->settings->getBindUser();
579  $pass = $this->settings->getBindPassword();
580 
581  define('IL_LDAP_REBIND_USER', $user);
582  define('IL_LDAP_REBIND_PASS', $pass);
583  $this->log->debug('Bind as ' . $user);
584  } else {
585  $user = $pass = '';
586  $this->log->debug('Bind anonymous');
587  }
588  break;
589 
590  case IL_LDAP_BIND_ADMIN:
591  $user = $this->settings->getRoleBindDN();
592  $pass = $this->settings->getRoleBindPassword();
593 
594  if (!strlen($user) or !strlen($pass)) {
595  $user = $this->settings->getBindUser();
596  $pass = $this->settings->getBindPassword();
597  }
598 
599  define('IL_LDAP_REBIND_USER', $user);
600  define('IL_LDAP_REBIND_PASS', $pass);
601  break;
602 
603  case IL_LDAP_BIND_AUTH:
604  $this->log->debug('Trying to bind as: ' . $a_user_dn);
605  $user = $a_user_dn;
606  $pass = $a_password;
607  break;
608 
609 
610  default:
611  throw new ilLDAPQueryException('LDAP: unknown binding type in: ' . __METHOD__);
612  }
613 
614  if (!@ldap_bind($this->lh, $user, $pass)) {
615  throw new ilLDAPQueryException('LDAP: Cannot bind as ' . $user . ' with message: ' . ldap_err2str(ldap_errno($this->lh)) . ' Trying fallback...', ldap_errno($this->lh));
616  } else {
617  $this->log->debug('Bind successful.');
618  }
619  }
620 
628  private function fetchUserProfileFields()
629  {
630  include_once('Services/LDAP/classes/class.ilLDAPRoleAssignmentRules.php');
631 
632  $this->user_fields = array_merge(
633  array($this->settings->getUserAttribute()),
634  array('dn'),
635  $this->mapping->getFields(),
637  );
638  }
639 
640 
648  private function unbind()
649  {
650  if ($this->lh) {
651  @ldap_unbind($this->lh);
652  }
653  }
654 
655 
663  public function __destruct()
664  {
665  if ($this->lh) {
666  @ldap_unbind($this->lh);
667  }
668  }
669 }
670 
671 function referralRebind($a_ds, $a_url)
672 {
673  global $ilLog;
674 
675  $ilLog->write('LDAP: Called referralRebind.');
676 
677  ldap_set_option($a_ds, LDAP_OPT_PROTOCOL_VERSION, 3);
678 
679  if (!ldap_bind($a_ds, IL_LDAP_REBIND_USER, IL_LDAP_REBIND_PASS)) {
680  $ilLog->write('LDAP: Rebind failed');
681  }
682 }
const IL_LDAP_BIND_USER
getLogger()
Get logger.
fetchUsers()
Fetch all users.
modAdd($a_dn, $a_attribute)
Add value to an existing attribute.
static _getInstanceByServerId($a_server_id)
Get instance of class.
const IL_LDAP_BIND_AUTH
const IL_LDAP_BIND_DEFAULT
const IL_LDAP_SCOPE_SUB
$GLOBALS['loaded']
Global hash that tracks already loaded includes.
__construct(ilLDAPServer $a_server, $a_url='')
Constructur.
checkGroupMembership($a_ldap_user_name, $ldap_user_data)
check group membership
connect()
Connect to LDAP server.
static getAttributeNames($a_server_id)
get all possible attribute names
const IL_LDAP_BIND_TEST
readAllUsers()
Fetch all users This function splits the query to filters like e.g (uid=a*) (uid=b*)...
fetchGroupMembers($a_name='')
Fetch group member ids.
$error
Definition: Error.php:17
if($format !==null) $name
Definition: metadata.php:146
const DEFAULT_NETWORK_TIMEOUT
parseAuthMode()
Parse authentication mode.
foreach($_POST as $key=> $value) $res
query($a_search_base, $a_filter, $a_scope, $a_attributes)
Perform a query.
fetchUserProfileFields()
fetch required fields of user profile data
referralRebind($a_ds, $a_url)
getServer()
Get server.
fetchUser($a_name)
Get one user by login name.
const IL_LDAP_SCOPE_ONE
readUserData($a_name, $a_check_dn=false, $a_try_group_user_filter=false)
Read user data.
modDelete($a_dn, $a_attribute)
Delete value from an existing attribute.
const IL_LDAP_BIND_ADMIN
Create styles array
The data for the language used.
$users
Definition: authpage.php:44
static _checkExternalAuthAccount($a_auth, $a_account, $tryFallback=true)
check whether external account and authentication method matches with a user
settings()
Definition: settings.php:2
__destruct()
Destructor unbind from ldap server.
bind($a_binding_type=IL_LDAP_BIND_DEFAULT, $a_user_dn='', $a_password='')
Bind to LDAP server.
const IL_LDAP_SCOPE_BASE
queryByScope($a_scope, $a_base_dn, $a_filter, $a_attributes)
Query by scope IL_SCOPE_SUB => ldap_search IL_SCOPE_ONE => ldap_list.