dolibarr 21.0.0-alpha
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"));
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
1095 public function getAttribute($dn, $filter)
1096 {
1097 // Check parameters
1098 if (!$this->connection) {
1099 $this->error = "NotConnected";
1100 return -2;
1101 }
1102 if (!$this->bind) {
1103 $this->error = "NotConnected";
1104 return -3;
1105 }
1106
1107 $search = @ldap_search($this->connection, $dn, $filter);
1108
1109 // Only one entry should ever be returned
1110 $entry = @ldap_first_entry($this->connection, $search);
1111
1112 if (!$entry) {
1113 $this->ldapErrorCode = -1;
1114 $this->ldapErrorText = "Couldn't find entry";
1115 return 0; // Couldn't find entry...
1116 }
1117
1118 // Get values
1119 if (!($values = ldap_get_attributes($this->connection, $entry))) {
1120 $this->ldapErrorCode = ldap_errno($this->connection);
1121 $this->ldapErrorText = ldap_error($this->connection);
1122 return 0; // No matching attributes
1123 }
1124
1125 // Return an array containing the attributes.
1126 return $values;
1127 }
1128
1136 public function getAttributeValues($filterrecord, $attribute)
1137 {
1138 $attributes = array();
1139 $attributes[0] = $attribute;
1140
1141 // We need to search for this user in order to get their entry.
1142 $this->result = @ldap_search($this->connection, $this->people, $filterrecord, $attributes);
1143
1144 // Pourquoi cette ligne ?
1145 //$info = ldap_get_entries($this->connection, $this->result);
1146
1147 // Only one entry should ever be returned (no user will have the same uid)
1148 $entry = ldap_first_entry($this->connection, $this->result);
1149
1150 if (!$entry) {
1151 $this->ldapErrorCode = -1;
1152 $this->ldapErrorText = "Couldn't find user";
1153 return false; // Couldn't find the user...
1154 }
1155
1156 // Get values
1157 if (!$values = @ldap_get_values_len($this->connection, $entry, $attribute)) {
1158 $this->ldapErrorCode = ldap_errno($this->connection);
1159 $this->ldapErrorText = ldap_error($this->connection);
1160 return false; // No matching attributes
1161 }
1162
1163 // Return an array containing the attributes.
1164 return $values;
1165 }
1166
1179 public function getRecords($search, $userDn, $useridentifier, $attributeArray, $activefilter = 0, $attributeAsArray = array())
1180 {
1181 $fulllist = array();
1182
1183 dol_syslog(get_class($this)."::getRecords search=".$search." userDn=".$userDn." useridentifier=".$useridentifier." attributeArray=array(".implode(',', $attributeArray).") activefilter=".$activefilter);
1184
1185 // if the directory is AD, then bind first with the search user first
1186 if ($this->serverType == "activedirectory") {
1187 $this->bindauth($this->searchUser, $this->searchPassword);
1188 dol_syslog(get_class($this)."::bindauth serverType=activedirectory searchUser=".$this->searchUser);
1189 }
1190
1191 // Define filter
1192 if (!empty($activefilter)) { // Use a predefined trusted filter (defined into setup by admin).
1193 if (((string) $activefilter == '1' || (string) $activefilter == 'user') && $this->filter) {
1194 $filter = '('.$this->filter.')';
1195 } elseif (((string) $activefilter == 'group') && $this->filtergroup) {
1196 $filter = '('.$this->filtergroup.')';
1197 } elseif (((string) $activefilter == 'member') && $this->filter) {
1198 $filter = '('.$this->filtermember.')';
1199 } else {
1200 // If this->filter/this->filtergroup is empty, make filter on * (all)
1201 $filter = '('.ldap_escape($useridentifier, '', LDAP_ESCAPE_FILTER).'=*)';
1202 }
1203 } else { // Use a filter forged using the $search value
1204 $filter = '('.ldap_escape($useridentifier, '', LDAP_ESCAPE_FILTER).'='.ldap_escape($search, '', LDAP_ESCAPE_FILTER).')';
1205 }
1206
1207 if (is_array($attributeArray)) {
1208 // Return list with required fields
1209 $attributeArray = array_values($attributeArray); // This is to force to have index reordered from 0 (not make ldap_search fails)
1210 dol_syslog(get_class($this)."::getRecords connection=".$this->connectedServer.":".$this->serverPort." userDn=".$userDn." filter=".$filter." attributeArray=(".implode(',', $attributeArray).")");
1211 //var_dump($attributeArray);
1212 $this->result = @ldap_search($this->connection, $userDn, $filter, $attributeArray);
1213 } else {
1214 // Return list with fields selected by default
1215 dol_syslog(get_class($this)."::getRecords connection=".$this->connectedServer.":".$this->serverPort." userDn=".$userDn." filter=".$filter);
1216 $this->result = @ldap_search($this->connection, $userDn, $filter);
1217 }
1218 if (!$this->result) {
1219 $this->error = 'LDAP search failed: '.ldap_errno($this->connection)." ".ldap_error($this->connection);
1220 return -1;
1221 }
1222
1223 $info = @ldap_get_entries($this->connection, $this->result);
1224
1225 // Warning: Dans info, les noms d'attributs sont en minuscule meme si passe
1226 // a ldap_search en majuscule !!!
1227 //print_r($info);
1228
1229 for ($i = 0; $i < $info["count"]; $i++) {
1230 $recordid = $this->convToOutputCharset($info[$i][strtolower($useridentifier)][0], $this->ldapcharset);
1231 if ($recordid) {
1232 //print "Found record with key $useridentifier=".$recordid."<br>\n";
1233 $fulllist[$recordid][$useridentifier] = $recordid;
1234
1235 // Add to the array for each attribute in my list
1236 $num = count($attributeArray);
1237 for ($j = 0; $j < $num; $j++) {
1238 $keyattributelower = strtolower($attributeArray[$j]);
1239 //print " Param ".$attributeArray[$j]."=".$info[$i][$keyattributelower][0]."<br>\n";
1240
1241 //permet de recuperer le SID avec Active Directory
1242 if ($this->serverType == "activedirectory" && $keyattributelower == "objectsid") {
1243 $objectsid = $this->getObjectSid($recordid);
1244 $fulllist[$recordid][$attributeArray[$j]] = $objectsid;
1245 } else {
1246 if (in_array($attributeArray[$j], $attributeAsArray) && is_array($info[$i][$keyattributelower])) {
1247 $valueTab = array();
1248 foreach ($info[$i][$keyattributelower] as $key => $value) {
1249 $valueTab[$key] = $this->convToOutputCharset($value, $this->ldapcharset);
1250 }
1251 $fulllist[$recordid][$attributeArray[$j]] = $valueTab;
1252 } else {
1253 $fulllist[$recordid][$attributeArray[$j]] = $this->convToOutputCharset($info[$i][$keyattributelower][0], $this->ldapcharset);
1254 }
1255 }
1256 }
1257 }
1258 }
1259
1260 asort($fulllist);
1261 return $fulllist;
1262 }
1263
1271 public function littleEndian($hex)
1272 {
1273 $result = '';
1274 for ($x = dol_strlen($hex) - 2; $x >= 0; $x -= 2) {
1275 $result .= substr($hex, $x, 2);
1276 }
1277 return $result;
1278 }
1279
1280
1288 public function getObjectSid($ldapUser)
1289 {
1290 $criteria = '('.$this->getUserIdentifier().'='.$ldapUser.')';
1291 $justthese = array("objectsid");
1292
1293 // if the directory is AD, then bind first with the search user first
1294 if ($this->serverType == "activedirectory") {
1295 $this->bindauth($this->searchUser, $this->searchPassword);
1296 }
1297
1298 $i = 0;
1299 $entry = null;
1300 $searchDN = $this->people;
1301
1302 while ($i <= 2) {
1303 $ldapSearchResult = @ldap_search($this->connection, $searchDN, $criteria, $justthese);
1304
1305 if (!$ldapSearchResult) {
1306 $this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1307 return -1;
1308 }
1309
1310 $entry = ldap_first_entry($this->connection, $ldapSearchResult);
1311
1312 if (!$entry) {
1313 // Si pas de resultat on cherche dans le domaine
1314 $searchDN = $this->domain;
1315 $i++;
1316 } else {
1317 $i++;
1318 $i++;
1319 }
1320 }
1321
1322 if ($entry) {
1323 $ldapBinary = ldap_get_values_len($this->connection, $entry, "objectsid");
1324 $SIDText = $this->binSIDtoText($ldapBinary[0]);
1325 return $SIDText;
1326 } else {
1327 $this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1328 return -1;
1329 }
1330 }
1331
1339 public function binSIDtoText($binsid)
1340 {
1341 $hex_sid = bin2hex($binsid);
1342 $rev = hexdec(substr($hex_sid, 0, 2)); // Get revision-part of SID
1343 $subcount = hexdec(substr($hex_sid, 2, 2)); // Get count of sub-auth entries
1344 $auth = hexdec(substr($hex_sid, 4, 12)); // SECURITY_NT_AUTHORITY
1345 $result = "$rev-$auth";
1346 for ($x = 0; $x < $subcount; $x++) {
1347 $result .= "-".hexdec($this->littleEndian(substr($hex_sid, 16 + ($x * 8), 8))); // get all SECURITY_NT_AUTHORITY
1348 }
1349 return $result;
1350 }
1351
1352
1366 public function search($checkDn, $filter)
1367 {
1368 dol_syslog(get_class($this)."::search checkDn=".$checkDn." filter=".$filter);
1369
1370 $checkDn = $this->convFromOutputCharset($checkDn, $this->ldapcharset);
1371 $filter = $this->convFromOutputCharset($filter, $this->ldapcharset);
1372
1373 // if the directory is AD, then bind first with the search user first
1374 if ($this->serverType == "activedirectory") {
1375 $this->bindauth($this->searchUser, $this->searchPassword);
1376 }
1377
1378 $this->result = @ldap_search($this->connection, $checkDn, $filter);
1379
1380 $result = @ldap_get_entries($this->connection, $this->result);
1381 if (!$result) {
1382 $this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1383 return -1;
1384 } else {
1385 ldap_free_result($this->result);
1386 return $result;
1387 }
1388 }
1389
1390
1399 public function fetch($user, $filter)
1400 {
1401 // Perform the search and get the entry handles
1402
1403 // if the directory is AD, then bind first with the search user first
1404 if ($this->serverType == "activedirectory") {
1405 $this->bindauth($this->searchUser, $this->searchPassword);
1406 }
1407
1408 $searchDN = $this->people; // TODO Why searching in people then domain ?
1409
1410 $result = '';
1411 $i = 0;
1412 while ($i <= 2) {
1413 dol_syslog(get_class($this)."::fetch search with searchDN=".$searchDN." filter=".$filter);
1414 $this->result = @ldap_search($this->connection, $searchDN, $filter);
1415 if ($this->result) {
1416 $result = @ldap_get_entries($this->connection, $this->result);
1417 if ($result['count'] > 0) {
1418 dol_syslog('Ldap::fetch search found '.$result['count'].' records');
1419 } else {
1420 dol_syslog('Ldap::fetch search returns but found no records');
1421 }
1422 //var_dump($result);exit;
1423 } else {
1424 $this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1425 dol_syslog(get_class($this)."::fetch search fails");
1426 return -1;
1427 }
1428
1429 if (!$result) {
1430 // Si pas de resultat on cherche dans le domaine
1431 $searchDN = $this->domain;
1432 $i++;
1433 } else {
1434 break;
1435 }
1436 }
1437
1438 if (!$result) {
1439 $this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1440 return -1;
1441 } else {
1442 $this->name = $this->convToOutputCharset($result[0][$this->attr_name][0], $this->ldapcharset);
1443 $this->firstname = $this->convToOutputCharset($result[0][$this->attr_firstname][0], $this->ldapcharset);
1444 $this->login = $this->convToOutputCharset($result[0][$this->attr_login][0], $this->ldapcharset);
1445 $this->phone = $this->convToOutputCharset($result[0][$this->attr_phone][0], $this->ldapcharset);
1446 $this->fax = $this->convToOutputCharset($result[0][$this->attr_fax][0], $this->ldapcharset);
1447 $this->mail = $this->convToOutputCharset($result[0][$this->attr_mail][0], $this->ldapcharset);
1448 $this->mobile = $this->convToOutputCharset($result[0][$this->attr_mobile][0], $this->ldapcharset);
1449
1450 $this->uacf = $this->parseUACF($this->convToOutputCharset($result[0]["useraccountcontrol"][0], $this->ldapcharset));
1451 if (isset($result[0]["pwdlastset"][0])) { // If expiration on password exists
1452 $this->pwdlastset = ($result[0]["pwdlastset"][0] != 0) ? $this->convertTime($this->convToOutputCharset($result[0]["pwdlastset"][0], $this->ldapcharset)) : 0;
1453 } else {
1454 $this->pwdlastset = -1;
1455 }
1456 if (!$this->name && !$this->login) {
1457 $this->pwdlastset = -1;
1458 }
1459 $this->badpwdtime = $this->convertTime($this->convToOutputCharset($result[0]["badpasswordtime"][0], $this->ldapcharset));
1460
1461 // FQDN domain
1462 $domain = str_replace('dc=', '', $this->domain);
1463 $domain = str_replace(',', '.', $domain);
1464 $this->domainFQDN = $domain;
1465
1466 // Set ldapUserDn (each user can have a different dn)
1467 //var_dump($result[0]);exit;
1468 $this->ldapUserDN = $result[0]['dn'];
1469
1470 ldap_free_result($this->result);
1471 return 1;
1472 }
1473 }
1474
1475
1476 // helper methods
1477
1483 public function getUserIdentifier()
1484 {
1485 if ($this->serverType == "activedirectory") {
1486 return $this->attr_sambalogin;
1487 } else {
1488 return $this->attr_login;
1489 }
1490 }
1491
1498 public function parseUACF($uacf)
1499 {
1500 //All flags array
1501 $flags = array(
1502 "TRUSTED_TO_AUTH_FOR_DELEGATION" => 16777216,
1503 "PASSWORD_EXPIRED" => 8388608,
1504 "DONT_REQ_PREAUTH" => 4194304,
1505 "USE_DES_KEY_ONLY" => 2097152,
1506 "NOT_DELEGATED" => 1048576,
1507 "TRUSTED_FOR_DELEGATION" => 524288,
1508 "SMARTCARD_REQUIRED" => 262144,
1509 "MNS_LOGON_ACCOUNT" => 131072,
1510 "DONT_EXPIRE_PASSWORD" => 65536,
1511 "SERVER_TRUST_ACCOUNT" => 8192,
1512 "WORKSTATION_TRUST_ACCOUNT" => 4096,
1513 "INTERDOMAIN_TRUST_ACCOUNT" => 2048,
1514 "NORMAL_ACCOUNT" => 512,
1515 "TEMP_DUPLICATE_ACCOUNT" => 256,
1516 "ENCRYPTED_TEXT_PWD_ALLOWED" => 128,
1517 "PASSWD_CANT_CHANGE" => 64,
1518 "PASSWD_NOTREQD" => 32,
1519 "LOCKOUT" => 16,
1520 "HOMEDIR_REQUIRED" => 8,
1521 "ACCOUNTDISABLE" => 2,
1522 "SCRIPT" => 1
1523 );
1524
1525 //Parse flags to text
1526 $retval = array();
1527 //while (list($flag, $val) = each($flags)) {
1528 foreach ($flags as $flag => $val) {
1529 if ($uacf >= $val) {
1530 $uacf -= $val;
1531 $retval[$val] = $flag;
1532 }
1533 }
1534
1535 //Return human friendly flags
1536 return $retval;
1537 }
1538
1545 public function parseSAT($samtype)
1546 {
1547 $stypes = array(
1548 805306368 => "NORMAL_ACCOUNT",
1549 805306369 => "WORKSTATION_TRUST",
1550 805306370 => "INTERDOMAIN_TRUST",
1551 268435456 => "SECURITY_GLOBAL_GROUP",
1552 268435457 => "DISTRIBUTION_GROUP",
1553 536870912 => "SECURITY_LOCAL_GROUP",
1554 536870913 => "DISTRIBUTION_LOCAL_GROUP"
1555 );
1556
1557 $retval = "";
1558 foreach ($stypes as $sat => $val) {
1559 if ($samtype == $sat) {
1560 $retval = $val;
1561 break;
1562 }
1563 }
1564 if (empty($retval)) {
1565 $retval = "UNKNOWN_TYPE_".$samtype;
1566 }
1567
1568 return $retval;
1569 }
1570
1577 public function convertTime($value)
1578 {
1579 $dateLargeInt = $value; // nano secondes depuis 1601 !!!!
1580 if (PHP_INT_SIZE < 8) {
1581 // 32 bit platform
1582 $secsAfterADEpoch = (float) $dateLargeInt / (10000000.); // secondes depuis le 1 jan 1601
1583 } else {
1584 // At least 64 bit platform
1585 $secsAfterADEpoch = (int) $dateLargeInt / (10000000); // secondes depuis le 1 jan 1601
1586 }
1587 $ADToUnixConvertor = ((1970 - 1601) * 365.242190) * 86400; // UNIX start date - AD start date * jours * secondes
1588 $unixTimeStamp = intval($secsAfterADEpoch - $ADToUnixConvertor); // Unix time stamp
1589 return $unixTimeStamp;
1590 }
1591
1592
1600 private function convToOutputCharset($str, $pagecodefrom = 'UTF-8')
1601 {
1602 global $conf;
1603 if ($pagecodefrom == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8') {
1604 $str = mb_convert_encoding($str, 'UTF-8', 'ISO-8859-1');
1605 }
1606 if ($pagecodefrom == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1') {
1607 $str = mb_convert_encoding($str, 'ISO-8859-1');
1608 }
1609 return $str;
1610 }
1611
1619 public function convFromOutputCharset($str, $pagecodeto = 'UTF-8')
1620 {
1621 global $conf;
1622 if ($pagecodeto == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8') {
1623 $str = mb_convert_encoding($str, 'ISO-8859-1');
1624 }
1625 if ($pagecodeto == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1') {
1626 $str = mb_convert_encoding($str, 'UTF-8', 'ISO-8859-1');
1627 }
1628 return $str;
1629 }
1630
1631
1638 public function getNextGroupGid($keygroup = 'LDAP_KEY_GROUPS')
1639 {
1640
1641 if (empty($keygroup)) {
1642 $keygroup = 'LDAP_KEY_GROUPS';
1643 }
1644
1645 $search = '(' . getDolGlobalString($keygroup).'=*)';
1646 $result = $this->search($this->groups, $search);
1647 if ($result) {
1648 $c = $result['count'];
1649 $gids = array();
1650 for ($i = 0; $i < $c; $i++) {
1651 $gids[] = $result[$i]['gidnumber'][0];
1652 }
1653 rsort($gids);
1654
1655 return $gids[0] + 1;
1656 }
1657
1658 return 0;
1659 }
1660}
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 a 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:140