Projet

Général

Profil

Révision bc175c27

Ajouté par Assos Assos il y a plus de 5 ans

Weekly update of contrib modules

Voir les différences:

drupal7/sites/all/modules/ldap/ldap_servers/LdapServer.class.php
13 13
 * TODO describe preconditions for ldap_entry
14 14
 */
15 15
function pretty_print_ldap_entry($ldap_entry) {
16
  $m=array();
17
  for ($i=0; $i < $ldap_entry['count']; $i++) {
18
    $k=$ldap_entry[$i];
19
    $v=$ldap_entry[$k];
16
  $m = array();
17
  for ($i = 0; $i < $ldap_entry['count']; $i++) {
18
    $k = $ldap_entry[$i];
19
    $v = $ldap_entry[$k];
20 20
    if(is_array($v)) {
21
      $m2=array();
22
      $max=$v['count']>3 ? 3 : $v['count'];
23
      for ($j=0; $j < $max; $j++) {
21
      $m2 = array();
22
      $max = $v['count'] > 3 ? 3 : $v['count'];
23
      for ($j = 0; $j < $max; $j++) {
24 24
	$m2[] = $v[$j];
25 25
      }
26
      $v="(".join(", ", $m2).")";
26
      $v = "(".join(", ", $m2).")";
27 27
    }
28 28
    $m[] = $k . ": " . $v;
29 29
  }
......
106 106
  public $connection;
107 107

  
108 108

  
109

  
110

  
111
  // direct mapping of db to object properties
109
  /**
110
   * Direct mapping of db to object properties
111
   *
112
   * @return array
113
   */
112 114
  public static function field_to_properties_map() {
113 115
    return array(
114 116
    'sid' => 'sid',
......
144 146
    'grp_memb_attr_match_user_attr' => 'groupMembershipsAttrMatchingUserAttr',
145 147
    'grp_derive_from_dn' => 'groupDeriveFromDn',
146 148
    'grp_derive_from_dn_attr' => 'groupDeriveFromDnAttr',
147
    'grp_test_grp_dn' =>  'groupTestGroupDn',
149
    'grp_test_grp_dn' => 'groupTestGroupDn',
148 150
    'grp_test_grp_dn_writeable' => 'groupTestGroupDnWriteable',
149 151

  
150 152
    'search_pagination' => 'searchPagination',
......
156 158

  
157 159
  /**
158 160
   * Constructor Method
161
   *
162
   * @param $sid
159 163
   */
160
  function __construct($sid) {
164
  public function __construct($sid) {
161 165
    if (!is_scalar($sid)) {
162 166
      return;
163 167
    }
......
176 180
    else {
177 181
      $select = db_select('ldap_servers')
178 182
        ->fields('ldap_servers')
179
        ->condition('ldap_servers.sid',  $sid)
183
        ->condition('ldap_servers.sid', $sid)
180 184
        ->execute();
181 185
      foreach ($select as $record) {
182 186
        if ($record->sid == $sid) {
......
204 208
  }
205 209

  
206 210
  /**
207
   * this method sets properties that don't directly map from db record.  it is split out so it can be shared with ldapServerTest.class.php
211
   * This method sets properties that don't directly map from db record.
212
   *
213
   * It is split out so it can be shared with ldapServerTest.class.php
214
   *
215
   * @param $bindpw
208 216
   */
209 217
  protected function initDerivedProperties($bindpw) {
210 218

  
......
223 231
        $this->basedn = array();
224 232
        $token = is_scalar($basedn_unserialized) ? $basedn_unserialized : print_r($basedn_unserialized, TRUE);
225 233
        debug("basednb desearialization error". $token);
226
        watchdog('ldap_server', 'Failed to deserialize LdapServer::basedn of !basedn', array('!basedn' => $token), WATCHDOG_ERROR);
234
        watchdog('ldap_servers', 'Failed to deserialize LdapServer::basedn of !basedn', array('!basedn' => $token), WATCHDOG_ERROR);
227 235
      }
228 236

  
229 237
    }
......
236 244
      $this->bindpw = ($bindpw == '') ? '' : ldap_servers_decrypt($bindpw);
237 245
    }
238 246

  
247
    $bind_overrides = variable_get('ldap_servers_overrides', []);
248
    if (isset($bind_overrides[$this->sid])) {
249
      if (isset($bind_overrides[$this->sid]['binddn'])) {
250
        $this->binddn = $bind_overrides[$this->sid]['binddn'];
251
      }
252
      if (isset($bind_overrides[$this->sid]['bindpw'])) {
253
        $this->bindpw = $bind_overrides[$this->sid]['bindpw'];
254
      }
255
    }
256

  
239 257
    $this->paginationEnabled = (boolean)(ldap_servers_php_supports_pagination() && $this->searchPagination);
240 258

  
241 259
    $this->queriableWithoutUserCredentials = (boolean)(
......
247 265
    $this->groupGroupEntryMembershipsConfigured = ($this->groupMembershipsAttrMatchingUserAttr && $this->groupMembershipsAttr);
248 266
    $this->groupUserMembershipsConfigured = ($this->groupUserMembershipsAttrExists && $this->groupUserMembershipsAttr);
249 267
  }
268

  
250 269
  /**
251 270
   * Destructor Method
252 271
   */
253
  function __destruct() {
272
  public function __destruct() {
254 273
    // Close the server connection to be sure.
255 274
    $this->disconnect();
256 275
  }
257 276

  
258

  
259 277
  /**
260 278
   * Invoke Method
261 279
   */
262
  function __invoke() {
280
  public function __invoke() {
263 281
    $this->connect();
264 282
    $this->bind();
265 283
  }
266 284

  
267

  
268

  
269 285
  /**
270 286
   * Connect Method
271 287
   */
272
  function connect() {
288
  public function connect() {
289
    if (!function_exists('ldap_connect')) {
290
      watchdog('ldap_servers', 'PHP LDAP extension not found, aborting.');
291
      return LDAP_NOT_SUPPORTED;
292
    }
273 293

  
274 294
    if (!$con = ldap_connect($this->address, $this->port)) {
275
      watchdog('user', 'LDAP Connect failure to ' . $this->address . ':' . $this->port);
295
      watchdog('ldap_servers', 'LDAP Connect failure to ' . $this->address . ':' . $this->port);
276 296
      return LDAP_CONNECT_ERROR;
277 297
    }
278 298

  
......
283 303
    if ($this->tls) {
284 304
      ldap_get_option($con, LDAP_OPT_PROTOCOL_VERSION, $vers);
285 305
      if ($vers == -1) {
286
        watchdog('user', 'Could not get LDAP protocol version.');
306
        watchdog('ldap_servers', 'Could not get LDAP protocol version.');
287 307
        return LDAP_PROTOCOL_ERROR;
288 308
      }
289 309
      if ($vers != 3) {
290
        watchdog('user', 'Could not start TLS, only supported by LDAP v3.');
310
        watchdog('ldap_servers', 'Could not start TLS, only supported by LDAP v3.');
291 311
        return LDAP_CONNECT_ERROR;
292 312
      }
293 313
      elseif (!function_exists('ldap_start_tls')) {
294
        watchdog('user', 'Could not start TLS. It does not seem to be supported by this PHP setup.');
314
        watchdog('ldap_servers', 'Could not start TLS. It does not seem to be supported by this PHP setup.');
295 315
        return LDAP_CONNECT_ERROR;
296 316
      }
297 317
      elseif (!ldap_start_tls($con)) {
298
        $msg =  t("Could not start TLS. (Error %errno: %error).", array('%errno' => ldap_errno($con), '%error' => ldap_error($con)));
299
        watchdog('user', $msg);
318
        $msg = t("Could not start TLS. (Error %errno: %error).", array('%errno' => ldap_errno($con), '%error' => ldap_error($con)));
319
        watchdog('ldap_servers', $msg);
300 320
        return LDAP_CONNECT_ERROR;
301 321
      }
302 322
    }
......
318 338
   * @return
319 339
   *   Result of bind; TRUE if successful, FALSE otherwise.
320 340
   */
321
  function bind($userdn = NULL, $pass = NULL, $anon_bind = FALSE) {
341
  public function bind($userdn = NULL, $pass = NULL, $anon_bind = FALSE) {
322 342

  
323 343
    // Ensure that we have an active server connection.
324 344
    if (!$this->connection) {
325
      watchdog('ldap', "LDAP bind failure for user %user. Not connected to LDAP server.", array('%user' => $userdn));
345
      watchdog('ldap_servers', "LDAP bind failure for user %user. Not connected to LDAP server.", array('%user' => $userdn));
326 346
      return LDAP_CONNECT_ERROR;
327 347
    }
328 348

  
......
332 352
    if ($anon_bind === TRUE) {
333 353
      if (@!ldap_bind($this->connection)) {
334 354
        if ($this->detailedWatchdogLog) {
335
          watchdog('ldap', "LDAP anonymous bind error. Error %errno: %error", array('%errno' => ldap_errno($this->connection), '%error' => ldap_error($this->connection)));
355
          watchdog('ldap_servers', "LDAP anonymous bind error. Error %errno: %error", array('%errno' => ldap_errno($this->connection), '%error' => ldap_error($this->connection)));
336 356
        }
337 357
        return ldap_errno($this->connection);
338 358
      }
......
347 367
      }
348 368

  
349 369
      if (drupal_strlen($pass) == 0 || drupal_strlen($userdn) == 0) {
350
        watchdog('ldap', "LDAP bind failure for user userdn=%userdn, pass=%pass.", array('%userdn' => $userdn, '%pass' => $pass));
370
        watchdog('ldap_servers', "LDAP bind failure for user userdn=%userdn, pass=%pass.", array('%userdn' => $userdn, '%pass' => $pass));
351 371
        return LDAP_LOCAL_ERROR;
352 372
      }
353 373
      if (@!ldap_bind($this->connection, $userdn, $pass)) {
354 374
        if ($this->detailedWatchdogLog) {
355
          watchdog('ldap', "LDAP bind failure for user %user. Error %errno: %error", array('%user' => $userdn, '%errno' => ldap_errno($this->connection), '%error' => ldap_error($this->connection)));
375
          watchdog('ldap_servers', "LDAP bind failure for user %user. Error %errno: %error", array('%user' => $userdn, '%errno' => ldap_errno($this->connection), '%error' => ldap_error($this->connection)));
356 376
        }
357 377
        return ldap_errno($this->connection);
358 378
      }
......
364 384
  /**
365 385
   * Disconnect (unbind) from an active LDAP server.
366 386
   */
367
  function disconnect() {
387
  public function disconnect() {
368 388
    if (!$this->connection) {
369 389
      // never bound or not currently bound, so no need to disconnect
370
      //watchdog('ldap', 'LDAP disconnect failure from '. $this->server_addr . ':' . $this->port);
390
      //watchdog('ldap_servers', 'LDAP disconnect failure from '. $this->server_addr . ':' . $this->port);
371 391
    }
372 392
    else {
373 393
      ldap_unbind($this->connection);
......
375 395
    }
376 396
  }
377 397

  
398
  /**
399
   *
400
   */
378 401
  public function connectAndBindIfNotAlready() {
379 402
    if (! $this->connection) {
380 403
      $this->connect();
......
382 405
    }
383 406
  }
384 407

  
385
/**
386
 * does dn exist for this server?
387
 * [ ] Finished
388
 * [ ] Test Coverage.  Test ID:
389
 * [ ] Case insensitive
390
 *
391
 * @param string $dn
392
 * @param enum $return = 'boolean' or 'ldap_entry'
393
 * @param array $attributes in same form as ldap_read $attributes parameter
394
 *
395
 * @param return FALSE or ldap entry array
396
 */
397
  function dnExists($dn, $return = 'boolean', $attributes = NULL) {
408
  /**
409
   * does dn exist for this server?
410
   *
411
   *
412
   * @param string $dn
413
   * @param enum $return = 'boolean' or 'ldap_entry'
414
   * @param array $attributes in same form as ldap_read $attributes parameter
415
   *
416
   * @return bool|array
417
   */
418
  public function dnExists($dn, $return = 'boolean', $attributes = NULL) {
398 419

  
399 420
    $params = array(
400 421
      'base_dn' => $dn,
......
435 456
    return ldap_count_entries($this->connection, $ldap_result);
436 457
  }
437 458

  
438

  
439

  
440 459
  /**
441 460
   * create ldap entry.
442 461
   *
443 462
   * @param array $attributes should follow the structure of ldap_add functions
444 463
   *   entry array: http://us.php.net/manual/en/function.ldap-add.php
445
        $attributes["attribute1"] = "value";
446
        $attributes["attribute2"][0] = "value1";
447
        $attributes["attribute2"][1] = "value2";
464
   *     $attributes["attribute1"] = "value";
465
   *     $attributes["attribute2"][0] = "value1";
466
   *     $attributes["attribute2"][1] = "value2";
448 467
   * @return boolean result
449 468
   */
450

  
451 469
  public function createLdapEntry($attributes, $dn = NULL) {
452 470

  
453 471
    if (!$this->connection) {
......
470 488
    if (!$result) {
471 489
      $error = "LDAP Server ldap_add(%dn) Error Server ID = %sid, LDAP Err No: %ldap_errno LDAP Err Message: %ldap_err2str ";
472 490
      $tokens = array('%dn' => $dn, '%sid' => $this->sid, '%ldap_errno' => ldap_errno($this->connection), '%ldap_err2str' => ldap_err2str(ldap_errno($this->connection)));
473
      watchdog('ldap_server', $error, $tokens, WATCHDOG_ERROR);
491
      watchdog('ldap_servers', $error, $tokens, WATCHDOG_ERROR);
474 492
    }
475 493

  
476 494
    return $result;
477 495
  }
478 496

  
479

  
480

  
481
/**
482
 * given 2 ldap entries, old and new, removed unchanged values to avoid security errors and incorrect date modifieds
483
 *
484
 * @param ldap entry array $new_entry in form <attribute> => <value>
485
 * @param ldap entry array $old_entry in form <attribute> => array('count' => N, array(<value>,...<value>
486
 *
487
 * @return ldap array with no values that have NOT changed
488
 */
489

  
490
  static public function removeUnchangedAttributes($new_entry, $old_entry) {
497
  /**
498
   * Compares 2 LDAP entries and returns the difference.
499
   *
500
   * Given 2 ldap entries, old and new, removes unchanged values to avoid
501
   * security errors and incorrect date modified.
502
   *
503
   * @param array $new_entry
504
   *   LDAP entry array in form <attribute> => <value>, or
505
   *   <attribute> => array(<value1>, <value2>, ...).
506
   * @param array $old_entry
507
   *   LDAP entry in form <attribute> =>
508
   *   array('count' => N, <value1>, <value2>, ...).
509
   *
510
   * @return array
511
   *   The $new_entry with unchanged attributes removed.
512
   *
513
   * @see \LdapServer::modifyLdapEntry()
514
   */
515
  public static function removeUnchangedAttributes($new_entry, $old_entry) {
491 516

  
492 517
    foreach ($new_entry as $key => $new_val) {
493 518
      $old_value = FALSE;
......
513 538
        unset($new_entry[$key]); // don't change values that aren't changing to avoid false permission constraints
514 539
      }
515 540
    }
541

  
516 542
    return $new_entry;
517 543
  }
518 544

  
519

  
520

  
521

  
522

  
523 545
  /**
524 546
   * modify attributes of ldap entry
525 547
   *
526 548
   * @param string $dn DN of entry
527 549
   * @param array $attributes should follow the structure of ldap_add functions
528 550
   *   entry array: http://us.php.net/manual/en/function.ldap-add.php
529
        $attributes["attribute1"] = "value";
530
        $attributes["attribute2"][0] = "value1";
531
        $attributes["attribute2"][1] = "value2";
532

  
533
    @return TRUE on success FALSE on error
551
   *     $attributes["attribute1"] = "value";
552
   *     $attributes["attribute2"][0] = "value1";
553
   *     $attributes["attribute2"][1] = "value2";
554
   *
555
   * @return TRUE on success FALSE on error
534 556
   */
535

  
536
  function modifyLdapEntry($dn, $attributes = array(), $old_attributes = FALSE) {
557
  public function modifyLdapEntry($dn, $attributes = array(), $old_attributes = FALSE) {
537 558

  
538 559
    $this->connectAndBindIfNotAlready();
539 560

  
......
542 563
      if (!$result) {
543 564
        $error = "LDAP Server ldap_read(%dn) in LdapServer::modifyLdapEntry() Error Server ID = %sid, LDAP Err No: %ldap_errno LDAP Err Message: %ldap_err2str ";
544 565
        $tokens = array('%dn' => $dn, '%sid' => $this->sid, '%ldap_errno' => ldap_errno($this->connection), '%ldap_err2str' => ldap_err2str(ldap_errno($this->connection)));
545
        watchdog('ldap_server', $error, $tokens, WATCHDOG_ERROR);
566
        watchdog('ldap_servers', $error, $tokens, WATCHDOG_ERROR);
546 567
        return FALSE;
547 568
      }
548 569

  
549 570
      $entries = ldap_get_entries($this->connection, $result);
550 571
      if (is_array($entries) && $entries['count'] == 1) {
551
        $old_attributes =  $entries[0];
572
        $old_attributes = $entries[0];
552 573
      }
553 574
    }
554 575

  
......
577 598
        if (!$result) {
578 599
          $error = "LDAP Server ldap_mod_del(%dn) in LdapServer::modifyLdapEntry() Error Server ID = %sid, LDAP Err No: %ldap_errno LDAP Err Message: %ldap_err2str ";
579 600
          $tokens = array('%dn' => $dn, '%sid' => $this->sid, '%ldap_errno' => ldap_errno($this->connection), '%ldap_err2str' => ldap_err2str(ldap_errno($this->connection)));
580
          watchdog('ldap_server', $error, $tokens, WATCHDOG_ERROR);
601
          watchdog('ldap_servers', $error, $tokens, WATCHDOG_ERROR);
581 602
          return FALSE;
582 603
        }
583 604
      }
......
598 619
      if (!$result) {
599 620
        $error = "LDAP Server ldap_modify(%dn) in LdapServer::modifyLdapEntry() Error Server ID = %sid, LDAP Err No: %ldap_errno LDAP Err Message: %ldap_err2str ";
600 621
        $tokens = array('%dn' => $dn, '%sid' => $this->sid, '%ldap_errno' => ldap_errno($this->connection), '%ldap_err2str' => ldap_err2str(ldap_errno($this->connection)));
601
        watchdog('ldap_server', $error, $tokens, WATCHDOG_ERROR);
622
        watchdog('ldap_servers', $error, $tokens, WATCHDOG_ERROR);
602 623
        return FALSE;
603 624
      }
604 625
    }
......
614 635
   *
615 636
   * @return boolean result per ldap_delete
616 637
   */
617

  
618 638
  public function delete($dn) {
619 639
    if (!$this->connection) {
620 640
      $this->connect();
......
624 644
    if (!$result) {
625 645
      $error = "LDAP Server delete(%dn) in LdapServer::delete() Error Server ID = %sid, LDAP Err No: %ldap_errno LDAP Err Message: %ldap_err2str ";
626 646
      $tokens = array('%dn' => $dn, '%sid' => $this->sid, '%ldap_errno' => ldap_errno($this->connection), '%ldap_err2str' => ldap_err2str(ldap_errno($this->connection)));
627
      watchdog('ldap_server', $error, $tokens, WATCHDOG_ERROR);
647
      watchdog('ldap_servers', $error, $tokens, WATCHDOG_ERROR);
628 648
    }
629 649
    return $result;
630 650
  }
......
640 660
   *
641 661
   * @remaining params mimick ldap_search() function params
642 662
   *
643
   * @return
644
   *   An array of matching entries->attributes (will have 0
645
   *   elements if search returns no results),
646
   *   or FALSE on error on any of the basedn queries
663
   * @return array
664
   *   An array of matching entries->attributes (will have 0 elements if search
665
   *   returns no results), or FALSE on error on any of the basedn queries.
647 666
   */
648

  
649 667
  public function searchAllBaseDns(
650 668
    $filter,
651 669
    $attributes = array(),
......
678 696

  
679 697
  }
680 698

  
681

  
682 699
  /**
683 700
   * Perform an LDAP search.
701
   *
684 702
   * @param string $basedn
685 703
   *   The search base. If NULL, we use $this->basedn. should not be esacaped
686
   *
687 704
   * @param string $filter
688
   *   The search filter. such as sAMAccountName=jbarclay.  attribute values (e.g. jbarclay) should be esacaped before calling
689

  
705
   *   The search filter. such as sAMAccountName=jbarclay.  attribute values
706
   * (e.g. jbarclay) should be esacaped before calling
707
   *
690 708
   * @param array $attributes
691 709
   *   List of desired attributes. If omitted, we only return "dn".
692 710
   *
......
697 715
   *   elements if search returns no results),
698 716
   *   or FALSE on error.
699 717
   */
700

  
701
  function search($base_dn = NULL, $filter, $attributes = array(),
718
  public function search($base_dn = NULL, $filter, $attributes = array(),
702 719
    $attrsonly = 0, $sizelimit = 0, $timelimit = 0, $deref = NULL, $scope = LDAP_SCOPE_SUBTREE) {
703 720

  
704 721
     /**
......
708 725
      * -- http://sgehrig.wordpress.com/2009/11/06/reading-paged-ldap-results-with-php-is-a-show-stopper/
709 726
      */
710 727

  
711

  
712 728
    if ($base_dn == NULL) {
713 729
      if (count($this->basedn) == 1) {
714 730
        $base_dn = $this->basedn[0];
......
718 734
      }
719 735
    }
720 736

  
721
    $attr_display =  is_array($attributes) ? join(',', $attributes) : 'none';
737
    $attr_display = is_array($attributes) ? join(',', $attributes) : 'none';
722 738
    $query = 'ldap_search() call: ' . join(",\n", array(
723 739
      'base_dn: ' . $base_dn,
724 740
      'filter = ' . $filter,
......
731 747
      )
732 748
    );
733 749
    if ($this->detailed_watchdog_log) {
734
      watchdog('ldap_server', $query, array());
750
      watchdog('ldap_servers', $query, array());
735 751
    }
736 752

  
737 753
    // When checking multiple servers, there's a chance we might not be connected yet.
......
765 781
        return (is_array($entries)) ? $entries : FALSE;
766 782
      }
767 783
      elseif ($this->ldapErrorNumber()) {
768
        $watchdog_tokens =  array('%basedn' => $ldap_query_params['base_dn'], '%filter' => $ldap_query_params['filter'],
784
        $watchdog_tokens = array('%basedn' => $ldap_query_params['base_dn'], '%filter' => $ldap_query_params['filter'],
769 785
          '%attributes' => print_r($ldap_query_params['attributes'], TRUE), '%errmsg' => $this->errorMsg('ldap'),
770 786
          '%errno' => $this->ldapErrorNumber());
771
        watchdog('ldap', "LDAP ldap_search error. basedn: %basedn| filter: %filter| attributes:
787
        watchdog('ldap_servers', "LDAP ldap_search error. basedn: %basedn| filter: %filter| attributes:
772 788
          %attributes| errmsg: %errmsg| ldap err no: %errno|", $watchdog_tokens);
773 789
        return FALSE;
774 790
      }
......
778 794
    }
779 795
  }
780 796

  
781

  
782 797
  /**
783 798
   * execute a paged ldap query and return entries as one aggregated array
784 799
   *
......
786 801
   *   a particular set of pages is desired
787 802
   *
788 803
   * @param array $ldap_query_params of form:
789
      'base_dn' => base_dn,
790
      'filter' =>  filter,
791
      'attributes' => attributes,
792
      'attrsonly' => attrsonly,
793
      'sizelimit' => sizelimit,
794
      'timelimit' => timelimit,
795
      'deref' => deref,
796
      'scope' => scope,
797

  
798
      (this array of parameters is primarily passed on to ldapQuery() method)
804
   *   'base_dn' => base_dn,
805
   *   'filter' =>  filter,
806
   *   'attributes' => attributes,
807
   *   'attrsonly' => attrsonly,
808
   *   'sizelimit' => sizelimit,
809
   *   'timelimit' => timelimit,
810
   *   'deref' => deref,
811
   *   'scope' => scope,
812
   *
813
   *   (this array of parameters is primarily passed on to ldapQuery() method)
799 814
   *
800 815
   * @return array of ldap entries or FALSE on error.
801 816
   *
......
803 818
  public function pagedLdapQuery($ldap_query_params) {
804 819

  
805 820
    if (!($this->searchPagination && $this->paginationEnabled)) {
806
      watchdog('ldap', "LDAP server pagedLdapQuery() called when functionality not available in php install or
821
      watchdog('ldap_servers', "LDAP server pagedLdapQuery() called when functionality not available in php install or
807 822
        not enabled in ldap server configuration.  error. basedn: %basedn| filter: %filter| attributes:
808 823
         %attributes| errmsg: %errmsg| ldap err no: %errno|", $watchdog_tokens);
809 824
      RETURN FALSE;
810 825
    }
811 826

  
812
    $paged_entries = array();
813 827
    $page_token = '';
814 828
    $page = 0;
815 829
    $estimated_entries = 0;
......
831 845
          $aggregated_entries_count = count($aggregated_entries);
832 846
        }
833 847
        elseif ($this->ldapErrorNumber()) {
834
          $watchdog_tokens =  array('%basedn' => $ldap_query_params['base_dn'], '%filter' => $ldap_query_params['filter'],
848
          $watchdog_tokens = array('%basedn' => $ldap_query_params['base_dn'], '%filter' => $ldap_query_params['filter'],
835 849
            '%attributes' => print_r($ldap_query_params['attributes'], TRUE), '%errmsg' => $this->errorMsg('ldap'),
836 850
            '%errno' => $this->ldapErrorNumber());
837
          watchdog('ldap', "LDAP ldap_search error. basedn: %basedn| filter: %filter| attributes:
851
          watchdog('ldap_servers', "LDAP ldap_search error. basedn: %basedn| filter: %filter| attributes:
838 852
            %attributes| errmsg: %errmsg| ldap err no: %errno|", $watchdog_tokens);
839 853
          RETURN FALSE;
840 854
        }
......
850 864
        // false positive error thrown.  do not set result limit error when $sizelimit specified
851 865
      }
852 866
      elseif ($this->hasError()) {
853
        watchdog('ldap_server', 'ldap_control_paged_result_response() function error. LDAP Error: %message, ldap_list() parameters: %query',
867
        watchdog('ldap_servers', 'ldap_control_paged_result_response() function error. LDAP Error: %message, ldap_list() parameters: %query',
854 868
          array('%message' => $this->errorMsg('ldap'), '%query' => $ldap_query_params['query_display']),
855 869
          WATCHDOG_ERROR);
856 870
      }
......
880 894
   *
881 895
   * @return array of ldap entries
882 896
   */
883
  function ldapQuery($scope, $params) {
897
  public function ldapQuery($scope, $params) {
884 898

  
885 899
    $this->connectAndBindIfNotAlready();
886 900

  
......
892 906
          // false positive error thrown.  do not return result limit error when $sizelimit specified
893 907
        }
894 908
        elseif ($this->hasError()) {
895
          watchdog('ldap_server', 'ldap_search() function error. LDAP Error: %message, ldap_search() parameters: %query',
909
          watchdog('ldap_servers', 'ldap_search() function error. LDAP Error: %message, ldap_search() parameters: %query',
896 910
            array('%message' => $this->errorMsg('ldap'), '%query' => $params['query_display']),
897 911
            WATCHDOG_ERROR);
898 912
        }
......
905 919
          // false positive error thrown.  do not result limit error when $sizelimit specified
906 920
        }
907 921
        elseif ($this->hasError()) {
908
          watchdog('ldap_server', 'ldap_read() function error.  LDAP Error: %message, ldap_read() parameters: %query',
922
          watchdog('ldap_servers', 'ldap_read() function error.  LDAP Error: %message, ldap_read() parameters: %query',
909 923
            array('%message' => $this->errorMsg('ldap'), '%query' => @$params['query_display']),
910 924
            WATCHDOG_ERROR);
911 925
        }
......
918 932
          // false positive error thrown.  do not result limit error when $sizelimit specified
919 933
        }
920 934
        elseif ($this->hasError()) {
921
          watchdog('ldap_server', 'ldap_list() function error. LDAP Error: %message, ldap_list() parameters: %query',
935
          watchdog('ldap_servers', 'ldap_list() function error. LDAP Error: %message, ldap_list() parameters: %query',
922 936
            array('%message' => $this->errorMsg('ldap'), '%query' => $params['query_display']),
923 937
            WATCHDOG_ERROR);
924 938
        }
......
931 945
   * @param array $dns Mixed Case
932 946
   * @return array $dns Lower Case
933 947
   */
934

  
935 948
  public function dnArrayToLowerCase($dns) {
936 949
    return array_keys(array_change_key_case(array_flip($dns), CASE_LOWER));
937 950
  }
938 951

  
939 952
  /**
940
   * @param binary or string $puid as returned from ldap_read or other ldap function
953
   * userUserEntityFromPuid.
941 954
   *
955
   * @param string $puid
956
   *   Binary or string as returned from ldap_read or other ldap function.
957
   *
958
   * @return mixed
942 959
   */
943 960
  public function userUserEntityFromPuid($puid) {
944 961

  
......
959 976
      }
960 977
      else {
961 978
        $uids = join(',', $uids);
962
        $tokens = array('%uids' => $uids, '%puid' => $puid, '%sid' =>  $this->sid, '%ldap_user_puid_property' =>  $this->unique_persistent_attr);
963
        watchdog('ldap_server', 'multiple users (uids: %uids) with same puid (puid=%puid, sid=%sid, ldap_user_puid_property=%ldap_user_puid_property)', $tokens, WATCHDOG_ERROR);
979
        $tokens = array('%uids' => $uids, '%puid' => $puid, '%sid' => $this->sid, '%ldap_user_puid_property' => $this->unique_persistent_attr);
980
        watchdog('ldap_servers', 'multiple users (uids: %uids) with same puid (puid=%puid, sid=%sid, ldap_user_puid_property=%ldap_user_puid_property)', $tokens, WATCHDOG_ERROR);
964 981
        return FALSE;
965 982
      }
966 983
    }
......
970 987

  
971 988
  }
972 989

  
973
  function userUsernameToLdapNameTransform($drupal_username, &$watchdog_tokens) {
990
  /**
991
   * @param $drupal_username
992
   * @param $watchdog_tokens
993
   *
994
   * @return string
995
   */
996
  public function userUsernameToLdapNameTransform($drupal_username, &$watchdog_tokens) {
974 997
    if ($this->ldapToDrupalUserPhp && module_exists('php')) {
975 998
      global $name;
976 999
      $old_name_value = $name;
......
983 1006
      $watchdog_tokens['%ldap_username'] = $ldap_username;
984 1007
      $name = $old_name_value;  // important because of global scope of $name
985 1008
      if ($this->detailedWatchdogLog) {
986
        watchdog('ldap_server', '%drupal_user_name tansformed to %ldap_username by applying code <code>%code</code>', $watchdog_tokens, WATCHDOG_DEBUG);
1009
        watchdog('ldap_servers', '%drupal_user_name tansformed to %ldap_username by applying code <code>%code</code>', $watchdog_tokens, WATCHDOG_DEBUG);
987 1010
      }
988 1011
    }
989 1012
    else {
......
1001 1024
  }
1002 1025

  
1003 1026

  
1004
 /**
1005
   * @param ldap entry array $ldap_entry
1027
  /**
1028
   * userUsernameFromLdapEntry.
1029
   *
1030
   * @param array $ldap_entry
1006 1031
   *
1007
   * @return string user's username value
1032
   * @return string
1033
   *   user's username value
1008 1034
   */
1009 1035
  public function userUsernameFromLdapEntry($ldap_entry) {
1010 1036

  
......
1022 1048
    return $accountname;
1023 1049
  }
1024 1050

  
1025
 /**
1026
   * @param string $dn ldap dn
1051
  /**
1052
   * userUsernameFromDn.
1027 1053
   *
1028
   * @return mixed string user's username value of FALSE
1054
   * @param string $dn
1055
   *
1056
   * @return mixed
1057
   *   string user's username value of FALSE
1029 1058
   */
1030 1059
  public function userUsernameFromDn($dn) {
1031 1060

  
......
1060 1089
  }
1061 1090

  
1062 1091
	/**
1063
	 * @param ldap entry array $ldap_entry
1092
	 * @param array $ldap_entry
1064 1093
	 *
1065
	 * @return drupal file object image user's thumbnail or FALSE if none present or ERROR happens.
1094
	 * @return object|bool
1095
   *   Drupal file object image user's thumbnail or FALSE if none present or
1096
   *   ERROR happens.
1066 1097
	 */
1067 1098
	public function userPictureFromLdapEntry($ldap_entry, $drupal_username = FALSE) {
1068 1099
		if ($ldap_entry && $this->picture_attr) {
1069 1100
			//Check if ldap entry has been provisioned.
1070 1101

  
1071
			$thumb = isset($ldap_entry[$this->picture_attr][0]) ? $ldap_entry[$this->picture_attr][0] : FALSE;
1072
			if(!$thumb){
1102
			$image_data = isset($ldap_entry[$this->picture_attr][0]) ? $ldap_entry[$this->picture_attr][0] : FALSE;
1103
			if (!$image_data) {
1073 1104
				return FALSE;
1074 1105
			}
1075 1106

  
1076
			//Create md5 check.
1077
			$md5thumb = md5($thumb);
1107
			$md5thumb = md5($image_data);
1078 1108

  
1079 1109
			/**
1080
			 * If existing account already has picture check if it has changed if so remove old file and create the new one
1081
		   * If picture is not set but account has md5 something is wrong exit.
1110
			 * If the existing account already has picture check if it has changed. If
1111
       * so remove the old file and create the new one. If a picture is not set
1112
       * but the account has an md5 hash, something is wrong and we exit.
1082 1113
			 */
1083 1114
			if ($drupal_username && $account = user_load_by_name($drupal_username)) {
1084
        if ($account->uid == 0 || $account->uid == 1){
1115
        if ($account->uid == 0 || $account->uid == 1) {
1085 1116
          return FALSE;
1086 1117
        }
1087
        if (isset($account->picture)){
1088
          // Check if image has changed
1089
          if (isset($account->data['ldap_user']['init']['thumb5md']) && $md5thumb === $account->data['ldap_user']['init']['thumb5md']){
1090
            //No change return same image
1118
        if (isset($account->picture)) {
1119
          // Check if image has changed.
1120
          if (isset($account->data['ldap_user']['init']['thumb5md']) && $md5thumb === $account->data['ldap_user']['init']['thumb5md']) {
1121
            // No change, return same image.
1122
            $account->picture->md5Sum = $md5thumb;
1091 1123
            return $account->picture;
1092 1124
          }
1093 1125
          else {
1094
            //Image is different check wether is obj/str and remove fileobject
1095
            if (is_object($account->picture)){
1126
            // Image is different, remove file object.
1127
            if (is_object($account->picture)) {
1096 1128
              file_delete($account->picture, TRUE);
1097 1129
            }
1098
            elseif (is_string($account->picture)){
1130
            elseif (is_string($account->picture)) {
1099 1131
              $file = file_load(intval($account->picture));
1100 1132
              file_delete($file, TRUE);
1101 1133
            }
1102 1134
          }
1103 1135
        }
1104 1136
        elseif (isset($account->data['ldap_user']['init']['thumb5md'])) {
1105
          watchdog('ldap_server', "Some error happened during thumbnailPhoto sync");
1137
          watchdog('ldap_servers', "Some error happened during thumbnailPhoto sync.");
1106 1138
          return FALSE;
1107 1139
        }
1108 1140
      }
1109
			//Create tmp file to get image format.
1110
			$filename = uniqid();
1111
			$fileuri = file_directory_temp() .'/'. $filename;
1112
			$size = file_put_contents($fileuri, $thumb);
1113
			$info = image_get_info($fileuri);
1114
			unlink($fileuri);
1115
			// create file object
1116
			$file = file_save_data($thumb, 'public://' . variable_get('user_picture_path') .'/'. $filename .'.'. $info['extension']);
1117
			$file->md5Sum = $md5thumb;
1118
			// standard Drupal validators for user pictures
1119
			$validators = array(
1120
					'file_validate_is_image' => array(),
1121
					'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
1122
					'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
1123
			);
1124
			$errors = file_validate($file ,$validators);
1125
			if (empty($errors)) {
1126
				return $file;
1127
			}
1128
      else {
1129
				foreach ($errors as $err => $err_val){
1130
					watchdog('ldap_server', "Error storing picture: %$err", array("%$err" => $err_val), WATCHDOG_ERROR);
1131
				}
1132
				return FALSE;
1133
			}
1134
		}
1141
      return $this->savePictureData($image_data, $md5thumb);
1142
    }
1143
    return FALSE;
1135 1144
	}
1136 1145

  
1137 1146

  
1138 1147
  /**
1139
   * @param ldap entry array $ldap_entry
1148
   * @param $image_data
1149
   * @param $md5thumb
1150
   */
1151
  private function savePictureData($image_data, $md5thumb) {
1152
    //Create tmp file to get image format.
1153
    $filename = uniqid();
1154
    $fileuri = file_directory_temp() . '/' . $filename;
1155
    $size = file_put_contents($fileuri, $image_data);
1156
    $info = image_get_info($fileuri);
1157
    unlink($fileuri);
1158
    // create file object
1159
    $file = file_save_data($image_data, file_default_scheme() . '://' . variable_get('user_picture_path') . '/' . $filename . '.' . $info['extension']);
1160
    $file->md5Sum = $md5thumb;
1161
    // standard Drupal validators for user pictures
1162
    $validators = [
1163
      'file_validate_is_image' => [],
1164
      'file_validate_image_resolution' => [variable_get('user_picture_dimensions', '85x85')],
1165
      'file_validate_size' => [variable_get('user_picture_file_size', '30') * 1024],
1166
    ];
1167
    $errors = file_validate($file, $validators);
1168
    if (empty($errors)) {
1169
      return $file;
1170
    }
1171
    else {
1172
      foreach ($errors as $err => $err_val) {
1173
        watchdog('ldap_servers', "Error storing picture: %error", ["%error" => $err_val], WATCHDOG_ERROR);
1174
      }
1175
      return FALSE;
1176
    }
1177
  }
1178

  
1179

  
1180
  /**
1181
   * @param array $ldap_entry
1140 1182
   *
1141 1183
   * @return string user's PUID or permanent user id (within ldap), converted from binary, if applicable
1142 1184
   */
......
1159 1201
    }
1160 1202
  }
1161 1203

  
1162
   /**
1204
  /**
1163 1205
   *  @param mixed $user
1164 1206
   *    - drupal user object (stdClass Object)
1165 1207
   *    - ldap entry of user (array)
......
1167 1209
   *    - drupal username of user (string)
1168 1210
   *
1169 1211
   *  @return array $ldap_user_entry (with top level keys of 'dn', 'mail', 'sid' and 'attr' )
1170
  */
1212
   */
1171 1213
  public function user_lookup($user) {
1172 1214
    return $this->userUserToExistingLdapEntry($user);
1173 1215
  }
......
1206 1248
   *   'attr' => single ldap entry array in form returned from ldap_search() extension, e.g.
1207 1249
   *   'dn' => dn of entry
1208 1250
   */
1209
  function userUserNameToExistingLdapEntry($drupal_user_name, $ldap_context = NULL) {
1251
  public function userUserNameToExistingLdapEntry($drupal_user_name, $ldap_context = NULL) {
1210 1252

  
1211 1253
    $watchdog_tokens = array('%drupal_user_name' => $drupal_user_name);
1212 1254
    $ldap_username = $this->userUsernameToLdapNameTransform($drupal_user_name, $watchdog_tokens);
......
1252 1294
      else {
1253 1295
        if ($this->bind_method == LDAP_SERVERS_BIND_METHOD_ANON_USER) {
1254 1296
          $result = array(
1255
            'dn' =>  $match['dn'],
1297
            'dn' => $match['dn'],
1256 1298
            'mail' => $this->userEmailFromLdapEntry($match),
1257 1299
            'attr' => $match,
1258 1300
            'sid' => $this->sid,
......
1275 1317
      foreach ($match[$name_attr] as $value) {
1276 1318
        if (drupal_strtolower(trim($value)) == drupal_strtolower($ldap_username)) {
1277 1319
          $result = array(
1278
            'dn' =>  $match['dn'],
1320
            'dn' => $match['dn'],
1279 1321
            'mail' => $this->userEmailFromLdapEntry($match),
1280 1322
            'attr' => $match,
1281 1323
            'sid' => $this->sid,
......
1306 1348
    return (is_array($group_dns) && in_array(drupal_strtolower($group_dn), $this->dnArrayToLowerCase($group_dns)));
1307 1349
  }
1308 1350

  
1309

  
1310

  
1311 1351
  /**
1312 1352
   * NOT TESTED
1313 1353
   * add a group entry
......
1475 1515

  
1476 1516
  }
1477 1517

  
1478
/**
1518
  /**
1479 1519
   *   NOT IMPLEMENTED
1480 1520
   * recurse through all child groups and add members.
1481 1521
   *
......
1488 1528
   * @param int $max_levels as max recursion allowed
1489 1529
   *
1490 1530
   */
1491

  
1492 1531
  public function groupMembersResursive($current_member_entries, &$all_member_dns, &$tested_group_ids, $level, $max_levels, $object_classes = FALSE) {
1493 1532

  
1494 1533
    if (!$this->groupGroupEntryMembershipsConfigured || !is_array($current_member_entries) || count($current_member_entries) == 0) {
......
1523 1562
          };
1524 1563
          $ors = array();
1525 1564
          foreach ($member_ids as $i => $member_id) {
1526
            $ors[] =  $this->groupMembershipsAttr . '=' . ldap_pear_escape_filter_value($member_id); // @todo this would be replaced by query template
1565
            $ors[] = $this->groupMembershipsAttr . '=' . ldap_pear_escape_filter_value($member_id); // @todo this would be replaced by query template
1527 1566
          }
1528 1567

  
1529 1568
          if (count($ors)) {
......
1548 1587
  }
1549 1588

  
1550 1589

  
1551
 /**
1552 1590
  /**
1553 1591
   *  get list of all groups that a user is a member of.
1554 1592
   *
......
1569 1607
   *
1570 1608
   *  @return array of groups dns in mixed case or FALSE on error
1571 1609
   */
1572

  
1573 1610
  public function groupMembershipsFromUser($user, $return = 'group_dns', $nested = NULL) {
1574 1611

  
1575 1612
    $group_dns = FALSE;
......
1618 1655
   *
1619 1656
   *  @return array of group dns
1620 1657
   */
1621

  
1622 1658
  public function groupUserMembershipsFromUserAttr($user, $nested = NULL) {
1623 1659

  
1624 1660
    if (!$this->groupUserMembershipsConfigured) {
......
1656 1692
        else {
1657 1693
          $member_value = ldap_servers_get_first_rdn_value_from_dn($member_group_dn, $this->groupMembershipsAttrMatchingUserAttr);
1658 1694
        }
1659
        $ors[] =  $this->groupMembershipsAttr . '=' . ldap_pear_escape_filter_value($member_value);
1695
        $ors[] = $this->groupMembershipsAttr . '=' . ldap_pear_escape_filter_value($member_value);
1660 1696
      }
1661 1697
    }
1662 1698

  
1663 1699
    if ($nested && count($ors)) {
1664 1700
      $count = count($ors);
1665
      for ($i=0; $i < $count; $i=$i+LDAP_SERVER_LDAP_QUERY_CHUNK) { // only 50 or so per query
1701
      for ($i = 0; $i < $count; $i = $i + LDAP_SERVER_LDAP_QUERY_CHUNK) { // only 50 or so per query
1666 1702
        $current_ors = array_slice($ors, $i, LDAP_SERVER_LDAP_QUERY_CHUNK);
1667 1703
        $or = '(|(' . join(")(", $current_ors) . '))';  // e.g. (|(cn=group1)(cn=group2)) or   (|(dn=cn=group1,ou=blah...)(dn=cn=group2,ou=blah...))
1668 1704
        $query_for_parent_groups = '(&(objectClass=' . $this->groupObjectClass . ')' . $or . ')';
......
1758 1794
   *
1759 1795
   * @return FALSE for error or misconfiguration, otherwise TRUE.  results are passed by reference.
1760 1796
   */
1761

  
1762 1797
  public function groupMembershipsFromEntryRecursive($current_group_entries, &$all_group_dns, &$tested_group_ids, $level, $max_levels) {
1763 1798

  
1764 1799
    if (!$this->groupGroupEntryMembershipsConfigured || !is_array($current_group_entries) || count($current_group_entries) == 0) {
......
1777 1812
        $member_id = ldap_servers_get_first_rdn_value_from_dn($group_entry['dn'], $this->groupMembershipsAttrMatchingUserAttr);
1778 1813
	if(!$member_id) {
1779 1814
	  if ($this->detailed_watchdog_log) {
1780
	     watchdog('ldap_server', 'group_entry: %ge', array('%ge'=>pretty_print_ldap_entry($group_entry)));
1815
	     watchdog('ldap_servers', 'group_entry: %ge', array('%ge' => pretty_print_ldap_entry($group_entry)));
1781 1816
	  }
1782 1817
	  // group not identified by simple checks yet!
1783 1818

  
1784 1819
	  // examine the entry and see if it matches the configured groupObjectClass
1785
	  $goc=$group_entry['objectclass']; // TODO do we need to ensure such entry is there?
1820
	  $goc = $group_entry['objectclass']; // TODO do we need to ensure such entry is there?
1786 1821
	  if(is_array($goc)) {              // TODO is it always an array?
1787 1822
	    foreach($goc as $g) {
1788
	      $g=drupal_strtolower($g);
1823
	      $g = drupal_strtolower($g);
1789 1824
	      if($g == $this->groupObjectClass) {
1790 1825
		// found a group, current user must be member in it - so:
1791 1826
		if ($this->detailed_watchdog_log) {
1792
		  watchdog('ldap_server', 'adding %mi', array('%mi'=>$member_id));
1827
		  watchdog('ldap_servers', 'adding %mi', array('%mi' => $member_id));
1793 1828
		}
1794
		$member_id=$group_entry['dn'];
1829
		$member_id = $group_entry['dn'];
1795 1830
		break;
1796 1831
	      }
1797 1832
	    }
......
1803 1838
        $tested_group_ids[] = $member_id;
1804 1839
        $all_group_dns[] = $group_entry['dn'];
1805 1840
        // add $group_id (dn, cn, uid) to query
1806
        $ors[] =  $this->groupMembershipsAttr . '=' .  ldap_pear_escape_filter_value($member_id);
1841
        $ors[] = $this->groupMembershipsAttr . '=' .  ldap_pear_escape_filter_value($member_id);
1807 1842
      }
1808 1843
    }
1809 1844

  
1810 1845
    if ($level < $max_levels && count($ors)) {
1811 1846
      $count = count($ors);
1812
      for ($i=0; $i < $count; $i=$i+LDAP_SERVER_LDAP_QUERY_CHUNK) { // only 50 or so per query
1847
      for ($i = 0; $i < $count; $i = $i + LDAP_SERVER_LDAP_QUERY_CHUNK) { // only 50 or so per query
1813 1848
        $current_ors = array_slice($ors, $i, LDAP_SERVER_LDAP_QUERY_CHUNK);
1814 1849
        $or = '(|(' . join(")(", $current_ors) . '))';  // e.g. (|(cn=group1)(cn=group2)) or   (|(dn=cn=group1,ou=blah...)(dn=cn=group2,ou=blah...))
1815 1850
        $query_for_parent_groups = '(&(objectClass=' . $this->groupObjectClass . ')' . $or . ')';
......
1827 1862
  }
1828 1863

  
1829 1864

  
1830
 /**
1831
   *  get "groups" from derived from DN.  Has limited usefulness
1865
  /**
1866
   * Get "groups" from derived from DN.  Has limited usefulness
1832 1867
   *
1833 1868
   *  @param mixed
1834 1869
   *    - drupal user object (stdClass Object)

Formats disponibles : Unified diff