dolibarr 20.0.0
ldap.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
4 * Copyright (C) 2005-2021 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2006-2021 Laurent Destailleur <eldy@users.sourceforge.net>
6 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
7 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 * or see https://www.gnu.org/
22 */
23
37class Ldap
38{
42 public $error = '';
43
47 public $errors = array();
48
52 public $server = array();
53
57 public $connectedServer;
58
62 public $serverPort;
63
68 public $dn;
73 public $serverType;
78 public $ldapProtocolVersion;
83 public $domain;
84
88 public $domainFQDN;
89
93 public $bind;
94
99 public $searchUser;
104 public $searchPassword;
105
109 public $people;
110
114 public $groups;
115
119 public $ldapErrorCode;
120
124 public $ldapErrorText;
125
129 public $filter;
130
134 public $filtergroup;
135
139 public $filtermember;
140
144 public $attr_login;
145
149 public $attr_sambalogin;
150
154 public $attr_name;
155
159 public $attr_firstname;
160
164 public $attr_mail;
165
169 public $attr_phone;
170
174 public $attr_fax;
175
179 public $attr_mobile;
180
184 public $badpwdtime;
185
189 public $ldapUserDN;
190
194 public $name;
195
199 public $firstname;
200
204 public $login;
205
209 public $phone;
210
214 public $fax;
215
219 public $mail;
220
224 public $mobile;
225
229 public $uacf;
230
234 public $pwdlastset;
235
240 public $ldapcharset = 'UTF-8';
241
245 public $connection;
246
250 public $result;
251
255 const SYNCHRO_NONE = 0;
256
260 const SYNCHRO_DOLIBARR_TO_LDAP = 1;
261
265 const SYNCHRO_LDAP_TO_DOLIBARR = 2;
266
270 public function __construct()
271 {
272
273 // Server
274 if (getDolGlobalString('LDAP_SERVER_HOST')) {
275 $this->server[] = getDolGlobalString('LDAP_SERVER_HOST');
276 }
277 if (getDolGlobalString('LDAP_SERVER_HOST_SLAVE')) {
278 $this->server[] = getDolGlobalString('LDAP_SERVER_HOST_SLAVE');
279 }
280 $this->serverPort = getDolGlobalInt('LDAP_SERVER_PORT', 389);
281 $this->ldapProtocolVersion = getDolGlobalString('LDAP_SERVER_PROTOCOLVERSION');
282 $this->dn = getDolGlobalString('LDAP_SERVER_DN');
283 $this->serverType = getDolGlobalString('LDAP_SERVER_TYPE');
284
285 $this->domain = getDolGlobalString('LDAP_SERVER_DN');
286 $this->searchUser = getDolGlobalString('LDAP_ADMIN_DN');
287 $this->searchPassword = getDolGlobalString('LDAP_ADMIN_PASS');
288 $this->people = getDolGlobalString('LDAP_USER_DN');
289 $this->groups = getDolGlobalString('LDAP_GROUP_DN');
290
291 $this->filter = getDolGlobalString('LDAP_FILTER_CONNECTION'); // Filter on user
292 $this->filtergroup = getDolGlobalString('LDAP_GROUP_FILTER'); // Filter on groups
293 $this->filtermember = getDolGlobalString('LDAP_MEMBER_FILTER'); // Filter on member
294
295 // Users
296 $this->attr_login = getDolGlobalString('LDAP_FIELD_LOGIN'); //unix
297 $this->attr_sambalogin = getDolGlobalString('LDAP_FIELD_LOGIN_SAMBA'); //samba, activedirectory
298 $this->attr_name = getDolGlobalString('LDAP_FIELD_NAME');
299 $this->attr_firstname = getDolGlobalString('LDAP_FIELD_FIRSTNAME');
300 $this->attr_mail = getDolGlobalString('LDAP_FIELD_MAIL');
301 $this->attr_phone = getDolGlobalString('LDAP_FIELD_PHONE');
302 $this->attr_fax = getDolGlobalString('LDAP_FIELD_FAX');
303 $this->attr_mobile = getDolGlobalString('LDAP_FIELD_MOBILE');
304 }
305
306 // Connection handling methods -------------------------------------------
307
316 public function connectBind()
317 {
318 global $dolibarr_main_auth_ldap_debug;
319
320 $connected = 0;
321 $this->bind = false;
322 $this->error = '';
323 $this->connectedServer = '';
324
325 $ldapdebug = ((empty($dolibarr_main_auth_ldap_debug) || $dolibarr_main_auth_ldap_debug == "false") ? false : true);
326
327 if ($ldapdebug) {
328 dol_syslog(get_class($this)."::connectBind");
329 print "DEBUG: connectBind<br>\n";
330 }
331
332 // Check parameters
333 if (count($this->server) == 0 || empty($this->server[0])) {
334 $this->error = 'LDAP setup (file conf.php) is not complete';
335 dol_syslog(get_class($this)."::connectBind ".$this->error, LOG_WARNING);
336 return -1;
337 }
338
339 if (!function_exists("ldap_connect")) {
340 $this->error = 'LDAPFunctionsNotAvailableOnPHP';
341 dol_syslog(get_class($this)."::connectBind ".$this->error, LOG_WARNING);
342 return -1;
343 }
344
345 if (empty($this->error)) {
346 // Loop on each ldap server
347 foreach ($this->server as $host) {
348 if ($connected) {
349 break;
350 }
351 if (empty($host)) {
352 continue;
353 }
354
355 if ($this->serverPing($host, $this->serverPort)) {
356 if ($ldapdebug) {
357 dol_syslog(get_class($this)."::connectBind serverPing true, we try ldap_connect to ".$host, LOG_DEBUG);
358 }
359 if (version_compare(PHP_VERSION, '8.3.0', '>=')) {
360 $uri = $host.':'.$this->serverPort;
361 $this->connection = ldap_connect($uri);
362 } else {
363 $this->connection = ldap_connect($host, $this->serverPort);
364 }
365 } else {
366 if (preg_match('/^ldaps/i', $host)) {
367 // With host = ldaps://server, the serverPing to ssl://server sometimes fails, even if the ldap_connect succeed, so
368 // we test this case and continue in such a case even if serverPing fails.
369 if ($ldapdebug) {
370 dol_syslog(get_class($this)."::connectBind serverPing false, we try ldap_connect to ".$host, LOG_DEBUG);
371 }
372 if (version_compare(PHP_VERSION, '8.3.0', '>=')) {
373 $uri = $host.':'.$this->serverPort;
374 $this->connection = ldap_connect($uri);
375 } else {
376 $this->connection = ldap_connect($host, $this->serverPort);
377 }
378 } else {
379 if ($ldapdebug) {
380 dol_syslog(get_class($this)."::connectBind serverPing false, no ldap_connect ".$host, LOG_DEBUG);
381 }
382 continue;
383 }
384 }
385
386 if (is_resource($this->connection) || is_object($this->connection)) {
387 if ($ldapdebug) {
388 dol_syslog(get_class($this)."::connectBind this->connection is ok", LOG_DEBUG);
389 }
390
391 // Upgrade connection to TLS, if requested by the configuration
392 if (getDolGlobalString('LDAP_SERVER_USE_TLS')) {
393 // For test/debug
394 //ldap_set_option($this->connection, LDAP_OPT_DEBUG_LEVEL, 7);
395 //ldap_set_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, 3);
396 //ldap_set_option($this->connection, LDAP_OPT_REFERRALS, 0);
397
398 $resulttls = ldap_start_tls($this->connection);
399 if (!$resulttls) {
400 dol_syslog(get_class($this)."::connectBind failed to start tls", LOG_WARNING);
401 $this->error = 'ldap_start_tls Failed to start TLS '.ldap_errno($this->connection).' '.ldap_error($this->connection);
402 $connected = 0;
403 $this->unbind();
404 }
405 }
406
407 // Execute the ldap_set_option here (after connect and before bind)
408 $this->setVersion();
409 $this->setSizeLimit();
410
411 if ($this->serverType == "activedirectory") {
412 $result = $this->setReferrals();
413 dol_syslog(get_class($this)."::connectBind try bindauth for activedirectory on ".$host." user=".$this->searchUser." password=".preg_replace('/./', '*', $this->searchPassword), LOG_DEBUG);
414 $this->result = $this->bindauth($this->searchUser, $this->searchPassword);
415 if ($this->result) {
416 $this->bind = $this->result;
417 $connected = 2;
418 $this->connectedServer = $host;
419 break;
420 } else {
421 $this->error = ldap_errno($this->connection).' '.ldap_error($this->connection);
422 }
423 } else {
424 // Try in auth mode
425 if ($this->searchUser && $this->searchPassword) {
426 dol_syslog(get_class($this)."::connectBind try bindauth on ".$host." user=".$this->searchUser." password=".preg_replace('/./', '*', $this->searchPassword), LOG_DEBUG);
427 $this->result = $this->bindauth($this->searchUser, $this->searchPassword);
428 if ($this->result) {
429 $this->bind = $this->result;
430 $connected = 2;
431 $this->connectedServer = $host;
432 break;
433 } else {
434 $this->error = ldap_errno($this->connection).' '.ldap_error($this->connection);
435 }
436 }
437 // Try in anonymous
438 if (!$this->bind) {
439 dol_syslog(get_class($this)."::connectBind try bind anonymously on ".$host, LOG_DEBUG);
440 $result = $this->bind();
441 if ($result) {
442 $this->bind = $this->result;
443 $connected = 1;
444 $this->connectedServer = $host;
445 break;
446 } else {
447 $this->error = ldap_errno($this->connection).' '.ldap_error($this->connection);
448 }
449 }
450 }
451 }
452
453 if (!$connected) {
454 $this->unbind();
455 }
456 } // End loop on each server
457 }
458
459 if ($connected) {
460 dol_syslog(get_class($this)."::connectBind ".$connected, LOG_DEBUG);
461 return $connected;
462 } else {
463 $this->error = 'Failed to connect to LDAP'.($this->error ? ': '.$this->error : '');
464 dol_syslog(get_class($this)."::connectBind ".$this->error, LOG_WARNING);
465 return -1;
466 }
467 }
468
477 public function close()
478 {
479 return $this->unbind();
480 }
481
488 public function bind()
489 {
490 if (!$this->result = @ldap_bind($this->connection)) {
491 $this->ldapErrorCode = ldap_errno($this->connection);
492 $this->ldapErrorText = ldap_error($this->connection);
493 $this->error = $this->ldapErrorCode." ".$this->ldapErrorText;
494 return false;
495 } else {
496 return true;
497 }
498 }
499
510 public function bindauth($bindDn, $pass)
511 {
512 if (!$this->result = @ldap_bind($this->connection, $bindDn, $pass)) {
513 $this->ldapErrorCode = ldap_errno($this->connection);
514 $this->ldapErrorText = ldap_error($this->connection);
515 $this->error = $this->ldapErrorCode." ".$this->ldapErrorText;
516 return false;
517 } else {
518 return true;
519 }
520 }
521
528 public function unbind()
529 {
530 $this->result = true;
531 if (version_compare(PHP_VERSION, '8.1.0', '>=')) {
532 if (is_object($this->connection)) {
533 try {
534 $this->result = ldap_unbind($this->connection);
535 } catch (Throwable $exception) {
536 $this->error = 'Failed to unbind LDAP connection: '.$exception;
537 $this->result = false;
538 dol_syslog(get_class($this).'::unbind - '.$this->error, LOG_WARNING);
539 }
540 }
541 } else {
542 if (is_resource($this->connection)) {
543 // @phan-suppress-next-line PhanTypeMismatchArgumentInternalReal
544 $this->result = @ldap_unbind($this->connection);
545 }
546 }
547 if ($this->result) {
548 return true;
549 } else {
550 return false;
551 }
552 }
553
554
560 public function getVersion()
561 {
562 @ldap_get_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, $version);
563 return $version;
564 }
565
572 public function setVersion()
573 {
574 return ldap_set_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, $this->ldapProtocolVersion);
575 }
576
582 public function setSizeLimit()
583 {
584 return ldap_set_option($this->connection, LDAP_OPT_SIZELIMIT, 0);
585 }
586
593 public function setReferrals()
594 {
595 return ldap_set_option($this->connection, LDAP_OPT_REFERRALS, 0);
596 }
597
598
608 public function add($dn, $info, $user)
609 {
610 dol_syslog(get_class($this)."::add dn=".$dn." info=".print_r($info, true));
611
612 // Check parameters
613 if (!$this->connection) {
614 $this->error = "NotConnected";
615 return -2;
616 }
617 if (!$this->bind) {
618 $this->error = "NotConnected";
619 return -3;
620 }
621
622 // Encode to LDAP page code
623 $dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
624 foreach ($info as $key => $val) {
625 if (!is_array($val)) {
626 $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
627 }
628 }
629
630 $this->dump($dn, $info);
631
632 //print_r($info);
633 $result = @ldap_add($this->connection, $dn, $info);
634
635 if ($result) {
636 dol_syslog(get_class($this)."::add successful", LOG_DEBUG);
637 return 1;
638 } else {
639 $this->ldapErrorCode = @ldap_errno($this->connection);
640 $this->ldapErrorText = @ldap_error($this->connection);
641 $this->error = $this->ldapErrorCode." ".$this->ldapErrorText;
642 dol_syslog(get_class($this)."::add failed: ".$this->error, LOG_ERR);
643 return -1;
644 }
645 }
646
656 public function modify($dn, $info, $user)
657 {
658 dol_syslog(get_class($this)."::modify dn=".$dn." info=".print_r($info, true));
659
660 // Check parameters
661 if (!$this->connection) {
662 $this->error = "NotConnected";
663 return -2;
664 }
665 if (!$this->bind) {
666 $this->error = "NotConnected";
667 return -3;
668 }
669
670 // Encode to LDAP page code
671 $dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
672 foreach ($info as $key => $val) {
673 if (!is_array($val)) {
674 $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
675 }
676 }
677
678 $this->dump($dn, $info);
679
680 //print_r($info);
681
682 // For better compatibility with Samba4 AD
683 if ($this->serverType == "activedirectory") {
684 unset($info['cn']); // To avoid error : Operation not allowed on RDN (Code 67)
685
686 // To avoid error : LDAP Error: 53 (Unwilling to perform)
687 if (isset($info['unicodePwd'])) {
688 $info['unicodePwd'] = mb_convert_encoding("\"".$info['unicodePwd']."\"", "UTF-16LE", "UTF-8");
689 }
690 }
691 $result = @ldap_mod_replace($this->connection, $dn, $info);
692
693 if ($result) {
694 dol_syslog(get_class($this)."::modify successful", LOG_DEBUG);
695 return 1;
696 } else {
697 $this->error = @ldap_error($this->connection);
698 dol_syslog(get_class($this)."::modify failed: ".$this->error, LOG_ERR);
699 return -1;
700 }
701 }
702
714 public function rename($dn, $newrdn, $newparent, $user, $deleteoldrdn = true)
715 {
716 dol_syslog(get_class($this)."::modify dn=".$dn." newrdn=".$newrdn." newparent=".$newparent." deleteoldrdn=".($deleteoldrdn ? 1 : 0));
717
718 // Check parameters
719 if (!$this->connection) {
720 $this->error = "NotConnected";
721 return -2;
722 }
723 if (!$this->bind) {
724 $this->error = "NotConnected";
725 return -3;
726 }
727
728 // Encode to LDAP page code
729 $dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
730 $newrdn = $this->convFromOutputCharset($newrdn, $this->ldapcharset);
731 $newparent = $this->convFromOutputCharset($newparent, $this->ldapcharset);
732
733 //print_r($info);
734 $result = @ldap_rename($this->connection, $dn, $newrdn, $newparent, $deleteoldrdn);
735
736 if ($result) {
737 dol_syslog(get_class($this)."::rename successful", LOG_DEBUG);
738 return 1;
739 } else {
740 $this->error = @ldap_error($this->connection);
741 dol_syslog(get_class($this)."::rename failed: ".$this->error, LOG_ERR);
742 return -1;
743 }
744 }
745
758 public function update($dn, $info, $user, $olddn, $newrdn = '', $newparent = '')
759 {
760 dol_syslog(get_class($this)."::update dn=".$dn." olddn=".$olddn);
761
762 // Check parameters
763 if (!$this->connection) {
764 $this->error = "NotConnected";
765 return -2;
766 }
767 if (!$this->bind) {
768 $this->error = "NotConnected";
769 return -3;
770 }
771
772 if (!$olddn || $olddn != $dn) {
773 if (!empty($olddn) && !empty($newrdn) && !empty($newparent) && $this->ldapProtocolVersion === '3') {
774 // This function currently only works with LDAPv3
775 $result = $this->rename($olddn, $newrdn, $newparent, $user, true);
776 $result = $this->modify($dn, $info, $user); // We force "modify" for avoid some fields not modify
777 } else {
778 // If change we make is rename the key of LDAP record, we create new one and if ok, we delete old one.
779 $result = $this->add($dn, $info, $user);
780 if ($result > 0 && $olddn && $olddn != $dn) {
781 $result = $this->delete($olddn); // If add fails, we do not try to delete old one
782 }
783 }
784 } else {
785 //$result = $this->delete($olddn);
786 $result = $this->add($dn, $info, $user); // If record has been deleted from LDAP, we recreate it. We ignore error if it already exists.
787 $result = $this->modify($dn, $info, $user); // We use add/modify instead of delete/add when olddn is received
788 }
789 if ($result <= 0) {
790 $this->error = ldap_error($this->connection).' (Code '.ldap_errno($this->connection).") ".$this->error;
791 dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
792 //print_r($info);
793 return -1;
794 } else {
795 dol_syslog(get_class($this)."::update done successfully");
796 return 1;
797 }
798 }
799
800
808 public function delete($dn)
809 {
810 dol_syslog(get_class($this)."::delete Delete LDAP entry dn=".$dn);
811
812 // Check parameters
813 if (!$this->connection) {
814 $this->error = "NotConnected";
815 return -2;
816 }
817 if (!$this->bind) {
818 $this->error = "NotConnected";
819 return -3;
820 }
821
822 // Encode to LDAP page code
823 $dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
824
825 $result = @ldap_delete($this->connection, $dn);
826
827 if ($result) {
828 return 1;
829 }
830 return -1;
831 }
832
841 public function dumpContent($dn, $info)
842 {
843 $content = '';
844
845 // Create file content
846 if (preg_match('/^ldap/', $this->server[0])) {
847 $target = "-H ".implode(',', $this->server);
848 } else {
849 $target = "-h ".implode(',', $this->server)." -p ".$this->serverPort;
850 }
851 $content .= "# ldapadd $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
852 $content .= "# ldapmodify $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
853 $content .= "# ldapdelete $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
854 if (in_array('localhost', $this->server)) {
855 $content .= "# If commands fails to connect, try without -h and -p\n";
856 }
857 $content .= "dn: ".$dn."\n";
858 foreach ($info as $key => $value) {
859 if (!is_array($value)) {
860 $content .= "$key: $value\n";
861 } else {
862 foreach ($value as $valuevalue) {
863 $content .= "$key: $valuevalue\n";
864 }
865 }
866 }
867 return $content;
868 }
869
877 public function dump($dn, $info)
878 {
879 global $conf;
880 $ldapDirTemp = $conf->ldap->dir_temp;
881 // Create content
882 $content = $this->dumpContent($dn, $info);
883
884 //Create directory & file
885 $result = dol_mkdir($ldapDirTemp);
886 if ($result != 0) {
887 $outputfile = $ldapDirTemp.'/ldapinput.in';
888 $fp = fopen($outputfile, "w");
889 if ($fp) {
890 fwrite($fp, $content);
891 fclose($fp);
892 dolChmod($outputfile);
893 return 1;
894 } else {
895 return -1;
896 }
897 } else {
898 return -1;
899 }
900 }
901
910 public function serverPing($host, $port = 389, $timeout = 1)
911 {
912 $regs = array();
913 if (preg_match('/^ldaps:\/\/([^\/]+)\/?$/', $host, $regs)) {
914 // Replace ldaps:// by ssl://
915 $host = 'ssl://'.$regs[1];
916 } elseif (preg_match('/^ldap:\/\/([^\/]+)\/?$/', $host, $regs)) {
917 // Remove ldap://
918 $host = $regs[1];
919 }
920
921 //var_dump($newhostforstream); var_dump($host); var_dump($port);
922 //$host = 'ssl://ldap.test.local:636';
923 //$port = 636;
924
925 $errno = $errstr = 0;
926 /*
927 if ($methodtochecktcpconnect == 'socket') {
928 Try to use socket_create() method.
929 Method that use stream_context_create() works only on registered listed in stream stream_get_wrappers(): http, https, ftp, ...
930 }
931 */
932
933 // Use the method fsockopen to test tcp connect. No way to ignore ssl certificate errors with this method !
934 $op = @fsockopen($host, $port, $errno, $errstr, $timeout);
935
936 //var_dump($op);
937 if (!$op) {
938 return false; //DC is N/A
939 } else {
940 fclose($op); //explicitly close open socket connection
941 return true; //DC is up & running, we can safely connect with ldap_connect
942 }
943 }
944
945
946 // Attribute methods -----------------------------------------------------
947
957 public function addAttribute($dn, $info, $user)
958 {
959 dol_syslog(get_class($this)."::addAttribute dn=".$dn." info=".implode(',', $info));
960
961 // Check parameters
962 if (!$this->connection) {
963 $this->error = "NotConnected";
964 return -2;
965 }
966 if (!$this->bind) {
967 $this->error = "NotConnected";
968 return -3;
969 }
970
971 // Encode to LDAP page code
972 $dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
973 foreach ($info as $key => $val) {
974 if (!is_array($val)) {
975 $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
976 }
977 }
978
979 $this->dump($dn, $info);
980
981 //print_r($info);
982 $result = @ldap_mod_add($this->connection, $dn, $info);
983
984 if ($result) {
985 dol_syslog(get_class($this)."::add_attribute successful", LOG_DEBUG);
986 return 1;
987 } else {
988 $this->error = @ldap_error($this->connection);
989 dol_syslog(get_class($this)."::add_attribute failed: ".$this->error, LOG_ERR);
990 return -1;
991 }
992 }
993
1003 public function updateAttribute($dn, $info, $user)
1004 {
1005 dol_syslog(get_class($this)."::updateAttribute dn=".$dn." info=".implode(',', $info));
1006
1007 // Check parameters
1008 if (!$this->connection) {
1009 $this->error = "NotConnected";
1010 return -2;
1011 }
1012 if (!$this->bind) {
1013 $this->error = "NotConnected";
1014 return -3;
1015 }
1016
1017 // Encode to LDAP page code
1018 $dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
1019 foreach ($info as $key => $val) {
1020 if (!is_array($val)) {
1021 $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
1022 }
1023 }
1024
1025 $this->dump($dn, $info);
1026
1027 //print_r($info);
1028 $result = @ldap_mod_replace($this->connection, $dn, $info);
1029
1030 if ($result) {
1031 dol_syslog(get_class($this)."::updateAttribute successful", LOG_DEBUG);
1032 return 1;
1033 } else {
1034 $this->error = @ldap_error($this->connection);
1035 dol_syslog(get_class($this)."::updateAttribute failed: ".$this->error, LOG_ERR);
1036 return -1;
1037 }
1038 }
1039
1049 public function deleteAttribute($dn, $info, $user)
1050 {
1051 dol_syslog(get_class($this)."::deleteAttribute dn=".$dn." info=".implode(',', $info));
1052
1053 // Check parameters
1054 if (!$this->connection) {
1055 $this->error = "NotConnected";
1056 return -2;
1057 }
1058 if (!$this->bind) {
1059 $this->error = "NotConnected";
1060 return -3;
1061 }
1062
1063 // Encode to LDAP page code
1064 $dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
1065 foreach ($info as $key => $val) {
1066 if (!is_array($val)) {
1067 $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
1068 }
1069 }
1070
1071 $this->dump($dn, $info);
1072
1073 //print_r($info);
1074 $result = @ldap_mod_del($this->connection, $dn, $info);
1075
1076 if ($result) {
1077 dol_syslog(get_class($this)."::deleteAttribute successful", LOG_DEBUG);
1078 return 1;
1079 } else {
1080 $this->error = @ldap_error($this->connection);
1081 dol_syslog(get_class($this)."::deleteAttribute failed: ".$this->error, LOG_ERR);
1082 return -1;
1083 }
1084 }
1085
1093 public function getAttribute($dn, $filter)
1094 {
1095 // Check parameters
1096 if (!$this->connection) {
1097 $this->error = "NotConnected";
1098 return -2;
1099 }
1100 if (!$this->bind) {
1101 $this->error = "NotConnected";
1102 return -3;
1103 }
1104
1105 $search = @ldap_search($this->connection, $dn, $filter);
1106
1107 // Only one entry should ever be returned
1108 $entry = @ldap_first_entry($this->connection, $search);
1109
1110 if (!$entry) {
1111 $this->ldapErrorCode = -1;
1112 $this->ldapErrorText = "Couldn't find entry";
1113 return 0; // Couldn't find entry...
1114 }
1115
1116 // Get values
1117 if (!($values = ldap_get_attributes($this->connection, $entry))) {
1118 $this->ldapErrorCode = ldap_errno($this->connection);
1119 $this->ldapErrorText = ldap_error($this->connection);
1120 return 0; // No matching attributes
1121 }
1122
1123 // Return an array containing the attributes.
1124 return $values;
1125 }
1126
1134 public function getAttributeValues($filterrecord, $attribute)
1135 {
1136 $attributes = array();
1137 $attributes[0] = $attribute;
1138
1139 // We need to search for this user in order to get their entry.
1140 $this->result = @ldap_search($this->connection, $this->people, $filterrecord, $attributes);
1141
1142 // Pourquoi cette ligne ?
1143 //$info = ldap_get_entries($this->connection, $this->result);
1144
1145 // Only one entry should ever be returned (no user will have the same uid)
1146 $entry = ldap_first_entry($this->connection, $this->result);
1147
1148 if (!$entry) {
1149 $this->ldapErrorCode = -1;
1150 $this->ldapErrorText = "Couldn't find user";
1151 return false; // Couldn't find the user...
1152 }
1153
1154 // Get values
1155 if (!$values = @ldap_get_values_len($this->connection, $entry, $attribute)) {
1156 $this->ldapErrorCode = ldap_errno($this->connection);
1157 $this->ldapErrorText = ldap_error($this->connection);
1158 return false; // No matching attributes
1159 }
1160
1161 // Return an array containing the attributes.
1162 return $values;
1163 }
1164
1177 public function getRecords($search, $userDn, $useridentifier, $attributeArray, $activefilter = 0, $attributeAsArray = array())
1178 {
1179 $fulllist = array();
1180
1181 dol_syslog(get_class($this)."::getRecords search=".$search." userDn=".$userDn." useridentifier=".$useridentifier." attributeArray=array(".implode(',', $attributeArray).") activefilter=".$activefilter);
1182
1183 // if the directory is AD, then bind first with the search user first
1184 if ($this->serverType == "activedirectory") {
1185 $this->bindauth($this->searchUser, $this->searchPassword);
1186 dol_syslog(get_class($this)."::bindauth serverType=activedirectory searchUser=".$this->searchUser);
1187 }
1188
1189 // Define filter
1190 if (!empty($activefilter)) { // Use a predefined trusted filter (defined into setup by admin).
1191 if (((string) $activefilter == '1' || (string) $activefilter == 'user') && $this->filter) {
1192 $filter = '('.$this->filter.')';
1193 } elseif (((string) $activefilter == 'group') && $this->filtergroup) {
1194 $filter = '('.$this->filtergroup.')';
1195 } elseif (((string) $activefilter == 'member') && $this->filter) {
1196 $filter = '('.$this->filtermember.')';
1197 } else {
1198 // If this->filter/this->filtergroup is empty, make filter on * (all)
1199 $filter = '('.ldap_escape($useridentifier, '', LDAP_ESCAPE_FILTER).'=*)';
1200 }
1201 } else { // Use a filter forged using the $search value
1202 $filter = '('.ldap_escape($useridentifier, '', LDAP_ESCAPE_FILTER).'='.ldap_escape($search, '', LDAP_ESCAPE_FILTER).')';
1203 }
1204
1205 if (is_array($attributeArray)) {
1206 // Return list with required fields
1207 $attributeArray = array_values($attributeArray); // This is to force to have index reordered from 0 (not make ldap_search fails)
1208 dol_syslog(get_class($this)."::getRecords connection=".$this->connectedServer.":".$this->serverPort." userDn=".$userDn." filter=".$filter." attributeArray=(".implode(',', $attributeArray).")");
1209 //var_dump($attributeArray);
1210 $this->result = @ldap_search($this->connection, $userDn, $filter, $attributeArray);
1211 } else {
1212 // Return list with fields selected by default
1213 dol_syslog(get_class($this)."::getRecords connection=".$this->connectedServer.":".$this->serverPort." userDn=".$userDn." filter=".$filter);
1214 $this->result = @ldap_search($this->connection, $userDn, $filter);
1215 }
1216 if (!$this->result) {
1217 $this->error = 'LDAP search failed: '.ldap_errno($this->connection)." ".ldap_error($this->connection);
1218 return -1;
1219 }
1220
1221 $info = @ldap_get_entries($this->connection, $this->result);
1222
1223 // Warning: Dans info, les noms d'attributs sont en minuscule meme si passe
1224 // a ldap_search en majuscule !!!
1225 //print_r($info);
1226
1227 for ($i = 0; $i < $info["count"]; $i++) {
1228 $recordid = $this->convToOutputCharset($info[$i][strtolower($useridentifier)][0], $this->ldapcharset);
1229 if ($recordid) {
1230 //print "Found record with key $useridentifier=".$recordid."<br>\n";
1231 $fulllist[$recordid][$useridentifier] = $recordid;
1232
1233 // Add to the array for each attribute in my list
1234 $num = count($attributeArray);
1235 for ($j = 0; $j < $num; $j++) {
1236 $keyattributelower = strtolower($attributeArray[$j]);
1237 //print " Param ".$attributeArray[$j]."=".$info[$i][$keyattributelower][0]."<br>\n";
1238
1239 //permet de recuperer le SID avec Active Directory
1240 if ($this->serverType == "activedirectory" && $keyattributelower == "objectsid") {
1241 $objectsid = $this->getObjectSid($recordid);
1242 $fulllist[$recordid][$attributeArray[$j]] = $objectsid;
1243 } else {
1244 if (in_array($attributeArray[$j], $attributeAsArray) && is_array($info[$i][$keyattributelower])) {
1245 $valueTab = array();
1246 foreach ($info[$i][$keyattributelower] as $key => $value) {
1247 $valueTab[$key] = $this->convToOutputCharset($value, $this->ldapcharset);
1248 }
1249 $fulllist[$recordid][$attributeArray[$j]] = $valueTab;
1250 } else {
1251 $fulllist[$recordid][$attributeArray[$j]] = $this->convToOutputCharset($info[$i][$keyattributelower][0], $this->ldapcharset);
1252 }
1253 }
1254 }
1255 }
1256 }
1257
1258 asort($fulllist);
1259 return $fulllist;
1260 }
1261
1269 public function littleEndian($hex)
1270 {
1271 $result = '';
1272 for ($x = dol_strlen($hex) - 2; $x >= 0; $x = $x - 2) {
1273 $result .= substr($hex, $x, 2);
1274 }
1275 return $result;
1276 }
1277
1278
1286 public function getObjectSid($ldapUser)
1287 {
1288 $criteria = '('.$this->getUserIdentifier().'='.$ldapUser.')';
1289 $justthese = array("objectsid");
1290
1291 // if the directory is AD, then bind first with the search user first
1292 if ($this->serverType == "activedirectory") {
1293 $this->bindauth($this->searchUser, $this->searchPassword);
1294 }
1295
1296 $i = 0;
1297 $searchDN = $this->people;
1298
1299 while ($i <= 2) {
1300 $ldapSearchResult = @ldap_search($this->connection, $searchDN, $criteria, $justthese);
1301
1302 if (!$ldapSearchResult) {
1303 $this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1304 return -1;
1305 }
1306
1307 $entry = ldap_first_entry($this->connection, $ldapSearchResult);
1308
1309 if (!$entry) {
1310 // Si pas de resultat on cherche dans le domaine
1311 $searchDN = $this->domain;
1312 $i++;
1313 } else {
1314 $i++;
1315 $i++;
1316 }
1317 }
1318
1319 if ($entry) {
1320 $ldapBinary = ldap_get_values_len($this->connection, $entry, "objectsid");
1321 $SIDText = $this->binSIDtoText($ldapBinary[0]);
1322 return $SIDText;
1323 } else {
1324 $this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1325 return -1;
1326 }
1327 }
1328
1336 public function binSIDtoText($binsid)
1337 {
1338 $hex_sid = bin2hex($binsid);
1339 $rev = hexdec(substr($hex_sid, 0, 2)); // Get revision-part of SID
1340 $subcount = hexdec(substr($hex_sid, 2, 2)); // Get count of sub-auth entries
1341 $auth = hexdec(substr($hex_sid, 4, 12)); // SECURITY_NT_AUTHORITY
1342 $result = "$rev-$auth";
1343 for ($x = 0; $x < $subcount; $x++) {
1344 $result .= "-".hexdec($this->littleEndian(substr($hex_sid, 16 + ($x * 8), 8))); // get all SECURITY_NT_AUTHORITY
1345 }
1346 return $result;
1347 }
1348
1349
1363 public function search($checkDn, $filter)
1364 {
1365 dol_syslog(get_class($this)."::search checkDn=".$checkDn." filter=".$filter);
1366
1367 $checkDn = $this->convFromOutputCharset($checkDn, $this->ldapcharset);
1368 $filter = $this->convFromOutputCharset($filter, $this->ldapcharset);
1369
1370 // if the directory is AD, then bind first with the search user first
1371 if ($this->serverType == "activedirectory") {
1372 $this->bindauth($this->searchUser, $this->searchPassword);
1373 }
1374
1375 $this->result = @ldap_search($this->connection, $checkDn, $filter);
1376
1377 $result = @ldap_get_entries($this->connection, $this->result);
1378 if (!$result) {
1379 $this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1380 return -1;
1381 } else {
1382 ldap_free_result($this->result);
1383 return $result;
1384 }
1385 }
1386
1387
1396 public function fetch($user, $filter)
1397 {
1398 // Perform the search and get the entry handles
1399
1400 // if the directory is AD, then bind first with the search user first
1401 if ($this->serverType == "activedirectory") {
1402 $this->bindauth($this->searchUser, $this->searchPassword);
1403 }
1404
1405 $searchDN = $this->people; // TODO Why searching in people then domain ?
1406
1407 $result = '';
1408 $i = 0;
1409 while ($i <= 2) {
1410 dol_syslog(get_class($this)."::fetch search with searchDN=".$searchDN." filter=".$filter);
1411 $this->result = @ldap_search($this->connection, $searchDN, $filter);
1412 if ($this->result) {
1413 $result = @ldap_get_entries($this->connection, $this->result);
1414 if ($result['count'] > 0) {
1415 dol_syslog('Ldap::fetch search found '.$result['count'].' records');
1416 } else {
1417 dol_syslog('Ldap::fetch search returns but found no records');
1418 }
1419 //var_dump($result);exit;
1420 } else {
1421 $this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1422 dol_syslog(get_class($this)."::fetch search fails");
1423 return -1;
1424 }
1425
1426 if (!$result) {
1427 // Si pas de resultat on cherche dans le domaine
1428 $searchDN = $this->domain;
1429 $i++;
1430 } else {
1431 break;
1432 }
1433 }
1434
1435 if (!$result) {
1436 $this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1437 return -1;
1438 } else {
1439 $this->name = $this->convToOutputCharset($result[0][$this->attr_name][0], $this->ldapcharset);
1440 $this->firstname = $this->convToOutputCharset($result[0][$this->attr_firstname][0], $this->ldapcharset);
1441 $this->login = $this->convToOutputCharset($result[0][$this->attr_login][0], $this->ldapcharset);
1442 $this->phone = $this->convToOutputCharset($result[0][$this->attr_phone][0], $this->ldapcharset);
1443 $this->fax = $this->convToOutputCharset($result[0][$this->attr_fax][0], $this->ldapcharset);
1444 $this->mail = $this->convToOutputCharset($result[0][$this->attr_mail][0], $this->ldapcharset);
1445 $this->mobile = $this->convToOutputCharset($result[0][$this->attr_mobile][0], $this->ldapcharset);
1446
1447 $this->uacf = $this->parseUACF($this->convToOutputCharset($result[0]["useraccountcontrol"][0], $this->ldapcharset));
1448 if (isset($result[0]["pwdlastset"][0])) { // If expiration on password exists
1449 $this->pwdlastset = ($result[0]["pwdlastset"][0] != 0) ? $this->convertTime($this->convToOutputCharset($result[0]["pwdlastset"][0], $this->ldapcharset)) : 0;
1450 } else {
1451 $this->pwdlastset = -1;
1452 }
1453 if (!$this->name && !$this->login) {
1454 $this->pwdlastset = -1;
1455 }
1456 $this->badpwdtime = $this->convertTime($this->convToOutputCharset($result[0]["badpasswordtime"][0], $this->ldapcharset));
1457
1458 // FQDN domain
1459 $domain = str_replace('dc=', '', $this->domain);
1460 $domain = str_replace(',', '.', $domain);
1461 $this->domainFQDN = $domain;
1462
1463 // Set ldapUserDn (each user can have a different dn)
1464 //var_dump($result[0]);exit;
1465 $this->ldapUserDN = $result[0]['dn'];
1466
1467 ldap_free_result($this->result);
1468 return 1;
1469 }
1470 }
1471
1472
1473 // helper methods
1474
1480 public function getUserIdentifier()
1481 {
1482 if ($this->serverType == "activedirectory") {
1483 return $this->attr_sambalogin;
1484 } else {
1485 return $this->attr_login;
1486 }
1487 }
1488
1495 public function parseUACF($uacf)
1496 {
1497 //All flags array
1498 $flags = array(
1499 "TRUSTED_TO_AUTH_FOR_DELEGATION" => 16777216,
1500 "PASSWORD_EXPIRED" => 8388608,
1501 "DONT_REQ_PREAUTH" => 4194304,
1502 "USE_DES_KEY_ONLY" => 2097152,
1503 "NOT_DELEGATED" => 1048576,
1504 "TRUSTED_FOR_DELEGATION" => 524288,
1505 "SMARTCARD_REQUIRED" => 262144,
1506 "MNS_LOGON_ACCOUNT" => 131072,
1507 "DONT_EXPIRE_PASSWORD" => 65536,
1508 "SERVER_TRUST_ACCOUNT" => 8192,
1509 "WORKSTATION_TRUST_ACCOUNT" => 4096,
1510 "INTERDOMAIN_TRUST_ACCOUNT" => 2048,
1511 "NORMAL_ACCOUNT" => 512,
1512 "TEMP_DUPLICATE_ACCOUNT" => 256,
1513 "ENCRYPTED_TEXT_PWD_ALLOWED" => 128,
1514 "PASSWD_CANT_CHANGE" => 64,
1515 "PASSWD_NOTREQD" => 32,
1516 "LOCKOUT" => 16,
1517 "HOMEDIR_REQUIRED" => 8,
1518 "ACCOUNTDISABLE" => 2,
1519 "SCRIPT" => 1
1520 );
1521
1522 //Parse flags to text
1523 $retval = array();
1524 //while (list($flag, $val) = each($flags)) {
1525 foreach ($flags as $flag => $val) {
1526 if ($uacf >= $val) {
1527 $uacf -= $val;
1528 $retval[$val] = $flag;
1529 }
1530 }
1531
1532 //Return human friendly flags
1533 return $retval;
1534 }
1535
1542 public function parseSAT($samtype)
1543 {
1544 $stypes = array(
1545 805306368 => "NORMAL_ACCOUNT",
1546 805306369 => "WORKSTATION_TRUST",
1547 805306370 => "INTERDOMAIN_TRUST",
1548 268435456 => "SECURITY_GLOBAL_GROUP",
1549 268435457 => "DISTRIBUTION_GROUP",
1550 536870912 => "SECURITY_LOCAL_GROUP",
1551 536870913 => "DISTRIBUTION_LOCAL_GROUP"
1552 );
1553
1554 $retval = "";
1555 foreach ($stypes as $sat => $val) {
1556 if ($samtype == $sat) {
1557 $retval = $val;
1558 break;
1559 }
1560 }
1561 if (empty($retval)) {
1562 $retval = "UNKNOWN_TYPE_".$samtype;
1563 }
1564
1565 return $retval;
1566 }
1567
1574 public function convertTime($value)
1575 {
1576 $dateLargeInt = $value; // nano secondes depuis 1601 !!!!
1577 $secsAfterADEpoch = $dateLargeInt / (10000000); // secondes depuis le 1 jan 1601
1578 $ADToUnixConvertor = ((1970 - 1601) * 365.242190) * 86400; // UNIX start date - AD start date * jours * secondes
1579 $unixTimeStamp = intval($secsAfterADEpoch - $ADToUnixConvertor); // Unix time stamp
1580 return $unixTimeStamp;
1581 }
1582
1583
1591 private function convToOutputCharset($str, $pagecodefrom = 'UTF-8')
1592 {
1593 global $conf;
1594 if ($pagecodefrom == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8') {
1595 $str = mb_convert_encoding($str, 'UTF-8', 'ISO-8859-1');
1596 }
1597 if ($pagecodefrom == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1') {
1598 $str = mb_convert_encoding($str, 'ISO-8859-1');
1599 }
1600 return $str;
1601 }
1602
1610 public function convFromOutputCharset($str, $pagecodeto = 'UTF-8')
1611 {
1612 global $conf;
1613 if ($pagecodeto == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8') {
1614 $str = mb_convert_encoding($str, 'ISO-8859-1');
1615 }
1616 if ($pagecodeto == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1') {
1617 $str = mb_convert_encoding($str, 'UTF-8', 'ISO-8859-1');
1618 }
1619 return $str;
1620 }
1621
1622
1629 public function getNextGroupGid($keygroup = 'LDAP_KEY_GROUPS')
1630 {
1631
1632 if (empty($keygroup)) {
1633 $keygroup = 'LDAP_KEY_GROUPS';
1634 }
1635
1636 $search = '(' . getDolGlobalString($keygroup).'=*)';
1637 $result = $this->search($this->groups, $search);
1638 if ($result) {
1639 $c = $result['count'];
1640 $gids = array();
1641 for ($i = 0; $i < $c; $i++) {
1642 $gids[] = $result[$i]['gidnumber'][0];
1643 }
1644 rsort($gids);
1645
1646 return $gids[0] + 1;
1647 }
1648
1649 return 0;
1650 }
1651}
Class to manage LDAP features.
add($dn, $info, $user)
Add an LDAP entry LDAP object connect and bind must have been done.
convertTime($value)
Converts ActiveDirectory time to Unix timestamp.
modify($dn, $info, $user)
Modify an LDAP entry LDAP object connect and bind must have been done.
deleteAttribute($dn, $info, $user)
Delete an LDAP attribute in entry LDAP object connect and bind must have been done.
setVersion()
Set LDAP protocol version.
convToOutputCharset($str, $pagecodefrom='UTF-8')
Convert a string into output/memory charset.
littleEndian($hex)
Converts a little-endian hex-number to one, that 'hexdec' can convert Required by Active Directory.
fetch($user, $filter)
Load all attributes of an LDAP user.
update($dn, $info, $user, $olddn, $newrdn='', $newparent='')
Modify an LDAP entry (to use if dn != olddn) LDAP object connect and bind must have been done.
getObjectSid($ldapUser)
Gets LDAP user SID.
updateAttribute($dn, $info, $user)
Update an LDAP attribute in entry LDAP object connect and bind must have been done.
getUserIdentifier()
Returns the correct user identifier to use, based on the LDAP server type.
getAttribute($dn, $filter)
Returns an array containing attributes and values for first record.
close()
Simply closes the connection set up earlier.
parseSAT($samtype)
SamAccountType value to text.
rename($dn, $newrdn, $newparent, $user, $deleteoldrdn=true)
Rename an LDAP entry LDAP object connect and bind must have been done.
getNextGroupGid($keygroup='LDAP_KEY_GROUPS')
Return available value of group GID.
setSizeLimit()
Set LDAP size limit.
binSIDtoText($binsid)
Returns the textual SID Required by Active Directory.
connectBind()
Connect and bind Use this->server, this->serverPort, this->ldapProtocolVersion, this->serverType,...
setReferrals()
Set LDAP referrals.
search($checkDn, $filter)
Search method with filter this->connection must be defined.
getRecords($search, $userDn, $useridentifier, $attributeArray, $activefilter=0, $attributeAsArray=array())
Returns an array containing a details or list of LDAP record(s).
getVersion()
Verify LDAP server version.
dumpContent($dn, $info)
Build an LDAP message.
getAttributeValues($filterrecord, $attribute)
Returns an array containing values for an attribute and for first record matching filterrecord.
parseUACF($uacf)
UserAccountControl Flags to more human understandable form...
__construct()
Constructor.
convFromOutputCharset($str, $pagecodeto='UTF-8')
Convert a string from output/memory charset.
serverPing($host, $port=389, $timeout=1)
Ping a server before ldap_connect for avoid waiting.
bind()
Anonymously binds to the connection.
unbind()
Unbind of LDAP server (close connection).
bindauth($bindDn, $pass)
Binds as an authenticated user, which usually allows for write access.
dump($dn, $info)
Dump an LDAP message to ldapinput.in file.
addAttribute($dn, $info, $user)
Add an LDAP attribute in entry LDAP object connect and bind must have been done.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
dolChmod($filepath, $newmask='')
Change mod of a file.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:142