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