dolibarr 24.0.0-beta
sync_users_ldap2dolibarr.php
Go to the documentation of this file.
1#!/usr/bin/env php
2<?php
29if (!defined('NOSESSION')) {
30 define('NOSESSION', '1');
31}
32
33$sapi_type = php_sapi_name();
34$script_file = basename(__FILE__);
35$path = __DIR__.'/';
36
37// Test if batch mode
38if (substr($sapi_type, 0, 3) == 'cgi') {
39 echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
40 exit(1);
41}
42
43require_once $path."../../htdocs/master.inc.php";
44require_once DOL_DOCUMENT_ROOT.'/core/lib/functionscli.lib.php';
45require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php";
46require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php";
47require_once DOL_DOCUMENT_ROOT."/user/class/user.class.php";
48
57$langs->loadLangs(array("main", "errors"));
58
59// Global variables
60$version = DOL_VERSION;
61$error = 0;
62$forcecommit = 0;
63$excludeuser = array();
64$confirmed = 0;
65
66$hookmanager->initHooks(array('cli'));
67
68
69/*
70 * Main
71 */
72
73@set_time_limit(0);
74print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
75dol_syslog($script_file." launched with arg ".implode(',', $argv));
76
77// List of fields to get from LDAP
78$required_fields = array(
79 getDolGlobalString('LDAP_KEY_USERS'),
80 getDolGlobalString('LDAP_FIELD_FULLNAME'),
81 getDolGlobalString('LDAP_FIELD_NAME'),
82 getDolGlobalString('LDAP_FIELD_FIRSTNAME'),
83 getDolGlobalString('LDAP_FIELD_LOGIN'),
84 getDolGlobalString('LDAP_FIELD_LOGIN_SAMBA'),
85 getDolGlobalString('LDAP_FIELD_PASSWORD'),
86 getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED'),
87 getDolGlobalString('LDAP_FIELD_PHONE'),
88 getDolGlobalString('LDAP_FIELD_FAX'),
89 getDolGlobalString('LDAP_FIELD_MOBILE'),
90 // getDolGlobalString('LDAP_FIELD_ADDRESS'),
91 // getDolGlobalString('LDAP_FIELD_ZIP'),
92 // getDolGlobalString('LDAP_FIELD_TOWN'),
93 // getDolGlobalString('LDAP_FIELD_COUNTRY'),
94 getDolGlobalString('LDAP_FIELD_MAIL'),
95 getDolGlobalString('LDAP_FIELD_TITLE'),
96 getDolGlobalString('LDAP_FIELD_DESCRIPTION'),
97 getDolGlobalString('LDAP_FIELD_SID')
98);
99
100// Remove from required_fields all entries not configured in LDAP (empty) and duplicated
101$required_fields = array_unique(array_values(array_filter($required_fields, "dolValidLdapElement3")));
102
103if (!isset($argv[1])) {
104 print "Usage: $script_file (nocommitiferror|commitiferror) [--server=ldapserverhost] [--excludeuser=user1,user2...] [-y]\n";
105 exit(1);
106}
107
108foreach ($argv as $key => $val) {
109 if ($val == 'commitiferror') {
110 $forcecommit = 1;
111 }
112 if (preg_match('/--server=([^\s]+)$/', $val, $reg)) {
113 $conf->global->LDAP_SERVER_HOST = $reg[1];
114 }
115 if (preg_match('/--excludeuser=([^\s]+)$/', $val, $reg)) {
116 $excludeuser = explode(',', $reg[1]);
117 }
118 if (preg_match('/-y$/', $val, $reg)) {
119 $confirmed = 1;
120 }
121}
122
123print "Mails sending disabled (useless in batch mode)\n";
124$conf->global->MAIN_DISABLE_ALL_MAILS = 1; // On bloque les mails
125print "\n";
126print "----- Synchronize all records from LDAP database:\n";
127print "host=" . getDolGlobalString('LDAP_SERVER_HOST')."\n";
128print "port=" . getDolGlobalString('LDAP_SERVER_PORT')."\n";
129print "login=" . getDolGlobalString('LDAP_ADMIN_DN')."\n";
130print "pass=".preg_replace('/./i', '*', getDolGlobalString('LDAP_ADMIN_PASS'))."\n";
131print "DN to extract=" . getDolGlobalString('LDAP_USER_DN')."\n";
132if (getDolGlobalString('LDAP_FILTER_CONNECTION')) {
133 print 'Filter=(' . getDolGlobalString('LDAP_FILTER_CONNECTION').')'."\n"; // Note: filter is defined into function getRecords
134} else {
135 print 'Filter=(' . getDolGlobalString('LDAP_KEY_USERS').'=*)'."\n";
136}
137print "----- To Dolibarr database:\n";
138print "type=".$conf->db->type."\n";
139print "host=".$conf->db->host."\n";
140print "port=".$conf->db->port."\n";
141print "login=".$conf->db->user."\n";
142print "database=".$conf->db->name."\n";
143print "----- Options:\n";
144print "commitiferror=".$forcecommit."\n";
145print "excludeuser=".implode(',', $excludeuser)."\n";
146print "Mapped LDAP fields=".implode(',', $required_fields)."\n";
147print "\n";
148
149if (!$confirmed) {
150 print "Hit Enter to continue or CTRL+C to stop...\n";
151 $input = trim(fgets(STDIN));
152}
153
154if (!getDolGlobalString('LDAP_USER_DN')) {
155 print $langs->trans("Error").': '.$langs->trans("LDAP setup for users not defined inside Dolibarr");
156 exit(1);
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);
167if ($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 {
183 exit(1);
184}
185
186$ldap = new Ldap();
187$result = $ldap->connectBind();
188if ($result >= 0) {
189 // We disable synchro Dolibarr-LDAP
190 $conf->global->LDAP_SYNCHRO_ACTIVE = 0;
191
192 $ldaprecords = $ldap->getRecords('*', getDolGlobalString('LDAP_USER_DN'), getDolGlobalString('LDAP_KEY_USERS'), $required_fields, 'user'); // Filter on 'user' filter param
193 if (is_array($ldaprecords)) {
194 $db->begin();
195
196 // Warning $ldapuser has a key in lowercase
197 foreach ($ldaprecords as $key => $ldapuser) {
198 // If login into exclude list, we discard record
199 if (in_array($ldapuser[getDolGlobalString('LDAP_FIELD_LOGIN')], $excludeuser)) {
200 print $langs->transnoentities("UserDiscarded").' # '.$key.': login='.$ldapuser[getDolGlobalString('LDAP_FIELD_LOGIN')].' --> Discarded'."\n";
201 continue;
202 }
203
204 $fuser = new User($db);
205
206 if (getDolGlobalString('LDAP_KEY_USERS') == getDolGlobalString('LDAP_FIELD_SID')) {
207 $fuser->fetch(0, '', $ldapuser[getDolGlobalString('LDAP_KEY_USERS')]); // Chargement du user concerné par le SID
208 } elseif (getDolGlobalString('LDAP_KEY_USERS') == getDolGlobalString('LDAP_FIELD_LOGIN')) {
209 $fuser->fetch(0, $ldapuser[getDolGlobalString('LDAP_KEY_USERS')]); // Chargement du user concerné par le login
210 }
211
212 // Propriete membre
213 $fuser->firstname = $ldapuser[getDolGlobalString('LDAP_FIELD_FIRSTNAME')] ?? '';
214 $fuser->lastname = $ldapuser[getDolGlobalString('LDAP_FIELD_NAME')] ?? '';
215 $fuser->login = $ldapuser[getDolGlobalString('LDAP_FIELD_LOGIN')] ?? '';
216 $fuser->pass = $ldapuser[getDolGlobalString('LDAP_FIELD_PASSWORD')] ?? '';
217 $fuser->pass_indatabase_crypted = $ldapuser[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] ?? '';
218
219 // $user->societe;
220 /*
221 * $fuser->address=$ldapuser[getDolGlobalString('LDAP_FIELD_ADDRESS')] ?? null;
222 * $fuser->zip=$ldapuser[getDolGlobalString('LDAP_FIELD_ZIP')] ?? null;
223 * $fuser->town=$ldapuser[getDolGlobalString('LDAP_FIELD_TOWN')] ?? null;
224 * $fuser->country=$ldapuser[getDolGlobalString('LDAP_FIELD_COUNTRY')] ?? null;
225 * $fuser->country_id=$countries[$hashlib2rowid[strtolower($fuser->country)]]['rowid'];
226 * $fuser->country_code=$countries[$hashlib2rowid[strtolower($fuser->country)]]['code'];
227 */
228
229 $fuser->office_phone = $ldapuser[getDolGlobalString('LDAP_FIELD_PHONE')] ?? '';
230 $fuser->user_mobile = $ldapuser[getDolGlobalString('LDAP_FIELD_MOBILE')] ?? '';
231 $fuser->office_fax = $ldapuser[getDolGlobalString('LDAP_FIELD_FAX')] ?? '';
232 $fuser->email = $ldapuser[getDolGlobalString('LDAP_FIELD_MAIL')] ?? '';
233 $fuser->ldap_sid = $ldapuser[getDolGlobalString('LDAP_FIELD_SID')] ?? '';
234
235 $fuser->job = $ldapuser[getDolGlobalString('LDAP_FIELD_TITLE')] ?? '';
236 $fuser->note = $ldapuser[getDolGlobalString('LDAP_FIELD_DESCRIPTION')] ?? null;
237 $fuser->admin = 0;
238 $fuser->socid = 0;
239 $fuser->contact_id = 0;
240 $fuser->fk_member = 0;
241
242 $fuser->status = 1;
243 // TODO : revoir la gestion du status
244 /*
245 * if (isset($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_STATUS')])) {
246 * $fuser->datec=dol_stringtotime($ldapuser[getdolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE')]);
247 * $fuser->datevalid=dol_stringtotime($ldapuser[getdolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE')]);
248 * $fuser->statut=$ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_STATUS')] ?? null;
249 * }
250 */
251 // if ($fuser->statut > 1) $fuser->statut=1;
252
253 // print_r($ldapuser);
254
255 if ($fuser->id > 0) { // User update
256 print $langs->transnoentities("UserUpdate").' # '.$key.': login='.$fuser->login.', fullname='.$fuser->getFullName($langs);
257 $res = $fuser->update($user);
258
259 if ($res < 0) {
260 $error++;
261 print ' --> '.$res.' '.$fuser->error;
262 } else {
263 print ' --> Updated user id='.$fuser->id.' login='.$fuser->login;
264 }
265 } else { // User creation
266 print $langs->transnoentities("UserCreate").' # '.$key.': login='.$fuser->login.', fullname='.$fuser->getFullName($langs);
267 $res = $fuser->create($user);
268
269 if ($res > 0) {
270 print ' --> Created user id='.$fuser->id.' login='.$fuser->login;
271 } else {
272 $error++;
273 print ' --> '.$res.' '.$fuser->error;
274 }
275 }
276 print "\n";
277 // print_r($fuser);
278
279 // Management of the groups
280 // TODO : Review the group management (or script for syncing groups)
281 /*
282 * if(!$error) {
283 * foreach ($ldapuser[getDolGlobalString('LDAP_FIELD_USERGROUPS') as $groupdn) {
284 * $groupdn;
285 * }
286 * }
287 */
288 }
289
290 if (!$error || $forcecommit) {
291 if (!$error) {
292 print $langs->transnoentities("NoErrorCommitIsDone")."\n";
293 } else {
294 print $langs->transnoentities("ErrorButCommitIsDone")."\n";
295 }
296 $db->commit();
297 } else {
298 print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", (string) $error)."\n";
299 $db->rollback();
300 }
301 print "\n";
302 } else {
303 dol_print_error(null, $ldap->error);
304 $error++;
305 }
306} else {
307 dol_print_error(null, $ldap->error);
308 $error++;
309}
310
311exit($error);
312
313
320function dolValidLdapElement3($element)
321{
322 return (trim($element) != '');
323}
Class to manage LDAP features.
Class to manage Dolibarr users.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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.
dolValidLdapElement3($element)
Function to say if a value is empty or not.