ldap.class.php 45 KB

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