dolibarr  19.0.0-dev
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  $pricefirst = 0;
191  $pricelast = 0;
192  // We disable synchro Dolibarr-LDAP
193  $conf->global->LDAP_MEMBER_ACTIVE = 0;
194 
195  $ldaprecords = $ldap->getRecords('*', $conf->global->LDAP_MEMBER_DN, $conf->global->LDAP_KEY_MEMBERS, $required_fields, 'member'); // Fiter on 'member' filter param
196  if (is_array($ldaprecords)) {
197  $db->begin();
198 
199  // Warning $ldapuser has a key in lowercase
200  foreach ($ldaprecords as $key => $ldapuser) {
201  $member = new Adherent($db);
202 
203  // Propriete membre
204  $member->firstname = $ldapuser[$conf->global->LDAP_FIELD_FIRSTNAME];
205  $member->lastname = $ldapuser[$conf->global->LDAP_FIELD_NAME];
206  $member->login = $ldapuser[$conf->global->LDAP_FIELD_LOGIN];
207  $member->pass = $ldapuser[$conf->global->LDAP_FIELD_PASSWORD];
208 
209  // $member->societe;
210  $member->address = $ldapuser[$conf->global->LDAP_FIELD_ADDRESS];
211  $member->zip = $ldapuser[$conf->global->LDAP_FIELD_ZIP];
212  $member->town = $ldapuser[$conf->global->LDAP_FIELD_TOWN];
213  $member->country = $ldapuser[$conf->global->LDAP_FIELD_COUNTRY];
214  $member->country_id = $countries[$hashlib2rowid[strtolower($member->country)]]['rowid'];
215  $member->country_code = $countries[$hashlib2rowid[strtolower($member->country)]]['code'];
216 
217  $member->phone = $ldapuser[$conf->global->LDAP_FIELD_PHONE];
218  $member->phone_perso = $ldapuser[$conf->global->LDAP_FIELD_PHONE_PERSO];
219  $member->phone_mobile = $ldapuser[$conf->global->LDAP_FIELD_MOBILE];
220  $member->email = $ldapuser[$conf->global->LDAP_FIELD_MAIL];
221 
222  $member->note = $ldapuser[$conf->global->LDAP_FIELD_DESCRIPTION];
223  $member->morphy = 'phy';
224  $member->photo = '';
225  $member->public = 1;
226  $member->birth = dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_BIRTHDATE]);
227 
228  $member->statut = - 1;
229  if (isset($ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS])) {
230  $member->datec = dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
231  $member->datevalid = dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
232  $member->statut = $ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS];
233  }
234  // if ($member->statut > 1) $member->statut=1;
235 
236  // print_r($ldapuser);
237 
238  // Propriete type membre
239  $member->typeid = $typeid;
240 
241  // Creation membre
242  print $langs->transnoentities("MemberCreate").' # '.$key.': login='.$member->login.', fullname='.$member->getFullName($langs);
243  print ', datec='.$member->datec;
244  $member_id = $member->create($user);
245  if ($member_id > 0) {
246  print ' --> Created member id='.$member_id.' login='.$member->login;
247  } else {
248  $error++;
249  print ' --> '.$member->error;
250  }
251  print "\n";
252 
253  // print_r($member);
254 
255  $datefirst = '';
256  if ($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE) {
257  $datefirst = dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
258  $pricefirst = price2num($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT]);
259  }
260 
261  $datelast = '';
262  if ($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE) {
263  $datelast = dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE]);
264  $pricelast = price2num($ldapuser[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT]);
265  } elseif ($conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION) {
266  $datelast = dol_time_plus_duree(dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION]), - 1, 'y') + 60 * 60 * 24;
267  $pricelast = price2num($ldapuser[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT]);
268 
269  // Cas special ou date derniere <= date premiere
270  if ($datefirst && $datelast && $datelast <= $datefirst) {
271  // On ne va inserer que la premiere
272  $datelast = 0;
273  if (!$pricefirst && $pricelast) {
274  $pricefirst = $pricelast;
275  }
276  }
277  }
278 
279  // Insert first subscription
280  if ($datefirst) {
281  // Cree premiere cotisation et met a jour datefin dans adherent
282  // print "xx".$datefirst."\n";
283  $crowid = $member->subscription($datefirst, $pricefirst, 0);
284  }
285 
286  // Insert last subscription
287  if ($datelast) {
288  // Cree derniere cotisation et met a jour datefin dans adherent
289  // print "yy".dol_print_date($datelast)."\n";
290  $crowid = $member->subscription($datelast, $pricelast, 0);
291  }
292  }
293 
294  if (!$error || $forcecommit) {
295  if (!$error) {
296  print $langs->transnoentities("NoErrorCommitIsDone")."\n";
297  } else {
298  print $langs->transnoentities("ErrorButCommitIsDone")."\n";
299  }
300  $db->commit();
301  } else {
302  print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n";
303  $db->rollback();
304  }
305  print "\n";
306  } else {
307  dol_print_error('', $ldap->error);
308  $error++;
309  }
310 } else {
311  dol_print_error('', $ldap->error);
312  $error++;
313 }
314 
315 exit($error);
316 
317 
324 function dolValidElement($element)
325 {
326  return (trim($element) != '');
327 }
Class to manage members of a foundation.
Class to manage LDAP features.
Definition: ldap.class.php:35
if(isModEnabled('facture') && $user->hasRight('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') && $user->hasRight('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)) $sql
Social contributions to pay.
Definition: index.php:746
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition: date.lib.php:122
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:408
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.