sync_users_ldap2dolibarr.php 9.9 KB

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