sync_users_ldap2dolibarr.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. #!/usr/bin/env php
  2. <?php
  3. /**
  4. * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  5. * Copyright (C) 2006-2012 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. */
  20. /**
  21. * \file scripts/user/sync_users_ldap2dolibarr.php
  22. * \ingroup ldap member
  23. * \brief Script to update users into Dolibarr from LDAP
  24. */
  25. if (!defined('NOSESSION')) {
  26. define('NOSESSION', '1');
  27. }
  28. $sapi_type = php_sapi_name();
  29. $script_file = basename(__FILE__);
  30. $path = __DIR__.'/';
  31. // Test if batch mode
  32. if (substr($sapi_type, 0, 3) == 'cgi') {
  33. echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
  34. exit(-1);
  35. }
  36. require_once $path."../../htdocs/master.inc.php";
  37. require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php";
  38. require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php";
  39. require_once DOL_DOCUMENT_ROOT."/user/class/user.class.php";
  40. $langs->loadLangs(array("main", "errors"));
  41. // Global variables
  42. $version = DOL_VERSION;
  43. $error = 0;
  44. $forcecommit = 0;
  45. $excludeuser = array();
  46. $confirmed = 0;
  47. /*
  48. * Main
  49. */
  50. @set_time_limit(0);
  51. print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
  52. dol_syslog($script_file." launched with arg ".join(',', $argv));
  53. // List of fields to get from LDAP
  54. $required_fields = array(
  55. $conf->global->LDAP_KEY_USERS,
  56. $conf->global->LDAP_FIELD_FULLNAME,
  57. $conf->global->LDAP_FIELD_NAME,
  58. $conf->global->LDAP_FIELD_FIRSTNAME,
  59. $conf->global->LDAP_FIELD_LOGIN,
  60. $conf->global->LDAP_FIELD_LOGIN_SAMBA,
  61. $conf->global->LDAP_FIELD_PASSWORD,
  62. $conf->global->LDAP_FIELD_PASSWORD_CRYPTED,
  63. $conf->global->LDAP_FIELD_PHONE,
  64. $conf->global->LDAP_FIELD_FAX,
  65. $conf->global->LDAP_FIELD_MOBILE,
  66. // $conf->global->LDAP_FIELD_ADDRESS,
  67. // $conf->global->LDAP_FIELD_ZIP,
  68. // $conf->global->LDAP_FIELD_TOWN,
  69. // $conf->global->LDAP_FIELD_COUNTRY,
  70. $conf->global->LDAP_FIELD_MAIL,
  71. $conf->global->LDAP_FIELD_TITLE,
  72. $conf->global->LDAP_FIELD_DESCRIPTION,
  73. $conf->global->LDAP_FIELD_SID
  74. );
  75. // Remove from required_fields all entries not configured in LDAP (empty) and duplicated
  76. $required_fields = array_unique(array_values(array_filter($required_fields, "dolValidElement")));
  77. if (!isset($argv[1])) {
  78. print "Usage: $script_file (nocommitiferror|commitiferror) [--server=ldapserverhost] [--excludeuser=user1,user2...] [-y]\n";
  79. exit(-1);
  80. }
  81. foreach ($argv as $key => $val) {
  82. if ($val == 'commitiferror') {
  83. $forcecommit = 1;
  84. }
  85. if (preg_match('/--server=([^\s]+)$/', $val, $reg)) {
  86. $conf->global->LDAP_SERVER_HOST = $reg[1];
  87. }
  88. if (preg_match('/--excludeuser=([^\s]+)$/', $val, $reg)) {
  89. $excludeuser = explode(',', $reg[1]);
  90. }
  91. if (preg_match('/-y$/', $val, $reg)) {
  92. $confirmed = 1;
  93. }
  94. }
  95. print "Mails sending disabled (useless in batch mode)\n";
  96. $conf->global->MAIN_DISABLE_ALL_MAILS = 1; // On bloque les mails
  97. print "\n";
  98. print "----- Synchronize all records from LDAP database:\n";
  99. print "host=".$conf->global->LDAP_SERVER_HOST."\n";
  100. print "port=".$conf->global->LDAP_SERVER_PORT."\n";
  101. print "login=".$conf->global->LDAP_ADMIN_DN."\n";
  102. print "pass=".preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)."\n";
  103. print "DN to extract=".$conf->global->LDAP_USER_DN."\n";
  104. if (!empty($conf->global->LDAP_FILTER_CONNECTION)) {
  105. print 'Filter=('.$conf->global->LDAP_FILTER_CONNECTION.')'."\n"; // Note: filter is defined into function getRecords
  106. } else {
  107. print 'Filter=('.$conf->global->LDAP_KEY_USERS.'=*)'."\n";
  108. }
  109. print "----- To Dolibarr database:\n";
  110. print "type=".$conf->db->type."\n";
  111. print "host=".$conf->db->host."\n";
  112. print "port=".$conf->db->port."\n";
  113. print "login=".$conf->db->user."\n";
  114. print "database=".$conf->db->name."\n";
  115. print "----- Options:\n";
  116. print "commitiferror=".$forcecommit."\n";
  117. print "excludeuser=".join(',', $excludeuser)."\n";
  118. print "Mapped LDAP fields=".join(',', $required_fields)."\n";
  119. print "\n";
  120. if (!$confirmed) {
  121. print "Hit Enter to continue or CTRL+C to stop...\n";
  122. $input = trim(fgets(STDIN));
  123. }
  124. if (empty($conf->global->LDAP_USER_DN)) {
  125. print $langs->trans("Error").': '.$langs->trans("LDAP setup for users not defined inside Dolibarr");
  126. exit(-1);
  127. }
  128. // Load table of correspondence of countries
  129. $hashlib2rowid = array();
  130. $countries = array();
  131. $sql = "SELECT rowid, code, label, active";
  132. $sql .= " FROM ".MAIN_DB_PREFIX."c_country";
  133. $sql .= " WHERE active = 1";
  134. $sql .= " ORDER BY code ASC";
  135. $resql = $db->query($sql);
  136. if ($resql) {
  137. $num = $db->num_rows($resql);
  138. $i = 0;
  139. if ($num) {
  140. while ($i < $num) {
  141. $obj = $db->fetch_object($resql);
  142. if ($obj) {
  143. // print 'Load cache for country '.strtolower($obj->label).' rowid='.$obj->rowid."\n";
  144. $hashlib2rowid[strtolower($obj->label)] = $obj->rowid;
  145. $countries[$obj->rowid] = array('rowid' => $obj->rowid, 'label' => $obj->label, 'code' => $obj->code);
  146. }
  147. $i++;
  148. }
  149. }
  150. } else {
  151. dol_print_error($db);
  152. exit(-1);
  153. }
  154. $ldap = new Ldap();
  155. $result = $ldap->connect_bind();
  156. if ($result >= 0) {
  157. $justthese = array();
  158. // We disable synchro Dolibarr-LDAP
  159. $conf->global->LDAP_SYNCHRO_ACTIVE = 0;
  160. $ldaprecords = $ldap->getRecords('*', $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, $required_fields, 'user'); // Fiter on 'user' filter param
  161. if (is_array($ldaprecords)) {
  162. $db->begin();
  163. // Warning $ldapuser has a key in lowercase
  164. foreach ($ldaprecords as $key => $ldapuser) {
  165. // If login into exclude list, we discard record
  166. if (in_array($ldapuser[$conf->global->LDAP_FIELD_LOGIN], $excludeuser)) {
  167. print $langs->transnoentities("UserDiscarded").' # '.$key.': login='.$ldapuser[$conf->global->LDAP_FIELD_LOGIN].' --> Discarded'."\n";
  168. continue;
  169. }
  170. $fuser = new User($db);
  171. if ($conf->global->LDAP_KEY_USERS == $conf->global->LDAP_FIELD_SID) {
  172. $fuser->fetch('', '', $ldapuser[$conf->global->LDAP_KEY_USERS]); // Chargement du user concerné par le SID
  173. } elseif ($conf->global->LDAP_KEY_USERS == $conf->global->LDAP_FIELD_LOGIN) {
  174. $fuser->fetch('', $ldapuser[$conf->global->LDAP_KEY_USERS]); // Chargement du user concerné par le login
  175. }
  176. // Propriete membre
  177. $fuser->firstname = $ldapuser[$conf->global->LDAP_FIELD_FIRSTNAME];
  178. $fuser->lastname = $ldapuser[$conf->global->LDAP_FIELD_NAME];
  179. $fuser->login = $ldapuser[$conf->global->LDAP_FIELD_LOGIN];
  180. $fuser->pass = $ldapuser[$conf->global->LDAP_FIELD_PASSWORD];
  181. $fuser->pass_indatabase_crypted = $ldapuser[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED];
  182. // $user->societe;
  183. /*
  184. * $fuser->address=$ldapuser[$conf->global->LDAP_FIELD_ADDRESS];
  185. * $fuser->zip=$ldapuser[$conf->global->LDAP_FIELD_ZIP];
  186. * $fuser->town=$ldapuser[$conf->global->LDAP_FIELD_TOWN];
  187. * $fuser->country=$ldapuser[$conf->global->LDAP_FIELD_COUNTRY];
  188. * $fuser->country_id=$countries[$hashlib2rowid[strtolower($fuser->country)]]['rowid'];
  189. * $fuser->country_code=$countries[$hashlib2rowid[strtolower($fuser->country)]]['code'];
  190. */
  191. $fuser->office_phone = $ldapuser[$conf->global->LDAP_FIELD_PHONE];
  192. $fuser->user_mobile = $ldapuser[$conf->global->LDAP_FIELD_MOBILE];
  193. $fuser->office_fax = $ldapuser[$conf->global->LDAP_FIELD_FAX];
  194. $fuser->email = $ldapuser[$conf->global->LDAP_FIELD_MAIL];
  195. $fuser->ldap_sid = $ldapuser[$conf->global->LDAP_FIELD_SID];
  196. $fuser->job = $ldapuser[$conf->global->LDAP_FIELD_TITLE];
  197. $fuser->note = $ldapuser[$conf->global->LDAP_FIELD_DESCRIPTION];
  198. $fuser->admin = 0;
  199. $fuser->socid = 0;
  200. $fuser->contact_id = 0;
  201. $fuser->fk_member = 0;
  202. $fuser->statut = 1;
  203. // TODO : revoir la gestion du status
  204. /*
  205. * if (isset($ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS]))
  206. * {
  207. * $fuser->datec=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
  208. * $fuser->datevalid=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
  209. * $fuser->statut=$ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS];
  210. * }
  211. */
  212. // if ($fuser->statut > 1) $fuser->statut=1;
  213. // print_r($ldapuser);
  214. if ($fuser->id > 0) { // User update
  215. print $langs->transnoentities("UserUpdate").' # '.$key.': login='.$fuser->login.', fullname='.$fuser->getFullName($langs);
  216. $res = $fuser->update($user);
  217. if ($res < 0) {
  218. $error++;
  219. print ' --> '.$res.' '.$fuser->error;
  220. } else {
  221. print ' --> Updated user id='.$fuser->id.' login='.$fuser->login;
  222. }
  223. } else { // User creation
  224. print $langs->transnoentities("UserCreate").' # '.$key.': login='.$fuser->login.', fullname='.$fuser->getFullName($langs);
  225. $res = $fuser->create($user);
  226. if ($res > 0) {
  227. print ' --> Created user id='.$fuser->id.' login='.$fuser->login;
  228. } else {
  229. $error++;
  230. print ' --> '.$res.' '.$fuser->error;
  231. }
  232. }
  233. print "\n";
  234. // print_r($fuser);
  235. // Gestion des groupes
  236. // TODO : revoir la gestion des groupes (ou script de sync groupes)
  237. /*
  238. * if(!$error) {
  239. * foreach ($ldapuser[$conf->global->LDAP_FIELD_USERGROUPS] as $groupdn) {
  240. * $groupdn;
  241. * }
  242. * }
  243. */
  244. }
  245. if (!$error || $forcecommit) {
  246. if (!$error) {
  247. print $langs->transnoentities("NoErrorCommitIsDone")."\n";
  248. } else {
  249. print $langs->transnoentities("ErrorButCommitIsDone")."\n";
  250. }
  251. $db->commit();
  252. } else {
  253. print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n";
  254. $db->rollback();
  255. }
  256. print "\n";
  257. } else {
  258. dol_print_error('', $ldap->error);
  259. $error++;
  260. }
  261. } else {
  262. dol_print_error('', $ldap->error);
  263. $error++;
  264. }
  265. exit($error);
  266. /**
  267. * Function to say if a value is empty or not
  268. *
  269. * @param string $element Value to test
  270. * @return boolean True of false
  271. */
  272. function dolValidElement($element)
  273. {
  274. return (trim($element) != '');
  275. }