dolibarr 19.0.4
sync_members_ldap2dolibarr.php
Go to the documentation of this file.
1#!/usr/bin/env php
2<?php
27if (!defined('NOSESSION')) {
28 define('NOSESSION', '1');
29}
30
31$sapi_type = php_sapi_name();
32$script_file = basename(__FILE__);
33$path = __DIR__.'/';
34
35// Test if batch mode
36if (substr($sapi_type, 0, 3) == 'cgi') {
37 echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
38 exit(-1);
39}
40
41require_once $path."../../htdocs/master.inc.php";
42require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php";
43require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php";
44require_once DOL_DOCUMENT_ROOT."/adherents/class/adherent.class.php";
45require_once DOL_DOCUMENT_ROOT."/adherents/class/subscription.class.php";
46
47$langs->loadLangs(array("main", "errors"));
48
49// Global variables
50$version = constant('DOL_VERSION');
51$error = 0;
52$forcecommit = 0;
53$confirmed = 0;
54
55/*
56 * Main
57 */
58
59@set_time_limit(0);
60print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
61dol_syslog($script_file." launched with arg ".join(',', $argv));
62
63// List of fields to get from LDAP
64$required_fields = array(
65 $conf->global->LDAP_KEY_MEMBERS,
66 $conf->global->LDAP_FIELD_FULLNAME,
67 $conf->global->LDAP_FIELD_LOGIN,
68 $conf->global->LDAP_FIELD_LOGIN_SAMBA,
69 $conf->global->LDAP_FIELD_PASSWORD,
70 $conf->global->LDAP_FIELD_PASSWORD_CRYPTED,
71 $conf->global->LDAP_FIELD_NAME,
72 $conf->global->LDAP_FIELD_FIRSTNAME,
73 $conf->global->LDAP_FIELD_MAIL,
74 $conf->global->LDAP_FIELD_PHONE,
75 $conf->global->LDAP_FIELD_PHONE_PERSO,
76 $conf->global->LDAP_FIELD_MOBILE,
77 $conf->global->LDAP_FIELD_FAX,
78 $conf->global->LDAP_FIELD_ADDRESS,
79 $conf->global->LDAP_FIELD_ZIP,
80 $conf->global->LDAP_FIELD_TOWN,
81 $conf->global->LDAP_FIELD_COUNTRY,
82 $conf->global->LDAP_FIELD_DESCRIPTION,
83 $conf->global->LDAP_FIELD_BIRTHDATE,
84 $conf->global->LDAP_FIELD_MEMBER_STATUS,
85 $conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION,
86 // Subscriptions
87 $conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE,
88 $conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT,
89 $conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE,
90 $conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT
91);
92
93// Remove from required_fields all entries not configured in LDAP (empty) and duplicated
94$required_fields = array_unique(array_values(array_filter($required_fields, "dolValidElement")));
95
96if (!isset($argv[2]) || !is_numeric($argv[2])) {
97 print "Usage: $script_file (nocommitiferror|commitiferror) id_member_type [--server=ldapserverhost] [-y]\n";
98 exit(-1);
99}
100
101$typeid = (int) $argv[2];
102foreach ($argv as $key => $val) {
103 if ($val == 'commitiferror') {
104 $forcecommit = 1;
105 }
106 if (preg_match('/--server=([^\s]+)$/', $val, $reg)) {
107 $conf->global->LDAP_SERVER_HOST = $reg[1];
108 }
109 if (preg_match('/-y$/', $val, $reg)) {
110 $confirmed = 1;
111 }
112}
113
114print "Mails sending disabled (useless in batch mode)\n";
115$conf->global->MAIN_DISABLE_ALL_MAILS = 1; // On bloque les mails
116print "\n";
117print "----- Synchronize all records from LDAP database:\n";
118print "host=" . getDolGlobalString('LDAP_SERVER_HOST')."\n";
119print "port=" . getDolGlobalString('LDAP_SERVER_PORT')."\n";
120print "login=" . getDolGlobalString('LDAP_ADMIN_DN')."\n";
121print "pass=".preg_replace('/./i', '*', getDolGlobalString('LDAP_ADMIN_PASS'))."\n";
122print "DN to extract=" . getDolGlobalString('LDAP_MEMBER_DN')."\n";
123if (getDolGlobalString('LDAP_MEMBER_FILTER')) {
124 print 'Filter=(' . getDolGlobalString('LDAP_MEMBER_FILTER').')'."\n"; // Note: filter is defined into function getRecords
125} else {
126 print 'Filter=(' . getDolGlobalString('LDAP_KEY_MEMBERS').'=*)'."\n";
127}
128print "----- To Dolibarr database:\n";
129print "type=".$conf->db->type."\n";
130print "host=".$conf->db->host."\n";
131print "port=".$conf->db->port."\n";
132print "login=".$conf->db->user."\n";
133print "database=".$conf->db->name."\n";
134print "----- Options:\n";
135print "commitiferror=".$forcecommit."\n";
136print "Mapped LDAP fields=".join(',', $required_fields)."\n";
137print "\n";
138
139// Check parameters
140if (!getDolGlobalString('LDAP_MEMBER_DN')) {
141 print $langs->trans("Error").': '.$langs->trans("LDAP setup for members not defined inside Dolibarr")."\n";
142 exit(-1);
143}
144if ($typeid <= 0) {
145 print $langs->trans("Error").': Parameter id_member_type is not a valid ref of an existing member type'."\n";
146 exit(-2);
147}
148
149if (!empty($dolibarr_main_db_readonly)) {
150 print "Error: instance in read-onyl mode\n";
151 exit(-1);
152}
153
154if (!$confirmed) {
155 print "Hit Enter to continue or CTRL+C to stop...\n";
156 $input = trim(fgets(STDIN));
157}
158
159// Load table of correspondence of countries
160$hashlib2rowid = array();
161$countries = array();
162$sql = "SELECT rowid, code, label, active";
163$sql .= " FROM ".MAIN_DB_PREFIX."c_country";
164$sql .= " WHERE active = 1";
165$sql .= " ORDER BY code ASC";
166$resql = $db->query($sql);
167if ($resql) {
168 $num = $db->num_rows($resql);
169 $i = 0;
170 if ($num) {
171 while ($i < $num) {
172 $obj = $db->fetch_object($resql);
173 if ($obj) {
174 // print 'Load cache for country '.strtolower($obj->label).' rowid='.$obj->rowid."\n";
175 $hashlib2rowid[strtolower($obj->label)] = $obj->rowid;
176 $countries[$obj->rowid] = array('rowid' => $obj->rowid, 'label' => $obj->label, 'code' => $obj->code);
177 }
178 $i++;
179 }
180 }
181} else {
182 dol_print_error($db);
183 exit(-1);
184}
185
186$ldap = new Ldap();
187$result = $ldap->connect_bind();
188if ($result >= 0) {
189 $justthese = array();
190 $pricefirst = 0;
191 $pricelast = 0;
192 // We disable synchro Dolibarr-LDAP
193 $conf->global->LDAP_MEMBER_ACTIVE = 0;
194
195 $ldaprecords = $ldap->getRecords('*', getDolGlobalString('LDAP_MEMBER_DN'), getDolGlobalString('LDAP_KEY_MEMBERS'), $required_fields, 'member'); // Fiter on 'member' filter param
196 if (is_array($ldaprecords)) {
197 $db->begin();
198
199 // Warning $ldapuser has a key in lowercase
200 foreach ($ldaprecords as $key => $ldapuser) {
201 $member = new Adherent($db);
202
203 // Propriete membre
204 $member->firstname = $ldapuser[getDolGlobalString('LDAP_FIELD_FIRSTNAME')];
205 $member->lastname = $ldapuser[getDolGlobalString('LDAP_FIELD_NAME')];
206 $member->login = $ldapuser[getDolGlobalString('LDAP_FIELD_LOGIN')];
207 $member->pass = $ldapuser[getDolGlobalString('LDAP_FIELD_PASSWORD')];
208
209 // $member->societe;
210 $member->address = $ldapuser[getDolGlobalString('LDAP_FIELD_ADDRESS')];
211 $member->zip = $ldapuser[getDolGlobalString('LDAP_FIELD_ZIP')];
212 $member->town = $ldapuser[getDolGlobalString('LDAP_FIELD_TOWN')];
213 $member->country = $ldapuser[getDolGlobalString('LDAP_FIELD_COUNTRY')];
214 $member->country_id = $countries[$hashlib2rowid[strtolower($member->country)]]['rowid'];
215 $member->country_code = $countries[$hashlib2rowid[strtolower($member->country)]]['code'];
216
217 $member->phone = $ldapuser[getDolGlobalString('LDAP_FIELD_PHONE')];
218 $member->phone_perso = $ldapuser[getDolGlobalString('LDAP_FIELD_PHONE_PERSO')];
219 $member->phone_mobile = $ldapuser[getDolGlobalString('LDAP_FIELD_MOBILE')];
220 $member->email = $ldapuser[getDolGlobalString('LDAP_FIELD_MAIL')];
221
222 $member->note = $ldapuser[getDolGlobalString('LDAP_FIELD_DESCRIPTION')];
223 $member->morphy = 'phy';
224 $member->photo = '';
225 $member->public = 1;
226 $member->birth = dol_stringtotime($ldapuser[getDolGlobalString('LDAP_FIELD_BIRTHDATE')]);
227
228 $member->statut = -1;
229 if (isset($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_STATUS')])) {
230 $member->datec = dol_stringtotime($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE')]);
231 $member->datevalid = dol_stringtotime($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE')]);
232 $member->statut = $ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_STATUS')];
233 }
234 // if ($member->statut > 1) $member->statut=1;
235
236 // print_r($ldapuser);
237
238 // Propriete type membre
239 $member->typeid = $typeid;
240
241 // Creation membre
242 print $langs->transnoentities("MemberCreate").' # '.$key.': login='.$member->login.', fullname='.$member->getFullName($langs);
243 print ', datec='.$member->datec;
244 $member_id = $member->create($user);
245 if ($member_id > 0) {
246 print ' --> Created member id='.$member_id.' login='.$member->login;
247 } else {
248 $error++;
249 print ' --> '.$member->error;
250 }
251 print "\n";
252
253 // print_r($member);
254
255 $datefirst = '';
256 if (getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE')) {
257 $datefirst = dol_stringtotime($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE')]);
258 $pricefirst = price2num($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT')]);
259 }
260
261 $datelast = '';
262 if (getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE')) {
263 $datelast = dol_stringtotime($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE')]);
264 $pricelast = price2num($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT')]);
265 } elseif (getDolGlobalString('LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION')) {
266 $datelast = dol_time_plus_duree(dol_stringtotime($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION')]), -1, 'y') + 60 * 60 * 24;
267 $pricelast = price2num($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT')]);
268
269 // Cas special ou date derniere <= date premiere
270 if ($datefirst && $datelast && $datelast <= $datefirst) {
271 // On ne va inserer que la premiere
272 $datelast = 0;
273 if (!$pricefirst && $pricelast) {
274 $pricefirst = $pricelast;
275 }
276 }
277 }
278
279 // Insert first subscription
280 if ($datefirst) {
281 // Cree premiere cotisation et met a jour datefin dans adherent
282 // print "xx".$datefirst."\n";
283 $crowid = $member->subscription($datefirst, $pricefirst, 0);
284 }
285
286 // Insert last subscription
287 if ($datelast) {
288 // Cree derniere cotisation et met a jour datefin dans adherent
289 // print "yy".dol_print_date($datelast)."\n";
290 $crowid = $member->subscription($datelast, $pricelast, 0);
291 }
292 }
293
294 if (!$error || $forcecommit) {
295 if (!$error) {
296 print $langs->transnoentities("NoErrorCommitIsDone")."\n";
297 } else {
298 print $langs->transnoentities("ErrorButCommitIsDone")."\n";
299 }
300 $db->commit();
301 } else {
302 print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n";
303 $db->rollback();
304 }
305 print "\n";
306 } else {
307 dol_print_error('', $ldap->error);
308 $error++;
309 }
310} else {
311 dol_print_error('', $ldap->error);
312 $error++;
313}
314
315exit($error);
316
317
324function dolValidElement($element)
325{
326 return (trim($element) != '');
327}
Class to manage members of a foundation.
Class to manage LDAP features.
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:125
dol_stringtotime($string, $gm=1)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition date.lib.php:426
dol_getmypid()
Return getmypid() or random PID when function is disabled Some web hosts disable this php function fo...
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dolValidElement($element)
Function to say if a value is empty or not.