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