Passed
Branch develop (7a9ea1)
by
unknown
36:03
created

Ldap::deleteAttribute()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 34
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 20
nc 8
nop 3
dl 0
loc 34
rs 8.9777
c 0
b 0
f 0
1
<?php
2
/* Copyright (C) 2004		Rodolphe Quiedeville <[email protected]>
3
 * Copyright (C) 2004		Benoit Mortier       <[email protected]>
4
 * Copyright (C) 2005-2017	Regis Houssin        <[email protected]>
5
 * Copyright (C) 2006-2015	Laurent Destailleur  <[email protected]>
6
 *
7
 * This program is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19
 * or see https://www.gnu.org/
20
 */
21
22
/**
23
 *	\file 		htdocs/core/class/ldap.class.php
24
 *	\brief 		File of class to manage LDAP features
25
 *
26
 *  Note:
27
 *  LDAP_ESCAPE_FILTER is to escape char  array('\\', '*', '(', ')', "\x00")
28
 *  LDAP_ESCAPE_DN is to escape char  array('\\', ',', '=', '+', '<', '>', ';', '"', '#')
29
 */
30
31
/**
32
 *	Class to manage LDAP features
33
 */
34
class Ldap
35
{
36
	/**
37
	 * @var string Error code (or message)
38
	 */
39
	public $error = '';
40
41
	/**
42
	 * @var string[]	Array of error strings
43
	 */
44
	public $errors = array();
45
46
	/**
47
	 * Tableau des serveurs (IP addresses ou nom d'hotes)
48
	 */
49
	public $server = array();
50
51
	/**
52
	 * Base DN (e.g. "dc=foo,dc=com")
53
	 */
54
	public $dn;
55
	/**
56
	 * type de serveur, actuellement OpenLdap et Active Directory
57
	 */
58
	public $serverType;
59
	/**
60
	 * Version du protocole ldap
61
	 */
62
	public $ldapProtocolVersion;
63
	/**
64
	 * Server DN
65
	 */
66
	public $domain;
67
	/**
68
	 * User administrateur Ldap
69
	 * Active Directory ne supporte pas les connexions anonymes
70
	 */
71
	public $searchUser;
72
	/**
73
	 * Mot de passe de l'administrateur
74
	 * Active Directory ne supporte pas les connexions anonymes
75
	 */
76
	public $searchPassword;
77
	/**
78
	 *  DN des utilisateurs
79
	 */
80
	public $people;
81
	/**
82
	 * DN des groupes
83
	 */
84
	public $groups;
85
	/**
86
	 * Code erreur retourne par le serveur Ldap
87
	 */
88
	public $ldapErrorCode;
89
	/**
90
	 * Message texte de l'erreur
91
	 */
92
	public $ldapErrorText;
93
94
95
	//Fetch user
96
	public $name;
97
	public $firstname;
98
	public $login;
99
	public $phone;
100
	public $skype;
101
	public $fax;
102
	public $mail;
103
	public $mobile;
104
105
	public $uacf;
106
	public $pwdlastset;
107
108
	public $ldapcharset = 'UTF-8'; // LDAP should be UTF-8 encoded
109
110
111
	/**
112
	 * The internal LDAP connection handle
113
	 */
114
	public $connection;
115
	/**
116
	 * Result of any connections etc.
117
	 */
118
	public $result;
119
120
121
	/**
122
	 *  Constructor
123
	 */
124
	public function __construct()
125
	{
126
		global $conf;
127
128
		// Server
129
		if (!empty($conf->global->LDAP_SERVER_HOST)) {
130
			$this->server[] = $conf->global->LDAP_SERVER_HOST;
131
		}
132
		if (!empty($conf->global->LDAP_SERVER_HOST_SLAVE)) {
133
			$this->server[] = $conf->global->LDAP_SERVER_HOST_SLAVE;
134
		}
135
		$this->serverPort          = $conf->global->LDAP_SERVER_PORT;
136
		$this->ldapProtocolVersion = $conf->global->LDAP_SERVER_PROTOCOLVERSION;
137
		$this->dn                  = $conf->global->LDAP_SERVER_DN;
138
		$this->serverType          = $conf->global->LDAP_SERVER_TYPE;
139
140
		$this->domain              = $conf->global->LDAP_SERVER_DN;
141
		$this->searchUser          = $conf->global->LDAP_ADMIN_DN;
142
		$this->searchPassword      = $conf->global->LDAP_ADMIN_PASS;
143
		$this->people              = $conf->global->LDAP_USER_DN;
144
		$this->groups              = $conf->global->LDAP_GROUP_DN;
145
146
		$this->filter              = $conf->global->LDAP_FILTER_CONNECTION; // Filter on user
147
		$this->filtergroup         = $conf->global->LDAP_GROUP_FILTER; // Filter on groups
148
		$this->filtermember        = $conf->global->LDAP_MEMBER_FILTER; // Filter on member
149
150
		// Users
151
		$this->attr_login      = $conf->global->LDAP_FIELD_LOGIN; //unix
152
		$this->attr_sambalogin = $conf->global->LDAP_FIELD_LOGIN_SAMBA; //samba, activedirectory
153
		$this->attr_name       = $conf->global->LDAP_FIELD_NAME;
154
		$this->attr_firstname  = $conf->global->LDAP_FIELD_FIRSTNAME;
155
		$this->attr_mail       = $conf->global->LDAP_FIELD_MAIL;
156
		$this->attr_phone      = $conf->global->LDAP_FIELD_PHONE;
157
		$this->attr_skype      = $conf->global->LDAP_FIELD_SKYPE;
158
		$this->attr_fax        = $conf->global->LDAP_FIELD_FAX;
159
		$this->attr_mobile     = $conf->global->LDAP_FIELD_MOBILE;
160
	}
161
162
163
164
	// Connection handling methods -------------------------------------------
165
166
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
167
	/**
168
	 *	Connect and bind
169
	 * 	Use this->server, this->serverPort, this->ldapProtocolVersion, this->serverType, this->searchUser, this->searchPassword
170
	 * 	After return, this->connection and $this->bind are defined
171
	 *
172
	 *	@return		int		<0 if KO, 1 if bind anonymous, 2 if bind auth
173
	 */
174
	public function connect_bind()
175
	{
176
		// phpcs:enable
177
		global $conf;
178
179
		$connected = 0;
180
		$this->bind = 0;
181
182
		// Check parameters
183
		if (count($this->server) == 0 || empty($this->server[0])) {
184
			$this->error = 'LDAP setup (file conf.php) is not complete';
185
			dol_syslog(get_class($this)."::connect_bind ".$this->error, LOG_WARNING);
186
			return -1;
187
		}
188
189
		if (!function_exists("ldap_connect")) {
190
			$this->error = 'LDAPFunctionsNotAvailableOnPHP';
191
			dol_syslog(get_class($this)."::connect_bind ".$this->error, LOG_WARNING);
192
			$return = -1;
193
		}
194
195
		if (empty($this->error)) {
196
			// Loop on each ldap server
197
			foreach ($this->server as $host) {
198
				if ($connected) {
199
					break;
200
				}
201
				if (empty($host)) {
202
					continue;
203
				}
204
205
				if ($this->serverPing($host, $this->serverPort) === true) {
206
					$this->connection = ldap_connect($host, $this->serverPort);
207
				} else {
208
					if (preg_match('/^ldaps/i', $host)) {
209
						// With host = ldaps://server, the serverPing to ssl://server sometimes fails, even if the ldap_connect succeed, so
210
						// we test this case and continue in suche a case even if serverPing fails.
211
						$this->connection = ldap_connect($host, $this->serverPort);
212
					} else {
213
						continue;
214
					}
215
				}
216
217
				if (is_resource($this->connection)) {
218
					// Upgrade connexion to TLS, if requested by the configuration
219
					if (!empty($conf->global->LDAP_SERVER_USE_TLS)) {
220
						// For test/debug
221
						//ldap_set_option($this->connection, LDAP_OPT_DEBUG_LEVEL, 7);
222
						//ldap_set_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, 3);
223
224
						$resulttls = ldap_start_tls($this->connection);
225
						if (!$resulttls) {
226
							dol_syslog(get_class($this)."::connect_bind failed to start tls", LOG_WARNING);
227
							$this->error = 'ldap_start_tls Failed to start TLS '.ldap_errno($this->connection).' '.ldap_error($this->connection);
228
							$connected = 0;
229
							$this->close();
230
						}
231
					}
232
233
					// Execute the ldap_set_option here (after connect and before bind)
234
					$this->setVersion();
235
					ldap_set_option($this->connection, LDAP_OPT_SIZELIMIT, 0); // no limit here. should return true.
236
237
238
					if ($this->serverType == "activedirectory") {
239
						$result = $this->setReferrals();
240
						dol_syslog(get_class($this)."::connect_bind try bindauth for activedirectory on ".$host." user=".$this->searchUser." password=".preg_replace('/./', '*', $this->searchPassword), LOG_DEBUG);
241
						$this->result = $this->bindauth($this->searchUser, $this->searchPassword);
242
						if ($this->result) {
243
							$this->bind = $this->result;
244
							$connected = 2;
245
							break;
246
						} else {
247
							$this->error = ldap_errno($this->connection).' '.ldap_error($this->connection);
248
						}
249
					} else {
250
						// Try in auth mode
251
						if ($this->searchUser && $this->searchPassword) {
252
							dol_syslog(get_class($this)."::connect_bind try bindauth on ".$host." user=".$this->searchUser." password=".preg_replace('/./', '*', $this->searchPassword), LOG_DEBUG);
253
							$this->result = $this->bindauth($this->searchUser, $this->searchPassword);
254
							if ($this->result) {
255
								$this->bind = $this->result;
256
								$connected = 2;
257
								break;
258
							} else {
259
								$this->error = ldap_errno($this->connection).' '.ldap_error($this->connection);
260
							}
261
						}
262
						// Try in anonymous
263
						if (!$this->bind) {
264
							dol_syslog(get_class($this)."::connect_bind try bind on ".$host, LOG_DEBUG);
265
							$result = $this->bind();
266
							if ($result) {
267
								$this->bind = $this->result;
268
								$connected = 1;
269
								break;
270
							} else {
271
								$this->error = ldap_errno($this->connection).' '.ldap_error($this->connection);
272
							}
273
						}
274
					}
275
				}
276
277
				if (!$connected) {
278
					$this->close();
279
				}
280
			}
281
		}
282
283
		if ($connected) {
284
			$return = $connected;
285
			dol_syslog(get_class($this)."::connect_bind return=".$return, LOG_DEBUG);
286
		} else {
287
			$this->error = 'Failed to connect to LDAP'.($this->error ? ': '.$this->error : '');
288
			$return = -1;
289
			dol_syslog(get_class($this)."::connect_bind return=".$return.' - '.$this->error, LOG_WARNING);
290
		}
291
		return $return;
292
	}
293
294
295
296
	/**
297
	 * Simply closes the connection set up earlier.
298
	 * Returns true if OK, false if there was an error.
299
	 *
300
	 * @return	boolean			true or false
301
	 */
302
	public function close()
303
	{
304
		if ($this->connection && !@ldap_close($this->connection)) {
305
			return false;
306
		} else {
307
			return true;
308
		}
309
	}
310
311
	/**
312
	 * Anonymously binds to the connection. After this is done,
313
	 * queries and searches can be done - but read-only.
314
	 *
315
	 * @return	boolean			true or false
316
	 */
317
	public function bind()
318
	{
319
		if (!$this->result = @ldap_bind($this->connection)) {
320
			$this->ldapErrorCode = ldap_errno($this->connection);
321
			$this->ldapErrorText = ldap_error($this->connection);
322
			$this->error = $this->ldapErrorCode." ".$this->ldapErrorText;
323
			return false;
324
		} else {
325
			return true;
326
		}
327
	}
328
329
	/**
330
	 * Binds as an authenticated user, which usually allows for write
331
	 * access. The FULL dn must be passed. For a directory manager, this is
332
	 * "cn=Directory Manager" under iPlanet. For a user, it will be something
333
	 * like "uid=jbloggs,ou=People,dc=foo,dc=com".
334
	 *
335
	 * @param	string	$bindDn			DN
336
	 * @param	string	$pass			Password
337
	 * @return	boolean					true or false
338
	 */
339
	public function bindauth($bindDn, $pass)
340
	{
341
		if (!$this->result = @ldap_bind($this->connection, $bindDn, $pass)) {
342
			$this->ldapErrorCode = ldap_errno($this->connection);
343
			$this->ldapErrorText = ldap_error($this->connection);
344
			$this->error = $this->ldapErrorCode." ".$this->ldapErrorText;
345
			return false;
346
		} else {
347
			return true;
348
		}
349
	}
350
351
	/**
352
	 * Unbind du serveur ldap.
353
	 *
354
	 * @return	boolean					true or false
355
	 */
356
	public function unbind()
357
	{
358
		if (!$this->result = @ldap_unbind($this->connection)) {
359
			return false;
360
		} else {
361
			return true;
362
		}
363
	}
364
365
366
	/**
367
	 * Verification de la version du serveur ldap.
368
	 *
369
	 * @return	string					version
370
	 */
371
	public function getVersion()
372
	{
373
		$version = 0;
374
		$version = @ldap_get_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, $version);
375
		return $version;
376
	}
377
378
	/**
379
	 * Change ldap protocol version to use.
380
	 *
381
	 * @return	boolean                 version
382
	 */
383
	public function setVersion()
384
	{
385
		// LDAP_OPT_PROTOCOL_VERSION est une constante qui vaut 17
386
		$ldapsetversion = ldap_set_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, $this->ldapProtocolVersion);
387
		return $ldapsetversion;
388
	}
389
390
	/**
391
	 * changement du referrals.
392
	 *
393
	 * @return	boolean                 referrals
394
	 */
395
	public function setReferrals()
396
	{
397
		// LDAP_OPT_REFERRALS est une constante qui vaut ?
398
		$ldapreferrals = ldap_set_option($this->connection, LDAP_OPT_REFERRALS, 0);
399
		return $ldapreferrals;
400
	}
401
402
403
	/**
404
	 * 	Add a LDAP entry
405
	 *	Ldap object connect and bind must have been done
406
	 *
407
	 *	@param	string	$dn			DN entry key
408
	 *	@param	array	$info		Attributes array
409
	 *	@param	User		$user		Objet user that create
410
	 *	@return	int					<0 if KO, >0 if OK
411
	 */
412
	public function add($dn, $info, $user)
413
	{
414
		dol_syslog(get_class($this)."::add dn=".$dn." info=".join(',', $info));
415
416
		// Check parameters
417
		if (!$this->connection) {
418
			$this->error = "NotConnected";
419
			return -2;
420
		}
421
		if (!$this->bind) {
422
			$this->error = "NotConnected";
423
			return -3;
424
		}
425
426
		// Encode to LDAP page code
427
		$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
428
		foreach ($info as $key => $val) {
429
			if (!is_array($val)) {
430
				$info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
431
			}
432
		}
433
434
		$this->dump($dn, $info);
435
436
		//print_r($info);
437
		$result = @ldap_add($this->connection, $dn, $info);
438
439
		if ($result) {
440
			dol_syslog(get_class($this)."::add successfull", LOG_DEBUG);
441
			return 1;
442
		} else {
443
			$this->ldapErrorCode = @ldap_errno($this->connection);
444
			$this->ldapErrorText = @ldap_error($this->connection);
445
			$this->error = $this->ldapErrorCode." ".$this->ldapErrorText;
446
			dol_syslog(get_class($this)."::add failed: ".$this->error, LOG_ERR);
447
			return -1;
448
		}
449
	}
450
451
	/**
452
	 * 	Modify a LDAP entry
453
	 *	Ldap object connect and bind must have been done
454
	 *
455
	 *	@param	string		$dn			DN entry key
456
	 *	@param	array		$info		Attributes array
457
	 *	@param	User		$user		Objet user that modify
458
	 *	@return	int						<0 if KO, >0 if OK
459
	 */
460
	public function modify($dn, $info, $user)
461
	{
462
		dol_syslog(get_class($this)."::modify dn=".$dn." info=".join(',', $info));
463
464
		// Check parameters
465
		if (!$this->connection) {
466
			$this->error = "NotConnected";
467
			return -2;
468
		}
469
		if (!$this->bind) {
470
			$this->error = "NotConnected";
471
			return -3;
472
		}
473
474
		// Encode to LDAP page code
475
		$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
476
		foreach ($info as $key => $val) {
477
			if (!is_array($val)) {
478
				$info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
479
			}
480
		}
481
482
		$this->dump($dn, $info);
483
484
		//print_r($info);
485
486
		// For better compatibility with Samba4 AD
487
		if ($this->serverType == "activedirectory") {
488
			unset($info['cn']); // To avoid error : Operation not allowed on RDN (Code 67)
489
490
			// To avoid error : LDAP Error: 53 (Unwilling to perform)
491
			if (isset($info['unicodePwd'])) {
492
				$info['unicodePwd'] = mb_convert_encoding("\"".$info['unicodePwd']."\"", "UTF-16LE", "UTF-8");
493
			}
494
		}
495
		$result = @ldap_modify($this->connection, $dn, $info);
496
497
		if ($result) {
498
			dol_syslog(get_class($this)."::modify successfull", LOG_DEBUG);
499
			return 1;
500
		} else {
501
			$this->error = @ldap_error($this->connection);
502
			dol_syslog(get_class($this)."::modify failed: ".$this->error, LOG_ERR);
503
			return -1;
504
		}
505
	}
506
507
	/**
508
	 * 	Rename a LDAP entry
509
	 *	Ldap object connect and bind must have been done
510
	 *
511
	 *	@param	string		$dn				Old DN entry key (uid=qqq,ou=xxx,dc=aaa,dc=bbb) (before update)
512
	 *	@param	string		$newrdn			New RDN entry key (uid=qqq)
513
	 *	@param	string		$newparent		New parent (ou=xxx,dc=aaa,dc=bbb)
514
	 *	@param	User			$user			Objet user that modify
515
	 *	@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.
516
	 *	@return	int							<0 if KO, >0 if OK
517
	 */
518
	public function rename($dn, $newrdn, $newparent, $user, $deleteoldrdn = true)
519
	{
520
		dol_syslog(get_class($this)."::modify dn=".$dn." newrdn=".$newrdn." newparent=".$newparent." deleteoldrdn=".($deleteoldrdn ? 1 : 0));
521
522
		// Check parameters
523
		if (!$this->connection) {
524
			$this->error = "NotConnected";
525
			return -2;
526
		}
527
		if (!$this->bind) {
528
			$this->error = "NotConnected";
529
			return -3;
530
		}
531
532
		// Encode to LDAP page code
533
		$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
534
		$newrdn = $this->convFromOutputCharset($newrdn, $this->ldapcharset);
535
		$newparent = $this->convFromOutputCharset($newparent, $this->ldapcharset);
536
537
		//print_r($info);
538
		$result = @ldap_rename($this->connection, $dn, $newrdn, $newparent, $deleteoldrdn);
539
540
		if ($result) {
541
			dol_syslog(get_class($this)."::rename successfull", LOG_DEBUG);
542
			return 1;
543
		} else {
544
			$this->error = @ldap_error($this->connection);
545
			dol_syslog(get_class($this)."::rename failed: ".$this->error, LOG_ERR);
546
			return -1;
547
		}
548
	}
549
550
	/**
551
	 *  Modify a LDAP entry (to use if dn != olddn)
552
	 *  Ldap object connect and bind must have been done
553
	 *
554
	 *  @param	string	$dn			DN entry key
555
	 *  @param	array	$info		Attributes array
556
	 *  @param	User		$user		Objet user that update
557
	 * 	@param	string	$olddn		Old DN entry key (before update)
558
	 * 	@param	string	$newrdn		New RDN entry key (uid=qqq) (for ldap_rename)
559
	 *	@param	string	$newparent	New parent (ou=xxx,dc=aaa,dc=bbb) (for ldap_rename)
560
	 *	@return	int					<0 if KO, >0 if OK
561
	 */
562
	public function update($dn, $info, $user, $olddn, $newrdn = false, $newparent = false)
563
	{
564
		dol_syslog(get_class($this)."::update dn=".$dn." olddn=".$olddn);
565
566
		// Check parameters
567
		if (!$this->connection) {
568
			$this->error = "NotConnected";
569
			return -2;
570
		}
571
		if (!$this->bind) {
572
			$this->error = "NotConnected";
573
			return -3;
574
		}
575
576
		if (!$olddn || $olddn != $dn) {
577
			if (!empty($olddn) && !empty($newrdn) && !empty($newparent) && $this->ldapProtocolVersion === '3') {
578
				// This function currently only works with LDAPv3
579
				$result = $this->rename($olddn, $newrdn, $newparent, $user, true);
580
				$result = $this->modify($dn, $info, $user); // We force "modify" for avoid some fields not modify
581
			} else {
582
				// If change we make is rename the key of LDAP record, we create new one and if ok, we delete old one.
583
				$result = $this->add($dn, $info, $user);
584
				if ($result > 0 && $olddn && $olddn != $dn) {
585
					$result = $this->delete($olddn); // If add fails, we do not try to delete old one
586
				}
587
			}
588
		} else {
589
			//$result = $this->delete($olddn);
590
			$result = $this->add($dn, $info, $user); // If record has been deleted from LDAP, we recreate it. We ignore error if it already exists.
591
			$result = $this->modify($dn, $info, $user); // We use add/modify instead of delete/add when olddn is received
592
		}
593
		if ($result <= 0) {
594
			$this->error = ldap_error($this->connection).' (Code '.ldap_errno($this->connection).") ".$this->error;
595
			dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
596
			//print_r($info);
597
			return -1;
598
		} else {
599
			dol_syslog(get_class($this)."::update done successfully");
600
			return 1;
601
		}
602
	}
603
604
605
	/**
606
	 * 	Delete a LDAP entry
607
	 *	Ldap object connect and bind must have been done
608
	 *
609
	 *	@param	string	$dn			DN entry key
610
	 *	@return	int					<0 if KO, >0 if OK
611
	 */
612
	public function delete($dn)
613
	{
614
		dol_syslog(get_class($this)."::delete Delete LDAP entry dn=".$dn);
615
616
		// Check parameters
617
		if (!$this->connection) {
618
			$this->error = "NotConnected";
619
			return -2;
620
		}
621
		if (!$this->bind) {
622
			$this->error = "NotConnected";
623
			return -3;
624
		}
625
626
		// Encode to LDAP page code
627
		$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
628
629
		$result = @ldap_delete($this->connection, $dn);
630
631
		if ($result) {
632
			return 1;
633
		}
634
		return -1;
635
	}
636
637
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
638
	/**
639
	 * 	Build a LDAP message
640
	 *
641
	 *	@param	string		$dn			DN entry key
642
	 *	@param	array		$info		Attributes array
643
	 *	@return	string					Content of file
644
	 */
645
	public function dump_content($dn, $info)
646
	{
647
		// phpcs:enable
648
		$content = '';
649
650
		// Create file content
651
		if (preg_match('/^ldap/', $this->server[0])) {
652
			$target = "-H ".join(',', $this->server);
653
		} else {
654
			$target = "-h ".join(',', $this->server)." -p ".$this->serverPort;
655
		}
656
		$content .= "# ldapadd $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
657
		$content .= "# ldapmodify $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
658
		$content .= "# ldapdelete $target -c -v -D ".$this->searchUser." -W -f ldapinput.in\n";
659
		if (in_array('localhost', $this->server)) {
660
			$content .= "# If commands fails to connect, try without -h and -p\n";
661
		}
662
		$content .= "dn: ".$dn."\n";
663
		foreach ($info as $key => $value) {
664
			if (!is_array($value)) {
665
				$content .= "$key: $value\n";
666
			} else {
667
				foreach ($value as $valuevalue) {
668
					$content .= "$key: $valuevalue\n";
669
				}
670
			}
671
		}
672
		return $content;
673
	}
674
675
	/**
676
	 * 	Dump a LDAP message to ldapinput.in file
677
	 *
678
	 *	@param	string		$dn			DN entry key
679
	 *	@param	array		$info		Attributes array
680
	 *	@return	int						<0 if KO, >0 if OK
681
	 */
682
	public function dump($dn, $info)
683
	{
684
		global $conf;
685
686
		// Create content
687
		$content = $this->dump_content($dn, $info);
688
689
		//Create file
690
		$result = dol_mkdir($conf->ldap->dir_temp);
691
692
		$outputfile = $conf->ldap->dir_temp.'/ldapinput.in';
693
		$fp = fopen($outputfile, "w");
694
		if ($fp) {
695
			fputs($fp, $content);
696
			fclose($fp);
697
			if (!empty($conf->global->MAIN_UMASK)) {
698
				@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
699
			}
700
			return 1;
701
		} else {
702
			return -1;
703
		}
704
	}
705
706
	/**
707
	 * Ping a server before ldap_connect for avoid waiting
708
	 *
709
	 * @param string	$host		Server host or address
710
	 * @param int		$port		Server port (default 389)
711
	 * @param int		$timeout	Timeout in second (default 1s)
712
	 * @return boolean				true or false
713
	 */
714
	public function serverPing($host, $port = 389, $timeout = 1)
715
	{
716
		$regs = array();
717
		if (preg_match('/^ldaps:\/\/([^\/]+)\/?$/', $host, $regs)) {
718
			// Replace ldaps:// by ssl://
719
			$host = 'ssl://'.$regs[1];
720
		} elseif (preg_match('/^ldap:\/\/([^\/]+)\/?$/', $host, $regs)) {
721
			// Remove ldap://
722
			$host = $regs[1];
723
		}
724
725
		//var_dump($newhostforstream); var_dump($host); var_dump($port);
726
		//$host = 'ssl://ldap.test.local:636';
727
		//$port = 636;
728
729
		$errno = $errstr = 0;
730
		/*
731
		if ($methodtochecktcpconnect == 'socket') {
732
			Try to use socket_create() method.
733
			Method that use stream_context_create() works only on registered listed in stream stream_get_wrappers(): http, https, ftp, ...
734
		}
735
		*/
736
737
		// Use the method fsockopen to test tcp connect. No way to ignore ssl certificate errors with this method !
738
		$op = @fsockopen($host, $port, $errno, $errstr, $timeout);
739
740
		//var_dump($op);
741
		if (!$op) {
742
			return false; //DC is N/A
743
		} else {
744
			fclose($op); //explicitly close open socket connection
745
			return true; //DC is up & running, we can safely connect with ldap_connect
746
		}
747
	}
748
749
750
	// Attribute methods -----------------------------------------------------
751
752
	/**
753
	 * 	Add a LDAP attribute in entry
754
	 *	Ldap object connect and bind must have been done
755
	 *
756
	 *	@param	string		$dn			DN entry key
757
	 *	@param	array		$info		Attributes array
758
	 *	@param	User		$user		Objet user that create
759
	 *	@return	int						<0 if KO, >0 if OK
760
	 */
761
	public function addAttribute($dn, $info, $user)
762
	{
763
		dol_syslog(get_class($this)."::addAttribute dn=".$dn." info=".join(',', $info));
764
765
		// Check parameters
766
		if (!$this->connection) {
767
			$this->error = "NotConnected";
768
			return -2;
769
		}
770
		if (!$this->bind) {
771
			$this->error = "NotConnected";
772
			return -3;
773
		}
774
775
		// Encode to LDAP page code
776
		$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
777
		foreach ($info as $key => $val) {
778
			if (!is_array($val)) {
779
				$info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
780
			}
781
		}
782
783
		$this->dump($dn, $info);
784
785
		//print_r($info);
786
		$result = @ldap_mod_add($this->connection, $dn, $info);
787
788
		if ($result) {
789
			dol_syslog(get_class($this)."::add_attribute successfull", LOG_DEBUG);
790
			return 1;
791
		} else {
792
			$this->error = @ldap_error($this->connection);
793
			dol_syslog(get_class($this)."::add_attribute failed: ".$this->error, LOG_ERR);
794
			return -1;
795
		}
796
	}
797
798
	/**
799
	 * 	Update a LDAP attribute in entry
800
	 *	Ldap object connect and bind must have been done
801
	 *
802
	 *	@param	string		$dn			DN entry key
803
	 *	@param	array		$info		Attributes array
804
	 *	@param	User		$user		Objet user that create
805
	 *	@return	int						<0 if KO, >0 if OK
806
	 */
807
	public function updateAttribute($dn, $info, $user)
808
	{
809
		dol_syslog(get_class($this)."::updateAttribute dn=".$dn." info=".join(',', $info));
810
811
		// Check parameters
812
		if (!$this->connection) {
813
			$this->error = "NotConnected";
814
			return -2;
815
		}
816
		if (!$this->bind) {
817
			$this->error = "NotConnected";
818
			return -3;
819
		}
820
821
		// Encode to LDAP page code
822
		$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
823
		foreach ($info as $key => $val) {
824
			if (!is_array($val)) {
825
				$info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
826
			}
827
		}
828
829
		$this->dump($dn, $info);
830
831
		//print_r($info);
832
		$result = @ldap_mod_replace($this->connection, $dn, $info);
833
834
		if ($result) {
835
			dol_syslog(get_class($this)."::updateAttribute successfull", LOG_DEBUG);
836
			return 1;
837
		} else {
838
			$this->error = @ldap_error($this->connection);
839
			dol_syslog(get_class($this)."::updateAttribute failed: ".$this->error, LOG_ERR);
840
			return -1;
841
		}
842
	}
843
844
	/**
845
	 * 	Delete a LDAP attribute in entry
846
	 *	Ldap object connect and bind must have been done
847
	 *
848
	 *	@param	string		$dn			DN entry key
849
	 *	@param	array		$info		Attributes array
850
	 *	@param	User		$user		Objet user that create
851
	 *	@return	int						<0 if KO, >0 if OK
852
	 */
853
	public function deleteAttribute($dn, $info, $user)
854
	{
855
		dol_syslog(get_class($this)."::deleteAttribute dn=".$dn." info=".join(',', $info));
856
857
		// Check parameters
858
		if (!$this->connection) {
859
			$this->error = "NotConnected";
860
			return -2;
861
		}
862
		if (!$this->bind) {
863
			$this->error = "NotConnected";
864
			return -3;
865
		}
866
867
		// Encode to LDAP page code
868
		$dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
869
		foreach ($info as $key => $val) {
870
			if (!is_array($val)) {
871
				$info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
872
			}
873
		}
874
875
		$this->dump($dn, $info);
876
877
		//print_r($info);
878
		$result = @ldap_mod_del($this->connection, $dn, $info);
879
880
		if ($result) {
881
			dol_syslog(get_class($this)."::deleteAttribute successfull", LOG_DEBUG);
882
			return 1;
883
		} else {
884
			$this->error = @ldap_error($this->connection);
885
			dol_syslog(get_class($this)."::deleteAttribute failed: ".$this->error, LOG_ERR);
886
			return -1;
887
		}
888
	}
889
890
	/**
891
	 *  Returns an array containing attributes and values for first record
892
	 *
893
	 *	@param	string	$dn			DN entry key
894
	 *	@param	string	$filter		Filter
895
	 *	@return	int|array			<0 or false if KO, array if OK
896
	 */
897
	public function getAttribute($dn, $filter)
898
	{
899
		// Check parameters
900
		if (!$this->connection) {
901
			$this->error = "NotConnected";
902
			return -2;
903
		}
904
		if (!$this->bind) {
905
			$this->error = "NotConnected";
906
			return -3;
907
		}
908
909
		$search = ldap_search($this->connection, $dn, $filter);
910
911
		// Only one entry should ever be returned
912
		$entry = ldap_first_entry($this->connection, $search);
913
914
		if (!$entry) {
915
			$this->ldapErrorCode = -1;
916
			$this->ldapErrorText = "Couldn't find entry";
917
			return 0; // Couldn't find entry...
918
		}
919
920
		// Get values
921
		if (!($values = ldap_get_attributes($this->connection, $entry))) {
922
			$this->ldapErrorCode = ldap_errno($this->connection);
923
			$this->ldapErrorText = ldap_error($this->connection);
924
			return 0; // No matching attributes
925
		}
926
927
		// Return an array containing the attributes.
928
		return $values;
929
	}
930
931
	/**
932
	 *  Returns an array containing values for an attribute and for first record matching filterrecord
933
	 *
934
	 * 	@param	string	$filterrecord		Record
935
	 * 	@param	string	$attribute			Attributes
936
	 * 	@return void
937
	 */
938
	public function getAttributeValues($filterrecord, $attribute)
939
	{
940
		$attributes = array();
941
		$attributes[0] = $attribute;
942
943
		// We need to search for this user in order to get their entry.
944
		$this->result = @ldap_search($this->connection, $this->people, $filterrecord, $attributes);
945
946
		// Pourquoi cette ligne ?
947
		//$info = ldap_get_entries($this->connection, $this->result);
948
949
		// Only one entry should ever be returned (no user will have the same uid)
950
		$entry = ldap_first_entry($this->connection, $this->result);
951
952
		if (!$entry) {
953
			$this->ldapErrorCode = -1;
954
			$this->ldapErrorText = "Couldn't find user";
955
			return false; // Couldn't find the user...
956
		}
957
958
		// Get values
959
		if (!$values = @ldap_get_values($this->connection, $entry, $attribute)) {
960
			$this->ldapErrorCode = ldap_errno($this->connection);
961
			$this->ldapErrorText = ldap_error($this->connection);
962
			return false; // No matching attributes
963
		}
964
965
		// Return an array containing the attributes.
966
		return $values;
967
	}
968
969
	/**
970
	 * 	Returns an array containing a details or list of LDAP record(s)
971
	 * 	ldapsearch -LLLx -hlocalhost -Dcn=admin,dc=parinux,dc=org -w password -b "ou=adherents,ou=people,dc=parinux,dc=org" userPassword
972
	 *
973
	 *	@param	string	$search			 	Value of field to search, '*' for all. Not used if $activefilter is set.
974
	 *	@param	string	$userDn			 	DN (Ex: ou=adherents,ou=people,dc=parinux,dc=org)
975
	 *	@param	string	$useridentifier 	Name of key field (Ex: uid)
976
	 *	@param	array	$attributeArray 	Array of fields required. Note this array must also contains field $useridentifier (Ex: sn,userPassword)
977
	 *	@param	int		$activefilter		'1' or 'user'=use field this->filter as filter instead of parameter $search, 'group'=use field this->filtergroup as filter, 'member'=use field this->filtermember as filter
978
	 *	@param	array	$attributeAsArray 	Array of fields wanted as an array not a string
979
	 *	@return	array						Array of [id_record][ldap_field]=value
980
	 */
981
	public function getRecords($search, $userDn, $useridentifier, $attributeArray, $activefilter = 0, $attributeAsArray = array())
982
	{
983
		$fulllist = array();
984
985
		dol_syslog(get_class($this)."::getRecords search=".$search." userDn=".$userDn." useridentifier=".$useridentifier." attributeArray=array(".join(',', $attributeArray).") activefilter=".$activefilter);
986
987
		// if the directory is AD, then bind first with the search user first
988
		if ($this->serverType == "activedirectory") {
989
			$this->bindauth($this->searchUser, $this->searchPassword);
990
			dol_syslog(get_class($this)."::bindauth serverType=activedirectory searchUser=".$this->searchUser);
991
		}
992
993
		// Define filter
994
		if (!empty($activefilter)) {	// Use a predefined trusted filter (defined into setup by admin).
995
			if (((string) $activefilter == '1' || (string) $activefilter == 'user') && $this->filter) {
996
				$filter = '('.$this->filter.')';
997
			} elseif (((string) $activefilter == 'group') && $this->filtergroup ) {
998
				$filter = '('.$this->filtergroup.')';
999
			} elseif (((string) $activefilter == 'member') && $this->filter) {
1000
				$filter = '('.$this->filtermember.')';
1001
			} else {
1002
				// If this->filter/this->filtergroup is empty, make fiter on * (all)
1003
				$filter = '('.ldap_escape($useridentifier, '', LDAP_ESCAPE_FILTER).'=*)';
1004
			}
1005
		} else {						// Use a filter forged using the $search value
1006
			$filter = '('.ldap_escape($useridentifier, '', LDAP_ESCAPE_FILTER).'='.ldap_escape($search, '', LDAP_ESCAPE_FILTER).')';
1007
		}
1008
1009
		if (is_array($attributeArray)) {
1010
			// Return list with required fields
1011
			$attributeArray = array_values($attributeArray); // This is to force to have index reordered from 0 (not make ldap_search fails)
1012
			dol_syslog(get_class($this)."::getRecords connection=".$this->connection." userDn=".$userDn." filter=".$filter." attributeArray=(".join(',', $attributeArray).")");
1013
			//var_dump($attributeArray);
1014
			$this->result = @ldap_search($this->connection, $userDn, $filter, $attributeArray);
1015
		} else {
1016
			// Return list with fields selected by default
1017
			dol_syslog(get_class($this)."::getRecords connection=".$this->connection." userDn=".$userDn." filter=".$filter);
1018
			$this->result = @ldap_search($this->connection, $userDn, $filter);
1019
		}
1020
		if (!$this->result) {
1021
			$this->error = 'LDAP search failed: '.ldap_errno($this->connection)." ".ldap_error($this->connection);
1022
			return -1;
1023
		}
1024
1025
		$info = @ldap_get_entries($this->connection, $this->result);
1026
1027
		// Warning: Dans info, les noms d'attributs sont en minuscule meme si passe
1028
		// a ldap_search en majuscule !!!
1029
		//print_r($info);
1030
1031
		for ($i = 0; $i < $info["count"]; $i++) {
1032
			$recordid = $this->convToOutputCharset($info[$i][$useridentifier][0], $this->ldapcharset);
1033
			if ($recordid) {
1034
				//print "Found record with key $useridentifier=".$recordid."<br>\n";
1035
				$fulllist[$recordid][$useridentifier] = $recordid;
1036
1037
				// Add to the array for each attribute in my list
1038
				$num = count($attributeArray);
1039
				for ($j = 0; $j < $num; $j++) {
1040
					$keyattributelower = strtolower($attributeArray[$j]);
1041
					//print " Param ".$attributeArray[$j]."=".$info[$i][$keyattributelower][0]."<br>\n";
1042
1043
					//permet de recuperer le SID avec Active Directory
1044
					if ($this->serverType == "activedirectory" && $keyattributelower == "objectsid") {
1045
						$objectsid = $this->getObjectSid($recordid);
1046
						$fulllist[$recordid][$attributeArray[$j]] = $objectsid;
1047
					} else {
1048
						if (in_array($attributeArray[$j], $attributeAsArray) && is_array($info[$i][$keyattributelower])) {
1049
							$valueTab = array();
1050
							foreach ($info[$i][$keyattributelower] as $key => $value) {
1051
								$valueTab[$key] = $this->convToOutputCharset($value, $this->ldapcharset);
1052
							}
1053
							$fulllist[$recordid][$attributeArray[$j]] = $valueTab;
1054
						} else {
1055
							$fulllist[$recordid][$attributeArray[$j]] = $this->convToOutputCharset($info[$i][$keyattributelower][0], $this->ldapcharset);
1056
						}
1057
					}
1058
				}
1059
			}
1060
		}
1061
1062
		asort($fulllist);
1063
		return $fulllist;
1064
	}
1065
1066
	/**
1067
	 *  Converts a little-endian hex-number to one, that 'hexdec' can convert
1068
	 *	Required by Active Directory
1069
	 *
1070
	 *	@param	string		$hex			Hex value
1071
	 *	@return	string						Little endian
1072
	 */
1073
	public function littleEndian($hex)
1074
	{
1075
		$result = '';
1076
		for ($x = dol_strlen($hex) - 2; $x >= 0; $x = $x - 2) {
1077
			$result .= substr($hex, $x, 2);
1078
		}
1079
		return $result;
1080
	}
1081
1082
1083
	/**
1084
	 *  Recupere le SID de l'utilisateur
1085
	 *	Required by Active Directory
1086
	 *
1087
	 * 	@param	string		$ldapUser		Login de l'utilisateur
1088
	 * 	@return	string						Sid
1089
	 */
1090
	public function getObjectSid($ldapUser)
1091
	{
1092
		$criteria = '('.$this->getUserIdentifier().'='.$ldapUser.')';
1093
		$justthese = array("objectsid");
1094
1095
		// if the directory is AD, then bind first with the search user first
1096
		if ($this->serverType == "activedirectory") {
1097
			$this->bindauth($this->searchUser, $this->searchPassword);
1098
		}
1099
1100
		$i = 0;
1101
		$searchDN = $this->people;
1102
1103
		while ($i <= 2) {
1104
			$ldapSearchResult = @ldap_search($this->connection, $searchDN, $criteria, $justthese);
1105
1106
			if (!$ldapSearchResult) {
1107
				$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1108
				return -1;
1109
			}
1110
1111
			$entry = ldap_first_entry($this->connection, $ldapSearchResult);
1112
1113
			if (!$entry) {
1114
				// Si pas de resultat on cherche dans le domaine
1115
				$searchDN = $this->domain;
1116
				$i++;
1117
			} else {
1118
				$i++;
1119
				$i++;
1120
			}
1121
		}
1122
1123
		if ($entry) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $entry does not seem to be defined for all execution paths leading up to this point.
Loading history...
1124
			$ldapBinary = ldap_get_values_len($this->connection, $entry, "objectsid");
1125
			$SIDText = $this->binSIDtoText($ldapBinary[0]);
1126
			return $SIDText;
1127
		} else {
1128
			$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1129
			return '?';
1130
		}
1131
	}
1132
1133
	/**
1134
	 * Returns the textual SID
1135
	 * Indispensable pour Active Directory
1136
	 *
1137
	 * @param	string	$binsid		Binary SID
1138
	 * @return	string				Textual SID
1139
	 */
1140
	public function binSIDtoText($binsid)
1141
	{
1142
		$hex_sid = bin2hex($binsid);
1143
		$rev = hexdec(substr($hex_sid, 0, 2)); // Get revision-part of SID
1144
		$subcount = hexdec(substr($hex_sid, 2, 2)); // Get count of sub-auth entries
1145
		$auth = hexdec(substr($hex_sid, 4, 12)); // SECURITY_NT_AUTHORITY
1146
		$result = "$rev-$auth";
1147
		for ($x = 0; $x < $subcount; $x++) {
1148
			$result .= "-".hexdec($this->littleEndian(substr($hex_sid, 16 + ($x * 8), 8))); // get all SECURITY_NT_AUTHORITY
1149
		}
1150
		return $result;
1151
	}
1152
1153
1154
	/**
1155
	 * 	Fonction de recherche avec filtre
1156
	 *	this->connection doit etre defini donc la methode bind ou bindauth doit avoir deja ete appelee
1157
	 *	Ne pas utiliser pour recherche d'une liste donnee de proprietes
1158
	 *	car conflit majuscule-minuscule. A n'utiliser que pour les pages
1159
	 *	'Fiche LDAP' qui affiche champ lisibles par defaut.
1160
	 *
1161
	 * 	@param	string		$checkDn		DN de recherche (Ex: ou=users,cn=my-domain,cn=com)
1162
	 * 	@param 	string		$filter			Search filter (ex: (sn=nom_personne) )
1163
	 *	@return	array|int					Array with answers (key lowercased - value)
1164
	 */
1165
	public function search($checkDn, $filter)
1166
	{
1167
		dol_syslog(get_class($this)."::search checkDn=".$checkDn." filter=".$filter);
1168
1169
		$checkDn = $this->convFromOutputCharset($checkDn, $this->ldapcharset);
1170
		$filter = $this->convFromOutputCharset($filter, $this->ldapcharset);
1171
1172
		// if the directory is AD, then bind first with the search user first
1173
		if ($this->serverType == "activedirectory") {
1174
			$this->bindauth($this->searchUser, $this->searchPassword);
1175
		}
1176
1177
		$this->result = @ldap_search($this->connection, $checkDn, $filter);
1178
1179
		$result = @ldap_get_entries($this->connection, $this->result);
1180
		if (!$result) {
1181
			$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1182
			return -1;
1183
		} else {
1184
			ldap_free_result($this->result);
1185
			return $result;
1186
		}
1187
	}
1188
1189
1190
	/**
1191
	 * 		Load all attribute of a LDAP user
1192
	 *
1193
	 * 		@param	User	$user		User to search for. Not used if a filter is provided.
1194
	 *      @param  string	$filter		Filter for search. Must start with &.
1195
	 *                       	       	Examples: &(objectClass=inetOrgPerson) &(objectClass=user)(objectCategory=person) &(isMemberOf=cn=Sales,ou=Groups,dc=opencsi,dc=com)
1196
	 *		@return	int					>0 if OK, <0 if KO
1197
	 */
1198
	public function fetch($user, $filter)
1199
	{
1200
		// Perform the search and get the entry handles
1201
1202
		// if the directory is AD, then bind first with the search user first
1203
		if ($this->serverType == "activedirectory") {
1204
			$this->bindauth($this->searchUser, $this->searchPassword);
1205
		}
1206
1207
		$searchDN = $this->people; // TODO Why searching in people then domain ?
1208
1209
		$result = '';
1210
		$i = 0;
1211
		while ($i <= 2) {
1212
			dol_syslog(get_class($this)."::fetch search with searchDN=".$searchDN." filter=".$filter);
1213
			$this->result = @ldap_search($this->connection, $searchDN, $filter);
1214
			if ($this->result) {
1215
				$result = @ldap_get_entries($this->connection, $this->result);
1216
				if ($result['count'] > 0) {
1217
					dol_syslog('Ldap::fetch search found '.$result['count'].' records');
1218
				} else {
1219
					dol_syslog('Ldap::fetch search returns but found no records');
1220
				}
1221
				//var_dump($result);exit;
1222
			} else {
1223
				$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1224
				dol_syslog(get_class($this)."::fetch search fails");
1225
				return -1;
1226
			}
1227
1228
			if (!$result) {
1229
				// Si pas de resultat on cherche dans le domaine
1230
				$searchDN = $this->domain;
1231
				$i++;
1232
			} else {
1233
				break;
1234
			}
1235
		}
1236
1237
		if (!$result) {
1238
			$this->error = ldap_errno($this->connection)." ".ldap_error($this->connection);
1239
			return -1;
1240
		} else {
1241
			$this->name       = $this->convToOutputCharset($result[0][$this->attr_name][0], $this->ldapcharset);
1242
			$this->firstname  = $this->convToOutputCharset($result[0][$this->attr_firstname][0], $this->ldapcharset);
1243
			$this->login      = $this->convToOutputCharset($result[0][$this->attr_login][0], $this->ldapcharset);
1244
			$this->phone      = $this->convToOutputCharset($result[0][$this->attr_phone][0], $this->ldapcharset);
1245
			$this->skype      = $this->convToOutputCharset($result[0][$this->attr_skype][0], $this->ldapcharset);
1246
			$this->fax        = $this->convToOutputCharset($result[0][$this->attr_fax][0], $this->ldapcharset);
1247
			$this->mail       = $this->convToOutputCharset($result[0][$this->attr_mail][0], $this->ldapcharset);
1248
			$this->mobile     = $this->convToOutputCharset($result[0][$this->attr_mobile][0], $this->ldapcharset);
1249
1250
			$this->uacf       = $this->parseUACF($this->convToOutputCharset($result[0]["useraccountcontrol"][0], $this->ldapcharset));
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $this->uacf is correct as $this->parseUACF($this->...], $this->ldapcharset)) targeting Ldap::parseUACF() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1251
			if (isset($result[0]["pwdlastset"][0])) {	// If expiration on password exists
1252
				$this->pwdlastset = ($result[0]["pwdlastset"][0] != 0) ? $this->convert_time($this->convToOutputCharset($result[0]["pwdlastset"][0], $this->ldapcharset)) : 0;
1253
			} else {
1254
				$this->pwdlastset = -1;
1255
			}
1256
			if (!$this->name && !$this->login) {
1257
				$this->pwdlastset = -1;
1258
			}
1259
			$this->badpwdtime = $this->convert_time($this->convToOutputCharset($result[0]["badpasswordtime"][0], $this->ldapcharset));
1260
1261
			// FQDN domain
1262
			$domain = str_replace('dc=', '', $this->domain);
1263
			$domain = str_replace(',', '.', $domain);
1264
			$this->domainFQDN = $domain;
1265
1266
			// Set ldapUserDn (each user can have a different dn)
1267
			//var_dump($result[0]);exit;
1268
			$this->ldapUserDN = $result[0]['dn'];
1269
1270
			ldap_free_result($this->result);
1271
			return 1;
1272
		}
1273
	}
1274
1275
1276
	// helper methods
1277
1278
	/**
1279
	 * 	Returns the correct user identifier to use, based on the ldap server type
1280
	 *
1281
	 *	@return	string 				Login
1282
	 */
1283
	public function getUserIdentifier()
1284
	{
1285
		if ($this->serverType == "activedirectory") {
1286
			return $this->attr_sambalogin;
1287
		} else {
1288
			return $this->attr_login;
1289
		}
1290
	}
1291
1292
	/**
1293
	 * 	UserAccountControl Flgs to more human understandable form...
1294
	 *
1295
	 *	@param	string		$uacf		UACF
1296
	 *	@return	void
1297
	 */
1298
	public function parseUACF($uacf)
1299
	{
1300
		//All flags array
1301
		$flags = array(
1302
			"TRUSTED_TO_AUTH_FOR_DELEGATION"  =>    16777216,
1303
			"PASSWORD_EXPIRED"                =>    8388608,
1304
			"DONT_REQ_PREAUTH"                =>    4194304,
1305
			"USE_DES_KEY_ONLY"                =>    2097152,
1306
			"NOT_DELEGATED"                   =>    1048576,
1307
			"TRUSTED_FOR_DELEGATION"          =>    524288,
1308
			"SMARTCARD_REQUIRED"              =>    262144,
1309
			"MNS_LOGON_ACCOUNT"               =>    131072,
1310
			"DONT_EXPIRE_PASSWORD"            =>    65536,
1311
			"SERVER_TRUST_ACCOUNT"            =>    8192,
1312
			"WORKSTATION_TRUST_ACCOUNT"       =>    4096,
1313
			"INTERDOMAIN_TRUST_ACCOUNT"       =>    2048,
1314
			"NORMAL_ACCOUNT"                  =>    512,
1315
			"TEMP_DUPLICATE_ACCOUNT"          =>    256,
1316
			"ENCRYPTED_TEXT_PWD_ALLOWED"      =>    128,
1317
			"PASSWD_CANT_CHANGE"              =>    64,
1318
			"PASSWD_NOTREQD"                  =>    32,
1319
			"LOCKOUT"                         =>    16,
1320
			"HOMEDIR_REQUIRED"                =>    8,
1321
			"ACCOUNTDISABLE"                  =>    2,
1322
			"SCRIPT"                          =>    1
1323
		);
1324
1325
		//Parse flags to text
1326
		$retval = array();
1327
		//while (list($flag, $val) = each($flags)) {
1328
		foreach ($flags as $flag => $val) {
1329
			if ($uacf >= $val) {
1330
				$uacf -= $val;
1331
				$retval[$val] = $flag;
1332
			}
1333
		}
1334
1335
		//Return human friendly flags
1336
		return($retval);
1337
	}
1338
1339
	/**
1340
	 * 	SamAccountType value to text
1341
	 *
1342
	 *	@param	string	$samtype	SamType
1343
	 *	@return	string				Sam string
1344
	 */
1345
	public function parseSAT($samtype)
1346
	{
1347
		$stypes = array(
1348
			805306368    =>    "NORMAL_ACCOUNT",
1349
			805306369    =>    "WORKSTATION_TRUST",
1350
			805306370    =>    "INTERDOMAIN_TRUST",
1351
			268435456    =>    "SECURITY_GLOBAL_GROUP",
1352
			268435457    =>    "DISTRIBUTION_GROUP",
1353
			536870912    =>    "SECURITY_LOCAL_GROUP",
1354
			536870913    =>    "DISTRIBUTION_LOCAL_GROUP"
1355
		);
1356
1357
		$retval = "";
1358
		while (list($sat, $val) = each($stypes)) {
1359
			if ($samtype == $sat) {
1360
				$retval = $val;
1361
				break;
1362
			}
1363
		}
1364
		if (empty($retval)) {
1365
			$retval = "UNKNOWN_TYPE_".$samtype;
1366
		}
1367
1368
		return($retval);
1369
	}
1370
1371
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1372
	/**
1373
	 *	Convertit le temps ActiveDirectory en Unix timestamp
1374
	 *
1375
	 *	@param	string	$value		AD time to convert
1376
	 *	@return	integer				Unix timestamp
1377
	 */
1378
	public function convert_time($value)
1379
	{
1380
		// phpcs:enable
1381
		$dateLargeInt = $value; // nano secondes depuis 1601 !!!!
1382
		$secsAfterADEpoch = $dateLargeInt / (10000000); // secondes depuis le 1 jan 1601
1383
		$ADToUnixConvertor = ((1970 - 1601) * 365.242190) * 86400; // UNIX start date - AD start date * jours * secondes
1384
		$unixTimeStamp = intval($secsAfterADEpoch - $ADToUnixConvertor); // Unix time stamp
1385
		return $unixTimeStamp;
1386
	}
1387
1388
1389
	/**
1390
	 *  Convert a string into output/memory charset
1391
	 *
1392
	 *  @param	string	$str            String to convert
1393
	 *  @param	string	$pagecodefrom	Page code of src string
1394
	 *  @return string         			Converted string
1395
	 */
1396
	private function convToOutputCharset($str, $pagecodefrom = 'UTF-8')
1397
	{
1398
		global $conf;
1399
		if ($pagecodefrom == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8') {
1400
			$str = utf8_encode($str);
1401
		}
1402
		if ($pagecodefrom == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1') {
1403
			$str = utf8_decode($str);
1404
		}
1405
		return $str;
1406
	}
1407
1408
	/**
1409
	 *  Convert a string from output/memory charset
1410
	 *
1411
	 *  @param	string	$str            String to convert
1412
	 *  @param	string	$pagecodeto		Page code for result string
1413
	 *  @return string         			Converted string
1414
	 */
1415
	public function convFromOutputCharset($str, $pagecodeto = 'UTF-8')
1416
	{
1417
		global $conf;
1418
		if ($pagecodeto == 'ISO-8859-1' && $conf->file->character_set_client == 'UTF-8') {
1419
			$str = utf8_decode($str);
1420
		}
1421
		if ($pagecodeto == 'UTF-8' && $conf->file->character_set_client == 'ISO-8859-1') {
1422
			$str = utf8_encode($str);
1423
		}
1424
		return $str;
1425
	}
1426
1427
1428
	/**
1429
	 *	Return available value of group GID
1430
	 *
1431
	 *	@param	string	$keygroup	Key of group
1432
	 *	@return	int					gid number
1433
	 */
1434
	public function getNextGroupGid($keygroup = 'LDAP_KEY_GROUPS')
1435
	{
1436
		global $conf;
1437
1438
		if (empty($keygroup)) {
1439
			$keygroup = 'LDAP_KEY_GROUPS';
1440
		}
1441
1442
		$search = '('.$conf->global->$keygroup.'=*)';
1443
		$result = $this->search($this->groups, $search);
1444
		if ($result) {
1445
			$c = $result['count'];
1446
			$gids = array();
1447
			for ($i = 0; $i < $c; $i++) {
1448
				$gids[] = $result[$i]['gidnumber'][0];
1449
			}
1450
			rsort($gids);
1451
1452
			return $gids[0] + 1;
1453
		}
1454
1455
		return 0;
1456
	}
1457
}
1458