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