dolibarr 19.0.3
sync_users_ldap2dolibarr.php
Go to the documentation of this file.
1#!/usr/bin/env php
2<?php
27if (!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
36if (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
41require_once $path."../../htdocs/master.inc.php";
42require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php";
43require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php";
44require_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);
60print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
61dol_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
89if (!isset($argv[1])) {
90 print "Usage: $script_file (nocommitiferror|commitiferror) [--server=ldapserverhost] [--excludeuser=user1,user2...] [-y]\n";
91 exit(-1);
92}
93
94foreach ($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
109print "Mails sending disabled (useless in batch mode)\n";
110$conf->global->MAIN_DISABLE_ALL_MAILS = 1; // On bloque les mails
111print "\n";
112print "----- Synchronize all records from LDAP database:\n";
113print "host=" . getDolGlobalString('LDAP_SERVER_HOST')."\n";
114print "port=" . getDolGlobalString('LDAP_SERVER_PORT')."\n";
115print "login=" . getDolGlobalString('LDAP_ADMIN_DN')."\n";
116print "pass=".preg_replace('/./i', '*', getDolGlobalString('LDAP_ADMIN_PASS'))."\n";
117print "DN to extract=" . getDolGlobalString('LDAP_USER_DN')."\n";
118if (getDolGlobalString('LDAP_FILTER_CONNECTION')) {
119 print 'Filter=(' . getDolGlobalString('LDAP_FILTER_CONNECTION').')'."\n"; // Note: filter is defined into function getRecords
120} else {
121 print 'Filter=(' . getDolGlobalString('LDAP_KEY_USERS').'=*)'."\n";
122}
123print "----- To Dolibarr database:\n";
124print "type=".$conf->db->type."\n";
125print "host=".$conf->db->host."\n";
126print "port=".$conf->db->port."\n";
127print "login=".$conf->db->user."\n";
128print "database=".$conf->db->name."\n";
129print "----- Options:\n";
130print "commitiferror=".$forcecommit."\n";
131print "excludeuser=".join(',', $excludeuser)."\n";
132print "Mapped LDAP fields=".join(',', $required_fields)."\n";
133print "\n";
134
135if (!$confirmed) {
136 print "Hit Enter to continue or CTRL+C to stop...\n";
137 $input = trim(fgets(STDIN));
138}
139
140if (!getDolGlobalString('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);
153if ($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();
174if ($result >= 0) {
175 $justthese = array();
176
177 // We disable synchro Dolibarr-LDAP
178 $conf->global->LDAP_SYNCHRO_ACTIVE = 0;
179
180 $ldaprecords = $ldap->getRecords('*', getDolGlobalString('LDAP_USER_DN'), getDolGlobalString('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[getDolGlobalString('LDAP_FIELD_LOGIN')], $excludeuser)) {
188 print $langs->transnoentities("UserDiscarded").' # '.$key.': login='.$ldapuser[getDolGlobalString('LDAP_FIELD_LOGIN')].' --> Discarded'."\n";
189 continue;
190 }
191
192 $fuser = new User($db);
193
194 if (getDolGlobalString('LDAP_KEY_USERS') == getDolGlobalString('LDAP_FIELD_SID')) {
195 $fuser->fetch('', '', $ldapuser[getDolGlobalString('LDAP_KEY_USERS')]); // Chargement du user concerné par le SID
196 } elseif (getDolGlobalString('LDAP_KEY_USERS') == getDolGlobalString('LDAP_FIELD_LOGIN')) {
197 $fuser->fetch('', $ldapuser[getDolGlobalString('LDAP_KEY_USERS')]); // Chargement du user concerné par le login
198 }
199
200 // Propriete membre
201 $fuser->firstname = $ldapuser[getDolGlobalString('LDAP_FIELD_FIRSTNAME')];
202 $fuser->lastname = $ldapuser[getDolGlobalString('LDAP_FIELD_NAME')];
203 $fuser->login = $ldapuser[getDolGlobalString('LDAP_FIELD_LOGIN')];
204 $fuser->pass = $ldapuser[getDolGlobalString('LDAP_FIELD_PASSWORD')];
205 $fuser->pass_indatabase_crypted = $ldapuser[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')];
206
207 // $user->societe;
208 /*
209 * $fuser->address=$ldapuser[getDolGlobalString('LDAP_FIELD_ADDRESS')];
210 * $fuser->zip=$ldapuser[getDolGlobalString('LDAP_FIELD_ZIP')];
211 * $fuser->town=$ldapuser[getDolGlobalString('LDAP_FIELD_TOWN')];
212 * $fuser->country=$ldapuser[getDolGlobalString('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[getDolGlobalString('LDAP_FIELD_PHONE')];
218 $fuser->user_mobile = $ldapuser[getDolGlobalString('LDAP_FIELD_MOBILE')];
219 $fuser->office_fax = $ldapuser[getDolGlobalString('LDAP_FIELD_FAX')];
220 $fuser->email = $ldapuser[getDolGlobalString('LDAP_FIELD_MAIL')];
221 $fuser->ldap_sid = $ldapuser[getDolGlobalString('LDAP_FIELD_SID')];
222
223 $fuser->job = $ldapuser[getDolGlobalString('LDAP_FIELD_TITLE')];
224 $fuser->note = $ldapuser[getDolGlobalString('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[getDolGlobalString('LDAP_FIELD_MEMBER_STATUS')])) {
234 * $fuser->datec=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
235 * $fuser->datevalid=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
236 * $fuser->statut=$ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_STATUS')];
237 * }
238 */
239 // if ($fuser->statut > 1) $fuser->statut=1;
240
241 // print_r($ldapuser);
242
243 if ($fuser->id > 0) { // User update
244 print $langs->transnoentities("UserUpdate").' # '.$key.': login='.$fuser->login.', fullname='.$fuser->getFullName($langs);
245 $res = $fuser->update($user);
246
247 if ($res < 0) {
248 $error++;
249 print ' --> '.$res.' '.$fuser->error;
250 } else {
251 print ' --> Updated user id='.$fuser->id.' login='.$fuser->login;
252 }
253 } else { // User creation
254 print $langs->transnoentities("UserCreate").' # '.$key.': login='.$fuser->login.', fullname='.$fuser->getFullName($langs);
255 $res = $fuser->create($user);
256
257 if ($res > 0) {
258 print ' --> Created user id='.$fuser->id.' login='.$fuser->login;
259 } else {
260 $error++;
261 print ' --> '.$res.' '.$fuser->error;
262 }
263 }
264 print "\n";
265 // print_r($fuser);
266
267 // Gestion des groupes
268 // TODO : revoir la gestion des groupes (ou script de sync groupes)
269 /*
270 * if(!$error) {
271 * foreach ($ldapuser[getDolGlobalString('LDAP_FIELD_USERGROUPS') as $groupdn) {
272 * $groupdn;
273 * }
274 * }
275 */
276 }
277
278 if (!$error || $forcecommit) {
279 if (!$error) {
280 print $langs->transnoentities("NoErrorCommitIsDone")."\n";
281 } else {
282 print $langs->transnoentities("ErrorButCommitIsDone")."\n";
283 }
284 $db->commit();
285 } else {
286 print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n";
287 $db->rollback();
288 }
289 print "\n";
290 } else {
291 dol_print_error('', $ldap->error);
292 $error++;
293 }
294} else {
295 dol_print_error('', $ldap->error);
296 $error++;
297}
298
299exit($error);
300
301
308function dolValidElement($element)
309{
310 return (trim($element) != '');
311}
Class to manage LDAP features.
Class to manage Dolibarr users.
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...
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
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.