dolibarr  13.0.2
sync_users_ldap2dolibarr.php
Go to the documentation of this file.
1 #!/usr/bin/env php
2 <?php
27 if (!defined('NOSESSION')) define('NOSESSION', '1');
28 
29 $sapi_type = php_sapi_name();
30 $script_file = basename(__FILE__);
31 $path = __DIR__.'/';
32 
33 // Test if batch mode
34 if (substr($sapi_type, 0, 3) == 'cgi') {
35  echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
36  exit(-1);
37 }
38 
39 require_once $path."../../htdocs/master.inc.php";
40 require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php";
41 require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php";
42 require_once DOL_DOCUMENT_ROOT."/user/class/user.class.php";
43 
44 $langs->loadLangs(array("main", "errors"));
45 
46 // Global variables
47 $version = DOL_VERSION;
48 $error = 0;
49 $forcecommit = 0;
50 $excludeuser = array();
51 $confirmed = 0;
52 
53 /*
54  * Main
55  */
56 
57 @set_time_limit(0);
58 print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
59 dol_syslog($script_file." launched with arg ".join(',', $argv));
60 
61 // List of fields to get from LDAP
62 $required_fields = array($conf->global->LDAP_KEY_USERS, $conf->global->LDAP_FIELD_FULLNAME, $conf->global->LDAP_FIELD_NAME, $conf->global->LDAP_FIELD_FIRSTNAME, $conf->global->LDAP_FIELD_LOGIN, $conf->global->LDAP_FIELD_LOGIN_SAMBA, $conf->global->LDAP_FIELD_PASSWORD, $conf->global->LDAP_FIELD_PASSWORD_CRYPTED, $conf->global->LDAP_FIELD_PHONE, $conf->global->LDAP_FIELD_FAX, $conf->global->LDAP_FIELD_MOBILE,
63  // $conf->global->LDAP_FIELD_ADDRESS,
64  // $conf->global->LDAP_FIELD_ZIP,
65  // $conf->global->LDAP_FIELD_TOWN,
66  // $conf->global->LDAP_FIELD_COUNTRY,
67  $conf->global->LDAP_FIELD_MAIL, $conf->global->LDAP_FIELD_TITLE, $conf->global->LDAP_FIELD_DESCRIPTION, $conf->global->LDAP_FIELD_SID);
68 
69 // Remove from required_fields all entries not configured in LDAP (empty) and duplicated
70 $required_fields = array_unique(array_values(array_filter($required_fields, "dolValidElement")));
71 
72 if (!isset($argv[1])) {
73  print "Usage: $script_file (nocommitiferror|commitiferror) [--server=ldapserverhost] [--excludeuser=user1,user2...] [-y]\n";
74  exit(-1);
75 }
76 
77 foreach ($argv as $key => $val) {
78  if ($val == 'commitiferror')
79  $forcecommit = 1;
80  if (preg_match('/--server=([^\s]+)$/', $val, $reg))
81  $conf->global->LDAP_SERVER_HOST = $reg[1];
82  if (preg_match('/--excludeuser=([^\s]+)$/', $val, $reg))
83  $excludeuser = explode(',', $reg[1]);
84  if (preg_match('/-y$/', $val, $reg))
85  $confirmed = 1;
86 }
87 
88 print "Mails sending disabled (useless in batch mode)\n";
89 $conf->global->MAIN_DISABLE_ALL_MAILS = 1; // On bloque les mails
90 print "\n";
91 print "----- Synchronize all records from LDAP database:\n";
92 print "host=".$conf->global->LDAP_SERVER_HOST."\n";
93 print "port=".$conf->global->LDAP_SERVER_PORT."\n";
94 print "login=".$conf->global->LDAP_ADMIN_DN."\n";
95 print "pass=".preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)."\n";
96 print "DN to extract=".$conf->global->LDAP_USER_DN."\n";
97 if (!empty($conf->global->LDAP_FILTER_CONNECTION))
98  print 'Filter=('.$conf->global->LDAP_FILTER_CONNECTION.')'."\n"; // Note: filter is defined into function getRecords
99 else print 'Filter=('.$conf->global->LDAP_KEY_USERS.'=*)'."\n";
100 print "----- To Dolibarr database:\n";
101 print "type=".$conf->db->type."\n";
102 print "host=".$conf->db->host."\n";
103 print "port=".$conf->db->port."\n";
104 print "login=".$conf->db->user."\n";
105 print "database=".$conf->db->name."\n";
106 print "----- Options:\n";
107 print "commitiferror=".$forcecommit."\n";
108 print "excludeuser=".join(',', $excludeuser)."\n";
109 print "Mapped LDAP fields=".join(',', $required_fields)."\n";
110 print "\n";
111 
112 if (!$confirmed) {
113  print "Hit Enter to continue or CTRL+C to stop...\n";
114  $input = trim(fgets(STDIN));
115 }
116 
117 if (empty($conf->global->LDAP_USER_DN)) {
118  print $langs->trans("Error").': '.$langs->trans("LDAP setup for users not defined inside Dolibarr");
119  exit(-1);
120 }
121 
122 // Load table of correspondence of countries
123 $hashlib2rowid = array();
124 $countries = array();
125 $sql = "SELECT rowid, code, label, active";
126 $sql .= " FROM ".MAIN_DB_PREFIX."c_country";
127 $sql .= " WHERE active = 1";
128 $sql .= " ORDER BY code ASC";
129 $resql = $db->query($sql);
130 if ($resql) {
131  $num = $db->num_rows($resql);
132  $i = 0;
133  if ($num) {
134  while ($i < $num) {
135  $obj = $db->fetch_object($resql);
136  if ($obj) {
137  // print 'Load cache for country '.strtolower($obj->label).' rowid='.$obj->rowid."\n";
138  $hashlib2rowid[strtolower($obj->label)] = $obj->rowid;
139  $countries[$obj->rowid] = array('rowid' => $obj->rowid, 'label' => $obj->label, 'code' => $obj->code);
140  }
141  $i++;
142  }
143  }
144 } else {
145  dol_print_error($db);
146  exit(-1);
147 }
148 
149 $ldap = new Ldap();
150 $result = $ldap->connect_bind();
151 if ($result >= 0) {
152  $justthese = array();
153 
154  // We disable synchro Dolibarr-LDAP
155  $conf->global->LDAP_SYNCHRO_ACTIVE = 0;
156 
157  $ldaprecords = $ldap->getRecords('*', $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, $required_fields, 'user'); // Fiter on 'user' filter param
158  if (is_array($ldaprecords)) {
159  $db->begin();
160 
161  // Warning $ldapuser has a key in lowercase
162  foreach ($ldaprecords as $key => $ldapuser) {
163  // If login into exclude list, we discard record
164  if (in_array($ldapuser[$conf->global->LDAP_FIELD_LOGIN], $excludeuser)) {
165  print $langs->transnoentities("UserDiscarded").' # '.$key.': login='.$ldapuser[$conf->global->LDAP_FIELD_LOGIN].' --> Discarded'."\n";
166  continue;
167  }
168 
169  $fuser = new User($db);
170 
171  if ($conf->global->LDAP_KEY_USERS == $conf->global->LDAP_FIELD_SID) {
172  $fuser->fetch('', '', $ldapuser[$conf->global->LDAP_KEY_USERS]); // Chargement du user concernĂ© par le SID
173  } elseif ($conf->global->LDAP_KEY_USERS == $conf->global->LDAP_FIELD_LOGIN) {
174  $fuser->fetch('', $ldapuser[$conf->global->LDAP_KEY_USERS]); // Chargement du user concernĂ© par le login
175  }
176 
177  // Propriete membre
178  $fuser->firstname = $ldapuser[$conf->global->LDAP_FIELD_FIRSTNAME];
179  $fuser->lastname = $ldapuser[$conf->global->LDAP_FIELD_NAME];
180  $fuser->login = $ldapuser[$conf->global->LDAP_FIELD_LOGIN];
181  $fuser->pass = $ldapuser[$conf->global->LDAP_FIELD_PASSWORD];
182  $fuser->pass_indatabase_crypted = $ldapuser[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED];
183 
184  // $user->societe;
185  /*
186  * $fuser->address=$ldapuser[$conf->global->LDAP_FIELD_ADDRESS];
187  * $fuser->zip=$ldapuser[$conf->global->LDAP_FIELD_ZIP];
188  * $fuser->town=$ldapuser[$conf->global->LDAP_FIELD_TOWN];
189  * $fuser->country=$ldapuser[$conf->global->LDAP_FIELD_COUNTRY];
190  * $fuser->country_id=$countries[$hashlib2rowid[strtolower($fuser->country)]]['rowid'];
191  * $fuser->country_code=$countries[$hashlib2rowid[strtolower($fuser->country)]]['code'];
192  */
193 
194  $fuser->office_phone = $ldapuser[$conf->global->LDAP_FIELD_PHONE];
195  $fuser->user_mobile = $ldapuser[$conf->global->LDAP_FIELD_MOBILE];
196  $fuser->office_fax = $ldapuser[$conf->global->LDAP_FIELD_FAX];
197  $fuser->email = $ldapuser[$conf->global->LDAP_FIELD_MAIL];
198  $fuser->ldap_sid = $ldapuser[$conf->global->LDAP_FIELD_SID];
199 
200  $fuser->job = $ldapuser[$conf->global->LDAP_FIELD_TITLE];
201  $fuser->note = $ldapuser[$conf->global->LDAP_FIELD_DESCRIPTION];
202  $fuser->admin = 0;
203  $fuser->societe_id = 0;
204  $fuser->contact_id = 0;
205  $fuser->fk_member = 0;
206 
207  $fuser->statut = 1;
208  // TODO : revoir la gestion du status
209  /*
210  * if (isset($ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS]))
211  * {
212  * $fuser->datec=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
213  * $fuser->datevalid=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
214  * $fuser->statut=$ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS];
215  * }
216  */
217  // if ($fuser->statut > 1) $fuser->statut=1;
218 
219  // print_r($ldapuser);
220 
221  if ($fuser->id > 0) { // User update
222  print $langs->transnoentities("UserUpdate").' # '.$key.': login='.$fuser->login.', fullname='.$fuser->getFullName($langs);
223  $res = $fuser->update($user);
224 
225  if ($res < 0) {
226  $error++;
227  print ' --> '.$res.' '.$fuser->error;
228  } else {
229  print ' --> Updated user id='.$fuser->id.' login='.$fuser->login;
230  }
231  } else { // User creation
232  print $langs->transnoentities("UserCreate").' # '.$key.': login='.$fuser->login.', fullname='.$fuser->getFullName($langs);
233  $res = $fuser->create($user);
234 
235  if ($res > 0) {
236  print ' --> Created user id='.$fuser->id.' login='.$fuser->login;
237  } else {
238  $error++;
239  print ' --> '.$res.' '.$fuser->error;
240  }
241  }
242  print "\n";
243  // print_r($fuser);
244 
245  // Gestion des groupes
246  // TODO : revoir la gestion des groupes (ou script de sync groupes)
247  /*
248  * if(!$error) {
249  * foreach ($ldapuser[$conf->global->LDAP_FIELD_USERGROUPS] as $groupdn) {
250  * $groupdn;
251  * }
252  * }
253  */
254  }
255 
256  if (!$error || $forcecommit) {
257  if (!$error)
258  print $langs->transnoentities("NoErrorCommitIsDone")."\n";
259  else print $langs->transnoentities("ErrorButCommitIsDone")."\n";
260  $db->commit();
261  } else {
262  print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n";
263  $db->rollback();
264  }
265  print "\n";
266  } else {
267  dol_print_error('', $ldap->error);
268  $error++;
269  }
270 } else {
271  dol_print_error('', $ldap->error);
272  $error++;
273 }
274 
275 exit($error);
276 
277 
284 function dolValidElement($element)
285 {
286  return (trim($element) != '');
287 }
Class to manage Dolibarr users.
Definition: user.class.php:44
dol_getmypid()
Return getmypid() or random PID when function is disabled Some web hosts disable this php function fo...
dolValidElement($element)
Function to say if a value is empty or not.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
Class to manage LDAP features.
Definition: ldap.class.php:30
print
Draft customers invoices.
Definition: index.php:89
if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->don->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1232
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...