dolibarr  19.0.0-dev
sync_users_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."/user/class/user.class.php";
45 
46 $langs->loadLangs(array("main", "errors"));
47 
48 // Global variables
49 $version = DOL_VERSION;
50 $error = 0;
51 $forcecommit = 0;
52 $excludeuser = array();
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_USERS,
66  $conf->global->LDAP_FIELD_FULLNAME,
67  $conf->global->LDAP_FIELD_NAME,
68  $conf->global->LDAP_FIELD_FIRSTNAME,
69  $conf->global->LDAP_FIELD_LOGIN,
70  $conf->global->LDAP_FIELD_LOGIN_SAMBA,
71  $conf->global->LDAP_FIELD_PASSWORD,
72  $conf->global->LDAP_FIELD_PASSWORD_CRYPTED,
73  $conf->global->LDAP_FIELD_PHONE,
74  $conf->global->LDAP_FIELD_FAX,
75  $conf->global->LDAP_FIELD_MOBILE,
76  // $conf->global->LDAP_FIELD_ADDRESS,
77  // $conf->global->LDAP_FIELD_ZIP,
78  // $conf->global->LDAP_FIELD_TOWN,
79  // $conf->global->LDAP_FIELD_COUNTRY,
80  $conf->global->LDAP_FIELD_MAIL,
81  $conf->global->LDAP_FIELD_TITLE,
82  $conf->global->LDAP_FIELD_DESCRIPTION,
83  $conf->global->LDAP_FIELD_SID
84 );
85 
86 // Remove from required_fields all entries not configured in LDAP (empty) and duplicated
87 $required_fields = array_unique(array_values(array_filter($required_fields, "dolValidElement")));
88 
89 if (!isset($argv[1])) {
90  print "Usage: $script_file (nocommitiferror|commitiferror) [--server=ldapserverhost] [--excludeuser=user1,user2...] [-y]\n";
91  exit(-1);
92 }
93 
94 foreach ($argv as $key => $val) {
95  if ($val == 'commitiferror') {
96  $forcecommit = 1;
97  }
98  if (preg_match('/--server=([^\s]+)$/', $val, $reg)) {
99  $conf->global->LDAP_SERVER_HOST = $reg[1];
100  }
101  if (preg_match('/--excludeuser=([^\s]+)$/', $val, $reg)) {
102  $excludeuser = explode(',', $reg[1]);
103  }
104  if (preg_match('/-y$/', $val, $reg)) {
105  $confirmed = 1;
106  }
107 }
108 
109 print "Mails sending disabled (useless in batch mode)\n";
110 $conf->global->MAIN_DISABLE_ALL_MAILS = 1; // On bloque les mails
111 print "\n";
112 print "----- Synchronize all records from LDAP database:\n";
113 print "host=".$conf->global->LDAP_SERVER_HOST."\n";
114 print "port=".$conf->global->LDAP_SERVER_PORT."\n";
115 print "login=".$conf->global->LDAP_ADMIN_DN."\n";
116 print "pass=".preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)."\n";
117 print "DN to extract=".$conf->global->LDAP_USER_DN."\n";
118 if (!empty($conf->global->LDAP_FILTER_CONNECTION)) {
119  print 'Filter=('.$conf->global->LDAP_FILTER_CONNECTION.')'."\n"; // Note: filter is defined into function getRecords
120 } else {
121  print 'Filter=('.$conf->global->LDAP_KEY_USERS.'=*)'."\n";
122 }
123 print "----- To Dolibarr database:\n";
124 print "type=".$conf->db->type."\n";
125 print "host=".$conf->db->host."\n";
126 print "port=".$conf->db->port."\n";
127 print "login=".$conf->db->user."\n";
128 print "database=".$conf->db->name."\n";
129 print "----- Options:\n";
130 print "commitiferror=".$forcecommit."\n";
131 print "excludeuser=".join(',', $excludeuser)."\n";
132 print "Mapped LDAP fields=".join(',', $required_fields)."\n";
133 print "\n";
134 
135 if (!$confirmed) {
136  print "Hit Enter to continue or CTRL+C to stop...\n";
137  $input = trim(fgets(STDIN));
138 }
139 
140 if (empty($conf->global->LDAP_USER_DN)) {
141  print $langs->trans("Error").': '.$langs->trans("LDAP setup for users not defined inside Dolibarr");
142  exit(-1);
143 }
144 
145 // Load table of correspondence of countries
146 $hashlib2rowid = array();
147 $countries = array();
148 $sql = "SELECT rowid, code, label, active";
149 $sql .= " FROM ".MAIN_DB_PREFIX."c_country";
150 $sql .= " WHERE active = 1";
151 $sql .= " ORDER BY code ASC";
152 $resql = $db->query($sql);
153 if ($resql) {
154  $num = $db->num_rows($resql);
155  $i = 0;
156  if ($num) {
157  while ($i < $num) {
158  $obj = $db->fetch_object($resql);
159  if ($obj) {
160  // print 'Load cache for country '.strtolower($obj->label).' rowid='.$obj->rowid."\n";
161  $hashlib2rowid[strtolower($obj->label)] = $obj->rowid;
162  $countries[$obj->rowid] = array('rowid' => $obj->rowid, 'label' => $obj->label, 'code' => $obj->code);
163  }
164  $i++;
165  }
166  }
167 } else {
168  dol_print_error($db);
169  exit(-1);
170 }
171 
172 $ldap = new Ldap();
173 $result = $ldap->connect_bind();
174 if ($result >= 0) {
175  $justthese = array();
176 
177  // We disable synchro Dolibarr-LDAP
178  $conf->global->LDAP_SYNCHRO_ACTIVE = 0;
179 
180  $ldaprecords = $ldap->getRecords('*', $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, $required_fields, 'user'); // Fiter on 'user' filter param
181  if (is_array($ldaprecords)) {
182  $db->begin();
183 
184  // Warning $ldapuser has a key in lowercase
185  foreach ($ldaprecords as $key => $ldapuser) {
186  // If login into exclude list, we discard record
187  if (in_array($ldapuser[$conf->global->LDAP_FIELD_LOGIN], $excludeuser)) {
188  print $langs->transnoentities("UserDiscarded").' # '.$key.': login='.$ldapuser[$conf->global->LDAP_FIELD_LOGIN].' --> Discarded'."\n";
189  continue;
190  }
191 
192  $fuser = new User($db);
193 
194  if ($conf->global->LDAP_KEY_USERS == $conf->global->LDAP_FIELD_SID) {
195  $fuser->fetch('', '', $ldapuser[$conf->global->LDAP_KEY_USERS]); // Chargement du user concernĂ© par le SID
196  } elseif ($conf->global->LDAP_KEY_USERS == $conf->global->LDAP_FIELD_LOGIN) {
197  $fuser->fetch('', $ldapuser[$conf->global->LDAP_KEY_USERS]); // Chargement du user concernĂ© par le login
198  }
199 
200  // Propriete membre
201  $fuser->firstname = $ldapuser[$conf->global->LDAP_FIELD_FIRSTNAME];
202  $fuser->lastname = $ldapuser[$conf->global->LDAP_FIELD_NAME];
203  $fuser->login = $ldapuser[$conf->global->LDAP_FIELD_LOGIN];
204  $fuser->pass = $ldapuser[$conf->global->LDAP_FIELD_PASSWORD];
205  $fuser->pass_indatabase_crypted = $ldapuser[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED];
206 
207  // $user->societe;
208  /*
209  * $fuser->address=$ldapuser[$conf->global->LDAP_FIELD_ADDRESS];
210  * $fuser->zip=$ldapuser[$conf->global->LDAP_FIELD_ZIP];
211  * $fuser->town=$ldapuser[$conf->global->LDAP_FIELD_TOWN];
212  * $fuser->country=$ldapuser[$conf->global->LDAP_FIELD_COUNTRY];
213  * $fuser->country_id=$countries[$hashlib2rowid[strtolower($fuser->country)]]['rowid'];
214  * $fuser->country_code=$countries[$hashlib2rowid[strtolower($fuser->country)]]['code'];
215  */
216 
217  $fuser->office_phone = $ldapuser[$conf->global->LDAP_FIELD_PHONE];
218  $fuser->user_mobile = $ldapuser[$conf->global->LDAP_FIELD_MOBILE];
219  $fuser->office_fax = $ldapuser[$conf->global->LDAP_FIELD_FAX];
220  $fuser->email = $ldapuser[$conf->global->LDAP_FIELD_MAIL];
221  $fuser->ldap_sid = $ldapuser[$conf->global->LDAP_FIELD_SID];
222 
223  $fuser->job = $ldapuser[$conf->global->LDAP_FIELD_TITLE];
224  $fuser->note = $ldapuser[$conf->global->LDAP_FIELD_DESCRIPTION];
225  $fuser->admin = 0;
226  $fuser->socid = 0;
227  $fuser->contact_id = 0;
228  $fuser->fk_member = 0;
229 
230  $fuser->statut = 1;
231  // TODO : revoir la gestion du status
232  /*
233  * if (isset($ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS]))
234  * {
235  * $fuser->datec=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
236  * $fuser->datevalid=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
237  * $fuser->statut=$ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS];
238  * }
239  */
240  // if ($fuser->statut > 1) $fuser->statut=1;
241 
242  // print_r($ldapuser);
243 
244  if ($fuser->id > 0) { // User update
245  print $langs->transnoentities("UserUpdate").' # '.$key.': login='.$fuser->login.', fullname='.$fuser->getFullName($langs);
246  $res = $fuser->update($user);
247 
248  if ($res < 0) {
249  $error++;
250  print ' --> '.$res.' '.$fuser->error;
251  } else {
252  print ' --> Updated user id='.$fuser->id.' login='.$fuser->login;
253  }
254  } else { // User creation
255  print $langs->transnoentities("UserCreate").' # '.$key.': login='.$fuser->login.', fullname='.$fuser->getFullName($langs);
256  $res = $fuser->create($user);
257 
258  if ($res > 0) {
259  print ' --> Created user id='.$fuser->id.' login='.$fuser->login;
260  } else {
261  $error++;
262  print ' --> '.$res.' '.$fuser->error;
263  }
264  }
265  print "\n";
266  // print_r($fuser);
267 
268  // Gestion des groupes
269  // TODO : revoir la gestion des groupes (ou script de sync groupes)
270  /*
271  * if(!$error) {
272  * foreach ($ldapuser[$conf->global->LDAP_FIELD_USERGROUPS] as $groupdn) {
273  * $groupdn;
274  * }
275  * }
276  */
277  }
278 
279  if (!$error || $forcecommit) {
280  if (!$error) {
281  print $langs->transnoentities("NoErrorCommitIsDone")."\n";
282  } else {
283  print $langs->transnoentities("ErrorButCommitIsDone")."\n";
284  }
285  $db->commit();
286  } else {
287  print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n";
288  $db->rollback();
289  }
290  print "\n";
291  } else {
292  dol_print_error('', $ldap->error);
293  $error++;
294  }
295 } else {
296  dol_print_error('', $ldap->error);
297  $error++;
298 }
299 
300 exit($error);
301 
302 
309 function dolValidElement($element)
310 {
311  return (trim($element) != '');
312 }
Class to manage LDAP features.
Definition: ldap.class.php:35
Class to manage Dolibarr users.
Definition: user.class.php:48
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_getmypid()
Return getmypid() or random PID when function is disabled Some web hosts disable this php function fo...
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.