sync_members_ldap2dolibarr.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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 = (int) $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=" . getDolGlobalString('LDAP_SERVER_HOST')."\n";
  105. print "port=" . getDolGlobalString('LDAP_SERVER_PORT')."\n";
  106. print "login=" . getDolGlobalString('LDAP_ADMIN_DN')."\n";
  107. print "pass=".preg_replace('/./i', '*', getDolGlobalString('LDAP_ADMIN_PASS'))."\n";
  108. print "DN to extract=" . getDolGlobalString('LDAP_MEMBER_DN')."\n";
  109. if (getDolGlobalString('LDAP_MEMBER_FILTER')) {
  110. print 'Filter=(' . getDolGlobalString('LDAP_MEMBER_FILTER').')'."\n"; // Note: filter is defined into function getRecords
  111. } else {
  112. print 'Filter=(' . getDolGlobalString('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 (!getDolGlobalString('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. $pricefirst = 0;
  172. $pricelast = 0;
  173. // We disable synchro Dolibarr-LDAP
  174. $conf->global->LDAP_MEMBER_ACTIVE = 0;
  175. $ldaprecords = $ldap->getRecords('*', getDolGlobalString('LDAP_MEMBER_DN'), getDolGlobalString('LDAP_KEY_MEMBERS'), $required_fields, 'member'); // Fiter on 'member' filter param
  176. if (is_array($ldaprecords)) {
  177. $db->begin();
  178. // Warning $ldapuser has a key in lowercase
  179. foreach ($ldaprecords as $key => $ldapuser) {
  180. $member = new Adherent($db);
  181. // Propriete membre
  182. $member->firstname = $ldapuser[getDolGlobalString('LDAP_FIELD_FIRSTNAME')];
  183. $member->lastname = $ldapuser[getDolGlobalString('LDAP_FIELD_NAME')];
  184. $member->login = $ldapuser[getDolGlobalString('LDAP_FIELD_LOGIN')];
  185. $member->pass = $ldapuser[getDolGlobalString('LDAP_FIELD_PASSWORD')];
  186. // $member->societe;
  187. $member->address = $ldapuser[getDolGlobalString('LDAP_FIELD_ADDRESS')];
  188. $member->zip = $ldapuser[getDolGlobalString('LDAP_FIELD_ZIP')];
  189. $member->town = $ldapuser[getDolGlobalString('LDAP_FIELD_TOWN')];
  190. $member->country = $ldapuser[getDolGlobalString('LDAP_FIELD_COUNTRY')];
  191. $member->country_id = $countries[$hashlib2rowid[strtolower($member->country)]]['rowid'];
  192. $member->country_code = $countries[$hashlib2rowid[strtolower($member->country)]]['code'];
  193. $member->phone = $ldapuser[getDolGlobalString('LDAP_FIELD_PHONE')];
  194. $member->phone_perso = $ldapuser[getDolGlobalString('LDAP_FIELD_PHONE_PERSO')];
  195. $member->phone_mobile = $ldapuser[getDolGlobalString('LDAP_FIELD_MOBILE')];
  196. $member->email = $ldapuser[getDolGlobalString('LDAP_FIELD_MAIL')];
  197. $member->note = $ldapuser[getDolGlobalString('LDAP_FIELD_DESCRIPTION')];
  198. $member->morphy = 'phy';
  199. $member->photo = '';
  200. $member->public = 1;
  201. $member->birth = dol_stringtotime($ldapuser[getDolGlobalString('LDAP_FIELD_BIRTHDATE')]);
  202. $member->statut = -1;
  203. if (isset($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_STATUS')])) {
  204. $member->datec = dol_stringtotime($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE')]);
  205. $member->datevalid = dol_stringtotime($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE')]);
  206. $member->statut = $ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_STATUS')];
  207. }
  208. // if ($member->statut > 1) $member->statut=1;
  209. // print_r($ldapuser);
  210. // Propriete type membre
  211. $member->typeid = $typeid;
  212. // Creation membre
  213. print $langs->transnoentities("MemberCreate").' # '.$key.': login='.$member->login.', fullname='.$member->getFullName($langs);
  214. print ', datec='.$member->datec;
  215. $member_id = $member->create($user);
  216. if ($member_id > 0) {
  217. print ' --> Created member id='.$member_id.' login='.$member->login;
  218. } else {
  219. $error++;
  220. print ' --> '.$member->error;
  221. }
  222. print "\n";
  223. // print_r($member);
  224. $datefirst = '';
  225. if (getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE')) {
  226. $datefirst = dol_stringtotime($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE')]);
  227. $pricefirst = price2num($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT')]);
  228. }
  229. $datelast = '';
  230. if (getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE')) {
  231. $datelast = dol_stringtotime($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE')]);
  232. $pricelast = price2num($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT')]);
  233. } elseif (getDolGlobalString('LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION')) {
  234. $datelast = dol_time_plus_duree(dol_stringtotime($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION')]), -1, 'y') + 60 * 60 * 24;
  235. $pricelast = price2num($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT')]);
  236. // Cas special ou date derniere <= date premiere
  237. if ($datefirst && $datelast && $datelast <= $datefirst) {
  238. // On ne va inserer que la premiere
  239. $datelast = 0;
  240. if (!$pricefirst && $pricelast) {
  241. $pricefirst = $pricelast;
  242. }
  243. }
  244. }
  245. // Insert first subscription
  246. if ($datefirst) {
  247. // Cree premiere cotisation et met a jour datefin dans adherent
  248. // print "xx".$datefirst."\n";
  249. $crowid = $member->subscription($datefirst, $pricefirst, 0);
  250. }
  251. // Insert last subscription
  252. if ($datelast) {
  253. // Cree derniere cotisation et met a jour datefin dans adherent
  254. // print "yy".dol_print_date($datelast)."\n";
  255. $crowid = $member->subscription($datelast, $pricelast, 0);
  256. }
  257. }
  258. if (!$error || $forcecommit) {
  259. if (!$error) {
  260. print $langs->transnoentities("NoErrorCommitIsDone")."\n";
  261. } else {
  262. print $langs->transnoentities("ErrorButCommitIsDone")."\n";
  263. }
  264. $db->commit();
  265. } else {
  266. print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n";
  267. $db->rollback();
  268. }
  269. print "\n";
  270. } else {
  271. dol_print_error('', $ldap->error);
  272. $error++;
  273. }
  274. } else {
  275. dol_print_error('', $ldap->error);
  276. $error++;
  277. }
  278. exit($error);
  279. /**
  280. * Function to say if a value is empty or not
  281. *
  282. * @param string $element Value to test
  283. * @return boolean True of false
  284. */
  285. function dolValidElement($element)
  286. {
  287. return (trim($element) != '');
  288. }