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