-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathldap.class.php
More file actions
1661 lines (1456 loc) · 48.7 KB
/
ldap.class.php
File metadata and controls
1661 lines (1456 loc) · 48.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/* Copyright (C) 2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
* Copyright (C) 2005-2021 Regis Houssin <regis.houssin@inodbox.com>
* Copyright (C) 2006-2021 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
* Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
* Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* or see https://www.gnu.org/
*/
/**
* \file htdocs/core/class/ldap.class.php
* \ingroup ldap
* \brief File of class to manage LDAP features
*
* Note:
* LDAP_ESCAPE_FILTER is to escape char array('\\', '*', '(', ')', "\x00")
* LDAP_ESCAPE_DN is to escape char array('\\', ',', '=', '+', '<', '>', ';', '"', '#')
* @phan-file-suppress PhanTypeMismatchArgumentInternal (notifications concern 'resource')
*/
/**
* Class to manage LDAP features
*/
class Ldap
{
/**
* @var string Error code (or message)
*/
public $error = '';
/**
* @var string[] Array of error strings
*/
public $errors = array();
/**
* @var string[] Servers (IP addresses or hostnames)
*/
public $server = array();
/**
* @var string Current connected server
*/
public $connectedServer;
/**
* @var int server port
*/
public $serverPort;
/**
* @var string Base DN (e.g. "dc=foo,dc=com")
*/
public $dn;
/**
* @var string Server type: OpenLDAP or Active Directory
*/
public $serverType;
/**
* @var string LDAP protocol version
*/
public $ldapProtocolVersion;
/**
* @var string Server DN
*/
public $domain;
/**
* @var string Server FQDN
*/
public $domainFQDN;
/**
* @var bool LDAP bind
*/
public $bind;
/**
* @var string LDAP administrator user
* Active Directory does not allow anonymous connections
*/
public $searchUser;
/**
* @var string LDAP administrator password
* Active Directory does not allow anonymous connections
*/
public $searchPassword;
/**
* @var string Users DN
*/
public $people;
/**
* @var string Groups DN
*/
public $groups;
/**
* @var int|null Error code provided by the LDAP server
*/
public $ldapErrorCode;
/**
* @var string|null Error text message
*/
public $ldapErrorText;
/**
* @var string
*/
public $filter;
/**
* @var string
*/
public $filtergroup;
/**
* @var string
*/
public $filtermember;
/**
* @var string attr_login
*/
public $attr_login;
/**
* @var string attr_sambalogin
*/
public $attr_sambalogin;
/**
* @var string attr_name
*/
public $attr_name;
/**
* @var string attr_firstname
*/
public $attr_firstname;
/**
* @var string attr_mail
*/
public $attr_mail;
/**
* @var string attr_phone
*/
public $attr_phone;
/**
* @var string attr_fax
*/
public $attr_fax;
/**
* @var string attr_mobile
*/
public $attr_mobile;
/**
* @var int badpwdtime
*/
public $badpwdtime;
/**
* @var string LDAP user DN
*/
public $ldapUserDN;
/**
* @var string Fetched username
*/
public $name;
/**
* @var string Fetched user first name
*/
public $firstname;
/**
* @var string Fetched user login
*/
public $login;
/**
* @var string Fetched user phone number
*/
public $phone;
/**
* @var string Fetched user fax number
*/
public $fax;
/**
* @var string Fetched user email
*/
public $mail;
/**
* @var string Fetched user mobile number
*/
public $mobile;
/**
* @var array<int,string> UserAccountControl Flags
*/
public $uacf;
/**
* @var int Password last set time
*/
public $pwdlastset;
/**
* @var string LDAP charset.
* LDAP should be UTF-8 encoded
*/
public $ldapcharset = 'UTF-8';
/**
* @var false|resource The internal LDAP connection handle. Was a resource before PHP 8.1 and is an object of class LDAP\Connection since PHP 8.1
* @phpstan-var LDAP\Connection
*/
public $connection;
/**
* @var bool|resource Result of any connections or search.
*/
public $result;
/**
* @var int No LDAP synchronization
*/
const SYNCHRO_NONE = 0;
/**
* @var int Dolibarr to LDAP synchronization
*/
const SYNCHRO_DOLIBARR_TO_LDAP = 1;
/**
* @var int LDAP to Dolibarr synchronization
*/
const SYNCHRO_LDAP_TO_DOLIBARR = 2;
/**
* Constructor
*/
public function __construct()
{
// Server
if (getDolGlobalString('LDAP_SERVER_HOST')) {
$this->server[] = getDolGlobalString('LDAP_SERVER_HOST');
}
if (getDolGlobalString('LDAP_SERVER_HOST_SLAVE')) {
$this->server[] = getDolGlobalString('LDAP_SERVER_HOST_SLAVE');
}
$this->serverPort = getDolGlobalInt('LDAP_SERVER_PORT', 389);
$this->ldapProtocolVersion = getDolGlobalString('LDAP_SERVER_PROTOCOLVERSION');
$this->dn = getDolGlobalString('LDAP_SERVER_DN');
$this->serverType = getDolGlobalString('LDAP_SERVER_TYPE');
$this->domain = getDolGlobalString('LDAP_SERVER_DN');
$this->searchUser = getDolGlobalString('LDAP_ADMIN_DN');
$this->searchPassword = getDolGlobalString('LDAP_ADMIN_PASS');
$this->people = getDolGlobalString('LDAP_USER_DN');
$this->groups = getDolGlobalString('LDAP_GROUP_DN');
$this->filter = getDolGlobalString('LDAP_FILTER_CONNECTION'); // Filter on user
$this->filtergroup = getDolGlobalString('LDAP_GROUP_FILTER'); // Filter on groups
$this->filtermember = getDolGlobalString('LDAP_MEMBER_FILTER'); // Filter on member
// Users
$this->attr_login = getDolGlobalString('LDAP_FIELD_LOGIN'); //unix
$this->attr_sambalogin = getDolGlobalString('LDAP_FIELD_LOGIN_SAMBA'); //samba, activedirectory
$this->attr_name = getDolGlobalString('LDAP_FIELD_NAME');
$this->attr_firstname = getDolGlobalString('LDAP_FIELD_FIRSTNAME');
$this->attr_mail = getDolGlobalString('LDAP_FIELD_MAIL');
$this->attr_phone = getDolGlobalString('LDAP_FIELD_PHONE');
$this->attr_fax = getDolGlobalString('LDAP_FIELD_FAX');
$this->attr_mobile = getDolGlobalString('LDAP_FIELD_MOBILE');
}
// Connection handling methods -------------------------------------------
/**
* Connect and bind
* Use this->server, this->serverPort, this->ldapProtocolVersion, this->serverType, this->searchUser, this->searchPassword
* After return, this->connection and $this->bind are defined
*
* @return int if KO: <0 || if bind anonymous: 1 || if bind auth: 2
*/
public function connectBind()
{
global $dolibarr_main_auth_ldap_debug;
$connected = 0;
$this->bind = false;
$this->error = '';
$this->connectedServer = '';
$ldapdebug = !((empty($dolibarr_main_auth_ldap_debug) || $dolibarr_main_auth_ldap_debug == "false"));
if ($ldapdebug) {
dol_syslog(get_class($this)."::connectBind");
print "DEBUG: connectBind<br>\n";
}
// Check parameters
if (count($this->server) == 0 || empty($this->server[0])) {
$this->error = 'LDAP setup (file conf.php) is not complete';
dol_syslog(get_class($this)."::connectBind ".$this->error, LOG_WARNING);
return -1;
}
if (!function_exists("ldap_connect")) {
$this->error = 'LDAPFunctionsNotAvailableOnPHP';
dol_syslog(get_class($this)."::connectBind ".$this->error, LOG_WARNING);
return -1;
}
if (empty($this->error)) {
// Loop on each ldap server
foreach ($this->server as $host) {
if ($connected) { // @phpstan-ignore if.alwaysFalse
break;
}
if (empty($host)) {
continue;
}
if ($this->serverPing($host, $this->serverPort)) {
if ($ldapdebug) {
dol_syslog(get_class($this)."::connectBind serverPing true, we try ldap_connect to ".$host, LOG_DEBUG);
}
if (version_compare(PHP_VERSION, '8.3.0', '>=')) {
$uri = $host.':'.$this->serverPort;
$this->connection = ldap_connect($uri);
} else {
$this->connection = ldap_connect($host, $this->serverPort);
}
} else {
if (preg_match('/^ldaps/i', $host)) {
// With host = ldaps://server, the serverPing to ssl://server sometimes fails, even if the ldap_connect succeed, so
// we test this case and continue in such a case even if serverPing fails.
if ($ldapdebug) {
dol_syslog(get_class($this)."::connectBind serverPing false, we try ldap_connect to ".$host, LOG_DEBUG);
}
if (version_compare(PHP_VERSION, '8.3.0', '>=')) {
$uri = $host.':'.$this->serverPort;
$this->connection = ldap_connect($uri);
} else {
$this->connection = ldap_connect($host, $this->serverPort);
}
} else {
if ($ldapdebug) {
dol_syslog(get_class($this)."::connectBind serverPing false, no ldap_connect ".$host, LOG_DEBUG);
}
continue;
}
}
if ($this->connection !== false) {
if ($ldapdebug) {
dol_syslog(get_class($this)."::connectBind this->connection is ok", LOG_DEBUG);
}
// Upgrade connection to TLS, if requested by the configuration
if (getDolGlobalString('LDAP_SERVER_USE_TLS')) {
// For test/debug
//ldap_set_option($this->connection, LDAP_OPT_DEBUG_LEVEL, 7);
//ldap_set_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, 3);
//ldap_set_option($this->connection, LDAP_OPT_REFERRALS, 0);
$resulttls = ldap_start_tls($this->connection);
if (!$resulttls) {
dol_syslog(get_class($this)."::connectBind failed to start tls", LOG_WARNING);
$this->error = 'ldap_start_tls Failed to start TLS '.ldap_errno($this->connection).' '.ldap_error($this->connection);
$connected = 0;
$this->unbind();
}
}
// Execute the ldap_set_option here (after connect and before bind)
$this->setVersion();
$this->setSizeLimit();
if ($this->serverType == "activedirectory") {
$result = $this->setReferrals();
dol_syslog(get_class($this)."::connectBind try bindauth for activedirectory on ".$host." user=".$this->searchUser." password=".preg_replace('/./', '*', $this->searchPassword), LOG_DEBUG);
$this->result = $this->bindauth($this->searchUser, $this->searchPassword);
if ($this->result) {
$this->bind = $this->result;
$connected = 2;
$this->connectedServer = $host;
break;
} else {
$this->error = ldap_errno($this->connection).' '.ldap_error($this->connection);
}
} else {
// Try in auth mode
if ($this->searchUser && $this->searchPassword) {
dol_syslog(get_class($this)."::connectBind try bindauth on ".$host." user=".$this->searchUser." password=".preg_replace('/./', '*', $this->searchPassword), LOG_DEBUG);
$this->result = $this->bindauth($this->searchUser, $this->searchPassword);
if ($this->result) {
$this->bind = $this->result;
$connected = 2;
$this->connectedServer = $host;
break;
} else {
$this->error = ldap_errno($this->connection).' '.ldap_error($this->connection);
}
}
// Try in anonymous
if (!$this->bind) { // @phpstan-ignore booleanNot.alwaysTrue
dol_syslog(get_class($this)."::connectBind try bind anonymously on ".$host, LOG_DEBUG);
$result = $this->bind();
if ($result) {
$this->bind = $this->result;
$connected = 1;
$this->connectedServer = $host;
break;
} else {
$this->error = ldap_errno($this->connection).' '.ldap_error($this->connection);
}
}
}
}
if (!$connected) { // @phpstan-ignore booleanNot.alwaysTrue
$this->unbind();
}
} // End loop on each server
}
if ($connected) {
dol_syslog(get_class($this)."::connectBind ".$connected, LOG_DEBUG);
return $connected;
} else {
$this->error = 'Failed to connect to LDAP'.($this->error ? ': '.$this->error : '');
dol_syslog(get_class($this)."::connectBind ".$this->error, LOG_WARNING);
return -1;
}
}
/**
* Simply closes the connection set up earlier. Returns true if OK, false if there was an error.
* This method seems a duplicate/alias of unbind().
*
* @return boolean true or false
* @deprecated ldap_close is an alias of ldap_unbind, so use unbind() instead.
* @see unbind()
*/
public function close()
{
return $this->unbind();
}
/**
* Anonymously binds to the connection. After this is done,
* queries and searches can be done - but read-only.
*
* @return boolean true or false
*/
public function bind()
{
if (!$this->result = @ldap_bind($this->connection)) {
$this->ldapErrorCode = ldap_errno($this->connection);
$this->ldapErrorText = ldap_error($this->connection);
$this->error = $this->ldapErrorCode." ".$this->ldapErrorText;
return false;
} else {
return true;
}
}
/**
* Binds as an authenticated user, which usually allows for write
* access. The FULL dn must be passed. For a directory manager, this is
* "cn=Directory Manager" under iPlanet. For a user, it will be something
* like "uid=jbloggs,ou=People,dc=foo,dc=com".
*
* @param string $bindDn DN
* @param string $pass Password
* @return bool true or false
*/
public function bindauth($bindDn, $pass)
{
if (!$this->result = @ldap_bind($this->connection, $bindDn, $pass)) {
$this->ldapErrorCode = ldap_errno($this->connection);
$this->ldapErrorText = ldap_error($this->connection);
$this->error = $this->ldapErrorCode." ".$this->ldapErrorText;
return false;
} else {
return true;
}
}
/**
* Unbind of LDAP server (close connection).
*
* @return bool true or false
* @see close()
*/
public function unbind()
{
$this->result = true;
if (version_compare(PHP_VERSION, '8.1.0', '>=')) {
if (is_object($this->connection)) {
try {
$this->result = ldap_unbind($this->connection);
} catch (Throwable $exception) {
$this->error = 'Failed to unbind LDAP connection: '.$exception;
$this->result = false;
dol_syslog(get_class($this).'::unbind - '.$this->error, LOG_WARNING);
}
}
} else {
if ($this->connection !== false) {
// @phan-suppress-next-line PhanTypeMismatchArgumentInternalReal PhanTypeSuspiciousIndirectVariable
$this->result = @ldap_unbind($this->connection);
}
}
if ($this->result) {
return true;
} else {
return false;
}
}
/**
* Verify LDAP server version
*
* @return int version
*/
public function getVersion()
{
@ldap_get_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, $version);
return $version;
}
/**
* Set LDAP protocol version.
* LDAP_OPT_PROTOCOL_VERSION is a constant equal to 3
*
* @return bool if set LDAP option OK: true, if KO: false
*/
public function setVersion()
{
return ldap_set_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, $this->ldapProtocolVersion);
}
/**
* Set LDAP size limit.
*
* @return bool if set LDAP option OK: true, if KO: false
*/
public function setSizeLimit()
{
return ldap_set_option($this->connection, LDAP_OPT_SIZELIMIT, 0);
}
/**
* Set LDAP referrals.
* LDAP_OPT_REFERRALS is a constant equal to ?
*
* @return bool if set LDAP option OK: true, if KO: false
*/
public function setReferrals()
{
return ldap_set_option($this->connection, LDAP_OPT_REFERRALS, 0);
}
/**
* Add an LDAP entry
* LDAP object connect and bind must have been done
*
* @param string $dn DN entry key
* @param array<string,string[]> $info Attributes array
* @param User $user Object user that create
* @return int<-3,-1>|int<1,1> if KO: <0 || if OK: >0
*/
public function add($dn, $info, $user)
{
dol_syslog(get_class($this)."::add dn=".$dn." info=".print_r($info, true));
// Check parameters
if (!$this->connection) {
$this->error = "NotConnected";
return -2;
}
if (!$this->bind) {
$this->error = "NotConnected";
return -3;
}
// Encode to LDAP page code
$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
foreach ($info as $key => $val) {
if (!is_array($val)) {
$info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
}
}
$this->dump($dn, $info);
//print_r($info);
$result = @ldap_add($this->connection, $dn, $info);
if ($result) {
dol_syslog(get_class($this)."::add successful", LOG_DEBUG);
return 1;
} else {
$this->ldapErrorCode = @ldap_errno($this->connection);
$this->ldapErrorText = @ldap_error($this->connection);
$this->error = $this->ldapErrorCode." ".$this->ldapErrorText;
dol_syslog(get_class($this)."::add failed: ".$this->error, LOG_ERR);
return -1;
}
}
/**
* Modify an LDAP entry
* LDAP object connect and bind must have been done
*
* @param string $dn DN entry key
* @param array<string,string[]> $info Attributes array
* @param User $user Object user that modify
* @return int<-3,-1>|int<1,1> if KO: <0 || if OK: >0
*/
public function modify($dn, $info, $user)
{
dol_syslog(get_class($this)."::modify dn=".$dn." info=".print_r($info, true));
// Check parameters
if (!$this->connection) {
$this->error = "NotConnected";
return -2;
}
if (!$this->bind) {
$this->error = "NotConnected";
return -3;
}
// Encode to LDAP page code
$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
foreach ($info as $key => $val) {
if (!is_array($val)) {
$info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
}
}
$this->dump($dn, $info);
//print_r($info);
// For better compatibility with Samba4 AD
if ($this->serverType == "activedirectory") {
unset($info['cn']); // To avoid error : Operation not allowed on RDN (Code 67)
// To avoid error : LDAP Error: 53 (Unwilling to perform)
if (isset($info['unicodePwd'])) {
$info['unicodePwd'] = mb_convert_encoding("\"".$info['unicodePwd']."\"", "UTF-16LE", "UTF-8");
}
}
$result = @ldap_mod_replace($this->connection, $dn, $info);
if ($result) {
dol_syslog(get_class($this)."::modify successful", LOG_DEBUG);
return 1;
} else {
$this->error = @ldap_error($this->connection);
dol_syslog(get_class($this)."::modify failed: ".$this->error, LOG_ERR);
return -1;
}
}
/**
* Rename an LDAP entry
* LDAP object connect and bind must have been done
*
* @param string $dn Old DN entry key (uid=qqq,ou=xxx,dc=aaa,dc=bbb) (before update)
* @param string $newrdn New RDN entry key (uid=qqq)
* @param string $newparent New parent (ou=xxx,dc=aaa,dc=bbb)
* @param User $user Object user that modify
* @param bool $deleteoldrdn If true the old RDN value(s) is removed, else the old RDN value(s) is retained as non-distinguished values of the entry.
* @return int<-3,-1>|int<1,1> if KO: <0 || if OK: >0
*/
public function rename($dn, $newrdn, $newparent, $user, $deleteoldrdn = true)
{
dol_syslog(get_class($this)."::modify dn=".$dn." newrdn=".$newrdn." newparent=".$newparent." deleteoldrdn=".($deleteoldrdn ? 1 : 0));
// Check parameters
if (!$this->connection) {
$this->error = "NotConnected";
return -2;
}
if (!$this->bind) {
$this->error = "NotConnected";
return -3;
}
// Encode to LDAP page code
$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
$newrdn = $this->convFromOutputCharset($newrdn, $this->ldapcharset);
$newparent = $this->convFromOutputCharset($newparent, $this->ldapcharset);
//print_r($info);
$result = @ldap_rename($this->connection, $dn, $newrdn, $newparent, $deleteoldrdn);
if ($result) {
dol_syslog(get_class($this)."::rename successful", LOG_DEBUG);
return 1;
} else {
$this->error = @ldap_error($this->connection);
dol_syslog(get_class($this)."::rename failed: ".$this->error, LOG_ERR);
return -1;
}
}
/**
* Modify an LDAP entry (to use if dn != olddn)
* LDAP object connect and bind must have been done
*
* @param string $dn DN entry key
* @param array<string,string[]> $info Attributes array
* @param User $user Object user that update
* @param string $olddn Old DN entry key (before update)
* @param string $newrdn New RDN entry key (uid=qqq) (for ldap_rename)
* @param string $newparent New parent (ou=xxx,dc=aaa,dc=bbb) (for ldap_rename)
* @return int<-3,-1>|int<1,1> if KO: <0 || if OK: >0
*/
public function update($dn, $info, $user, $olddn, $newrdn = '', $newparent = '')
{
dol_syslog(get_class($this)."::update dn=".$dn." olddn=".$olddn);
// Check parameters
if (!$this->connection) {
$this->error = "NotConnected";
return -2;
}
if (!$this->bind) {
$this->error = "NotConnected";
return -3;
}
if (!$olddn || $olddn != $dn) {
if (!empty($olddn) && !empty($newrdn) && !empty($newparent) && $this->ldapProtocolVersion === '3') {
// This function currently only works with LDAPv3
$result = $this->rename($olddn, $newrdn, $newparent, $user, true);
$result = $this->modify($dn, $info, $user); // We force "modify" for avoid some fields not modify
} else {
// If change we make is rename the key of LDAP record, we create new one and if ok, we delete old one.
$result = $this->add($dn, $info, $user);
if ($result > 0 && $olddn && $olddn != $dn) {
$result = $this->delete($olddn); // If add fails, we do not try to delete old one
}
}
} else {
//$result = $this->delete($olddn);
$result = $this->add($dn, $info, $user); // If record has been deleted from LDAP, we recreate it. We ignore error if it already exists.
$result = $this->modify($dn, $info, $user); // We use add/modify instead of delete/add when olddn is received
}
if ($result <= 0) {
$this->error = ldap_error($this->connection).' (Code '.ldap_errno($this->connection).") ".$this->error;
dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
//print_r($info);
return -1;
} else {
dol_syslog(get_class($this)."::update done successfully");
return 1;
}
}
/**
* Delete an LDAP entry
* LDAP object connect and bind must have been done
*
* @param string $dn DN entry key
* @return int<-3,-1>|int<1,1> if KO: <0 || if OK: >0
*/
public function delete($dn)
{
dol_syslog(get_class($this)."::delete Delete LDAP entry dn=".$dn);
// Check parameters
if (!$this->connection) {
$this->error = "NotConnected";
return -2;
}
if (!$this->bind) {
$this->error = "NotConnected";
return -3;
}
// Encode to LDAP page code
$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
$result = @ldap_delete($this->connection, $dn);
if ($result) {
return 1;
}
return -1;
}
/**
* Build an LDAP message
*
* @param string $dn DN entry key
* @param array<string,string[]> $info Attributes array
* @return string Content of file
*/
public function dumpContent($dn, $info)
{
$content = '';
// Create file content
if (preg_match('/^ldap/', $this->server[0])) {
$target = "-H ".implode(',', $this->server);
} else {
$target = "-h ".implode(',', $this->server)." -p ".$this->serverPort;
}
$content .= "# ldapadd $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
$content .= "# ldapmodify $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
$content .= "# ldapdelete $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
if (in_array('localhost', $this->server)) {
$content .= "# If commands fails to connect, try without -h and -p\n";
}
$content .= "dn: ".$dn."\n";
foreach ($info as $key => $value) {
if (!is_array($value)) {
$content .= "$key: $value\n";
} else {
foreach ($value as $valuevalue) {
$content .= "$key: $valuevalue\n";
}
}
}
return $content;
}
/**
* Dump an LDAP message to ldapinput.in file
*
* @param string $dn DN entry key
* @param array<string,string[]> $info Attributes array
* @return int<-1,-1>|int<1,1> if KO: <0 || if OK: >0
*/
public function dump($dn, $info)
{
global $conf;
$ldapDirTemp = $conf->ldap->dir_temp;
// Create content
$content = $this->dumpContent($dn, $info);
//Create directory & file
$result = dol_mkdir($ldapDirTemp);
if ($result != 0) {
$outputfile = $ldapDirTemp.'/ldapinput.in';
$fp = fopen($outputfile, "w");
if ($fp) {
fwrite($fp, $content);
fclose($fp);
dolChmod($outputfile);
return 1;
} else {
return -1;
}
} else {
return -1;
}
}
/**
* Ping a server before ldap_connect for avoid waiting
*
* @param string $host Server host or address
* @param int $port Server port (default 389)
* @param int $timeout Timeout in second (default 1s)
* @return bool true or false
*/
public function serverPing($host, $port = 389, $timeout = 1)
{
$regs = array();
if (preg_match('/^ldaps:\/\/([^\/]+)\/?$/', $host, $regs)) {
// Replace ldaps:// by ssl://
$host = 'ssl://'.$regs[1];
} elseif (preg_match('/^ldap:\/\/([^\/]+)\/?$/', $host, $regs)) {
// Remove ldap://
$host = $regs[1];
}
//var_dump($newhostforstream); var_dump($host); var_dump($port);
//$host = 'ssl://ldap.test.local:636';
//$port = 636;
$errno = $errstr = 0;
/*
if ($methodtochecktcpconnect == 'socket') {
Try to use socket_create() method.
Method that use stream_context_create() works only on registered listed in stream stream_get_wrappers(): http, https, ftp, ...
}
*/
// Use the method fsockopen to test tcp connect. No way to ignore ssl certificate errors with this method !
$op = @fsockopen($host, $port, $errno, $errstr, $timeout);
//var_dump($op);
if (!$op) {
return false; //DC is N/A
} else {
fclose($op); //explicitly close open socket connection
return true; //DC is up & running, we can safely connect with ldap_connect
}
}
// Attribute methods -----------------------------------------------------
/**
* Add an LDAP attribute in entry
* LDAP object connect and bind must have been done
*
* @param string $dn DN entry key
* @param array<string,string|string[]> $info Attributes array
* @param User $user Object user that create
* @return int<-3,-1>|int<1,1> if KO: <0 || if OK: >0
*/
public function addAttribute($dn, $info, $user)
{
dol_syslog(get_class($this)."::addAttribute dn=".$dn." info=".implode(',', $info));
// Check parameters
if (!$this->connection) {
$this->error = "NotConnected";
return -2;
}
if (!$this->bind) {
$this->error = "NotConnected";
return -3;
}
// Encode to LDAP page code
$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
foreach ($info as $key => $val) {
if (!is_array($val)) {
$info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
}
}
$this->dump($dn, $info);
//print_r($info);
$result = @ldap_mod_add($this->connection, $dn, $info);
if ($result) {
dol_syslog(get_class($this)."::add_attribute successful", LOG_DEBUG);
return 1;
} else {
$this->error = @ldap_error($this->connection);
dol_syslog(get_class($this)."::add_attribute failed: ".$this->error, LOG_ERR);
return -1;
}
}
/**
* Update an LDAP attribute in entry
* LDAP object connect and bind must have been done
*
* @param string $dn DN entry key
* @param array<string,string|string[]> $info Attributes array