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