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