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