sync_members_ldap2dolibarr.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. #!/usr/bin/env php
  2. <?php
  3. /**
  4. * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  5. * Copyright (C) 2006-2015 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/members/sync_members_ldap2dolibarr.php
  22. * \ingroup ldap member
  23. * \brief Script de mise a jour des adherents dans Dolibarr depuis 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."/adherents/class/adherent.class.php";
  40. require_once DOL_DOCUMENT_ROOT."/adherents/class/subscription.class.php";
  41. $langs->loadLangs(array("main", "errors"));
  42. // Global variables
  43. $version = constant('DOL_VERSION');
  44. $error = 0;
  45. $forcecommit = 0;
  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_MEMBERS,
  56. $conf->global->LDAP_FIELD_FULLNAME,
  57. $conf->global->LDAP_FIELD_LOGIN,
  58. $conf->global->LDAP_FIELD_LOGIN_SAMBA,
  59. $conf->global->LDAP_FIELD_PASSWORD,
  60. $conf->global->LDAP_FIELD_PASSWORD_CRYPTED,
  61. $conf->global->LDAP_FIELD_NAME,
  62. $conf->global->LDAP_FIELD_FIRSTNAME,
  63. $conf->global->LDAP_FIELD_MAIL,
  64. $conf->global->LDAP_FIELD_PHONE,
  65. $conf->global->LDAP_FIELD_PHONE_PERSO,
  66. $conf->global->LDAP_FIELD_MOBILE,
  67. $conf->global->LDAP_FIELD_FAX,
  68. $conf->global->LDAP_FIELD_ADDRESS,
  69. $conf->global->LDAP_FIELD_ZIP,
  70. $conf->global->LDAP_FIELD_TOWN,
  71. $conf->global->LDAP_FIELD_COUNTRY,
  72. $conf->global->LDAP_FIELD_DESCRIPTION,
  73. $conf->global->LDAP_FIELD_BIRTHDATE,
  74. $conf->global->LDAP_FIELD_MEMBER_STATUS,
  75. $conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION,
  76. // Subscriptions
  77. $conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE,
  78. $conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT,
  79. $conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE,
  80. $conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT
  81. );
  82. // Remove from required_fields all entries not configured in LDAP (empty) and duplicated
  83. $required_fields = array_unique(array_values(array_filter($required_fields, "dolValidElement")));
  84. if (!isset($argv[2]) || !is_numeric($argv[2])) {
  85. print "Usage: $script_file (nocommitiferror|commitiferror) id_member_type [--server=ldapserverhost] [-y]\n";
  86. exit(-1);
  87. }
  88. $typeid = $argv[2];
  89. foreach ($argv as $key => $val) {
  90. if ($val == 'commitiferror') {
  91. $forcecommit = 1;
  92. }
  93. if (preg_match('/--server=([^\s]+)$/', $val, $reg)) {
  94. $conf->global->LDAP_SERVER_HOST = $reg[1];
  95. }
  96. if (preg_match('/-y$/', $val, $reg)) {
  97. $confirmed = 1;
  98. }
  99. }
  100. print "Mails sending disabled (useless in batch mode)\n";
  101. $conf->global->MAIN_DISABLE_ALL_MAILS = 1; // On bloque les mails
  102. print "\n";
  103. print "----- Synchronize all records from LDAP database:\n";
  104. print "host=".$conf->global->LDAP_SERVER_HOST."\n";
  105. print "port=".$conf->global->LDAP_SERVER_PORT."\n";
  106. print "login=".$conf->global->LDAP_ADMIN_DN."\n";
  107. print "pass=".preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)."\n";
  108. print "DN to extract=".$conf->global->LDAP_MEMBER_DN."\n";
  109. if (!empty($conf->global->LDAP_MEMBER_FILTER)) {
  110. print 'Filter=('.$conf->global->LDAP_MEMBER_FILTER.')'."\n"; // Note: filter is defined into function getRecords
  111. } else {
  112. print 'Filter=('.$conf->global->LDAP_KEY_MEMBERS.'=*)'."\n";
  113. }
  114. print "----- To Dolibarr database:\n";
  115. print "type=".$conf->db->type."\n";
  116. print "host=".$conf->db->host."\n";
  117. print "port=".$conf->db->port."\n";
  118. print "login=".$conf->db->user."\n";
  119. print "database=".$conf->db->name."\n";
  120. print "----- Options:\n";
  121. print "commitiferror=".$forcecommit."\n";
  122. print "Mapped LDAP fields=".join(',', $required_fields)."\n";
  123. print "\n";
  124. // Check parameters
  125. if (empty($conf->global->LDAP_MEMBER_DN)) {
  126. print $langs->trans("Error").': '.$langs->trans("LDAP setup for members not defined inside Dolibarr")."\n";
  127. exit(-1);
  128. }
  129. if ($typeid <= 0) {
  130. print $langs->trans("Error").': Parameter id_member_type is not a valid ref of an existing member type'."\n";
  131. exit(-2);
  132. }
  133. if (!empty($dolibarr_main_db_readonly)) {
  134. print "Error: instance in read-onyl mode\n";
  135. exit(-1);
  136. }
  137. if (!$confirmed) {
  138. print "Hit Enter to continue or CTRL+C to stop...\n";
  139. $input = trim(fgets(STDIN));
  140. }
  141. // Load table of correspondence of countries
  142. $hashlib2rowid = array();
  143. $countries = array();
  144. $sql = "SELECT rowid, code, label, active";
  145. $sql .= " FROM ".MAIN_DB_PREFIX."c_country";
  146. $sql .= " WHERE active = 1";
  147. $sql .= " ORDER BY code ASC";
  148. $resql = $db->query($sql);
  149. if ($resql) {
  150. $num = $db->num_rows($resql);
  151. $i = 0;
  152. if ($num) {
  153. while ($i < $num) {
  154. $obj = $db->fetch_object($resql);
  155. if ($obj) {
  156. // print 'Load cache for country '.strtolower($obj->label).' rowid='.$obj->rowid."\n";
  157. $hashlib2rowid[strtolower($obj->label)] = $obj->rowid;
  158. $countries[$obj->rowid] = array('rowid' => $obj->rowid, 'label' => $obj->label, 'code' => $obj->code);
  159. }
  160. $i++;
  161. }
  162. }
  163. } else {
  164. dol_print_error($db);
  165. exit(-1);
  166. }
  167. $ldap = new Ldap();
  168. $result = $ldap->connect_bind();
  169. if ($result >= 0) {
  170. $justthese = array();
  171. // We disable synchro Dolibarr-LDAP
  172. $conf->global->LDAP_MEMBER_ACTIVE = 0;
  173. $ldaprecords = $ldap->getRecords('*', $conf->global->LDAP_MEMBER_DN, $conf->global->LDAP_KEY_MEMBERS, $required_fields, 'member'); // Fiter on 'member' filter param
  174. if (is_array($ldaprecords)) {
  175. $db->begin();
  176. // Warning $ldapuser has a key in lowercase
  177. foreach ($ldaprecords as $key => $ldapuser) {
  178. $member = new Adherent($db);
  179. // Propriete membre
  180. $member->firstname = $ldapuser[$conf->global->LDAP_FIELD_FIRSTNAME];
  181. $member->lastname = $ldapuser[$conf->global->LDAP_FIELD_NAME];
  182. $member->login = $ldapuser[$conf->global->LDAP_FIELD_LOGIN];
  183. $member->pass = $ldapuser[$conf->global->LDAP_FIELD_PASSWORD];
  184. // $member->societe;
  185. $member->address = $ldapuser[$conf->global->LDAP_FIELD_ADDRESS];
  186. $member->zip = $ldapuser[$conf->global->LDAP_FIELD_ZIP];
  187. $member->town = $ldapuser[$conf->global->LDAP_FIELD_TOWN];
  188. $member->country = $ldapuser[$conf->global->LDAP_FIELD_COUNTRY];
  189. $member->country_id = $countries[$hashlib2rowid[strtolower($member->country)]]['rowid'];
  190. $member->country_code = $countries[$hashlib2rowid[strtolower($member->country)]]['code'];
  191. $member->phone = $ldapuser[$conf->global->LDAP_FIELD_PHONE];
  192. $member->phone_perso = $ldapuser[$conf->global->LDAP_FIELD_PHONE_PERSO];
  193. $member->phone_mobile = $ldapuser[$conf->global->LDAP_FIELD_MOBILE];
  194. $member->email = $ldapuser[$conf->global->LDAP_FIELD_MAIL];
  195. $member->note = $ldapuser[$conf->global->LDAP_FIELD_DESCRIPTION];
  196. $member->morphy = 'phy';
  197. $member->photo = '';
  198. $member->public = 1;
  199. $member->birth = dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_BIRTHDATE]);
  200. $member->statut = - 1;
  201. if (isset($ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS])) {
  202. $member->datec = dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
  203. $member->datevalid = dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
  204. $member->statut = $ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS];
  205. }
  206. // if ($member->statut > 1) $member->statut=1;
  207. // print_r($ldapuser);
  208. // Propriete type membre
  209. $member->typeid = $typeid;
  210. // Creation membre
  211. print $langs->transnoentities("MemberCreate").' # '.$key.': login='.$member->login.', fullname='.$member->getFullName($langs);
  212. print ', datec='.$member->datec;
  213. $member_id = $member->create($user);
  214. if ($member_id > 0) {
  215. print ' --> Created member id='.$member_id.' login='.$member->login;
  216. } else {
  217. $error++;
  218. print ' --> '.$member->error;
  219. }
  220. print "\n";
  221. // print_r($member);
  222. $datefirst = '';
  223. if ($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE) {
  224. $datefirst = dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
  225. $pricefirst = price2num($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT]);
  226. }
  227. $datelast = '';
  228. if ($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE) {
  229. $datelast = dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE]);
  230. $pricelast = price2num($ldapuser[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT]);
  231. } elseif ($conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION) {
  232. $datelast = dol_time_plus_duree(dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION]), - 1, 'y') + 60 * 60 * 24;
  233. $pricelast = price2num($ldapuser[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT]);
  234. // Cas special ou date derniere <= date premiere
  235. if ($datefirst && $datelast && $datelast <= $datefirst) {
  236. // On ne va inserer que la premiere
  237. $datelast = 0;
  238. if (!$pricefirst && $pricelast) {
  239. $pricefirst = $pricelast;
  240. }
  241. }
  242. }
  243. // Insert first subscription
  244. if ($datefirst) {
  245. // Cree premiere cotisation et met a jour datefin dans adherent
  246. // print "xx".$datefirst."\n";
  247. $crowid = $member->subscription($datefirst, $pricefirst, 0);
  248. }
  249. // Insert last subscription
  250. if ($datelast) {
  251. // Cree derniere cotisation et met a jour datefin dans adherent
  252. // print "yy".dol_print_date($datelast)."\n";
  253. $crowid = $member->subscription($datelast, $pricelast, 0);
  254. }
  255. }
  256. if (!$error || $forcecommit) {
  257. if (!$error) {
  258. print $langs->transnoentities("NoErrorCommitIsDone")."\n";
  259. } else {
  260. print $langs->transnoentities("ErrorButCommitIsDone")."\n";
  261. }
  262. $db->commit();
  263. } else {
  264. print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n";
  265. $db->rollback();
  266. }
  267. print "\n";
  268. } else {
  269. dol_print_error('', $ldap->error);
  270. $error++;
  271. }
  272. } else {
  273. dol_print_error('', $ldap->error);
  274. $error++;
  275. }
  276. exit($error);
  277. /**
  278. * Function to say if a value is empty or not
  279. *
  280. * @param string $element Value to test
  281. * @return boolean True of false
  282. */
  283. function dolValidElement($element)
  284. {
  285. return (trim($element) != '');
  286. }