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