dolibarr 22.0.5
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 $conf->global->LDAP_KEY_USERS,
80 $conf->global->LDAP_FIELD_FULLNAME,
81 $conf->global->LDAP_FIELD_NAME,
82 $conf->global->LDAP_FIELD_FIRSTNAME,
83 $conf->global->LDAP_FIELD_LOGIN,
84 $conf->global->LDAP_FIELD_LOGIN_SAMBA,
85 $conf->global->LDAP_FIELD_PASSWORD,
86 $conf->global->LDAP_FIELD_PASSWORD_CRYPTED,
87 $conf->global->LDAP_FIELD_PHONE,
88 $conf->global->LDAP_FIELD_FAX,
89 $conf->global->LDAP_FIELD_MOBILE,
90 // $conf->global->LDAP_FIELD_ADDRESS,
91 // $conf->global->LDAP_FIELD_ZIP,
92 // $conf->global->LDAP_FIELD_TOWN,
93 // $conf->global->LDAP_FIELD_COUNTRY,
94 $conf->global->LDAP_FIELD_MAIL,
95 $conf->global->LDAP_FIELD_TITLE,
96 $conf->global->LDAP_FIELD_DESCRIPTION,
97 $conf->global->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 {
182 dol_print_error($db);
183 exit(1);
184}
185
186$ldap = new Ldap();
187$result = $ldap->connectBind();
188if ($result >= 0) {
189 $justthese = array();
190
191 // We disable synchro Dolibarr-LDAP
192 $conf->global->LDAP_SYNCHRO_ACTIVE = 0;
193
194 $ldaprecords = $ldap->getRecords('*', getDolGlobalString('LDAP_USER_DN'), getDolGlobalString('LDAP_KEY_USERS'), $required_fields, 'user'); // Filter on 'user' filter param
195 if (is_array($ldaprecords)) {
196 $db->begin();
197
198 // Warning $ldapuser has a key in lowercase
199 foreach ($ldaprecords as $key => $ldapuser) {
200 // If login into exclude list, we discard record
201 if (in_array($ldapuser[getDolGlobalString('LDAP_FIELD_LOGIN')], $excludeuser)) {
202 print $langs->transnoentities("UserDiscarded").' # '.$key.': login='.$ldapuser[getDolGlobalString('LDAP_FIELD_LOGIN')].' --> Discarded'."\n";
203 continue;
204 }
205
206 $fuser = new User($db);
207
208 if (getDolGlobalString('LDAP_KEY_USERS') == getDolGlobalString('LDAP_FIELD_SID')) {
209 $fuser->fetch(0, '', $ldapuser[getDolGlobalString('LDAP_KEY_USERS')]); // Chargement du user concerné par le SID
210 } elseif (getDolGlobalString('LDAP_KEY_USERS') == getDolGlobalString('LDAP_FIELD_LOGIN')) {
211 $fuser->fetch(0, $ldapuser[getDolGlobalString('LDAP_KEY_USERS')]); // Chargement du user concerné par le login
212 }
213
214 // Propriete membre
215 $fuser->firstname = $ldapuser[getDolGlobalString('LDAP_FIELD_FIRSTNAME')] ?? '';
216 $fuser->lastname = $ldapuser[getDolGlobalString('LDAP_FIELD_NAME')] ?? '';
217 $fuser->login = $ldapuser[getDolGlobalString('LDAP_FIELD_LOGIN')] ?? '';
218 $fuser->pass = $ldapuser[getDolGlobalString('LDAP_FIELD_PASSWORD')] ?? '';
219 $fuser->pass_indatabase_crypted = $ldapuser[getDolGlobalString('LDAP_FIELD_PASSWORD_CRYPTED')] ?? '';
220
221 // $user->societe;
222 /*
223 * $fuser->address=$ldapuser[getDolGlobalString('LDAP_FIELD_ADDRESS')] ?? null;
224 * $fuser->zip=$ldapuser[getDolGlobalString('LDAP_FIELD_ZIP')] ?? null;
225 * $fuser->town=$ldapuser[getDolGlobalString('LDAP_FIELD_TOWN')] ?? null;
226 * $fuser->country=$ldapuser[getDolGlobalString('LDAP_FIELD_COUNTRY')] ?? null;
227 * $fuser->country_id=$countries[$hashlib2rowid[strtolower($fuser->country)]]['rowid'];
228 * $fuser->country_code=$countries[$hashlib2rowid[strtolower($fuser->country)]]['code'];
229 */
230
231 $fuser->office_phone = $ldapuser[getDolGlobalString('LDAP_FIELD_PHONE')] ?? '';
232 $fuser->user_mobile = $ldapuser[getDolGlobalString('LDAP_FIELD_MOBILE')] ?? '';
233 $fuser->office_fax = $ldapuser[getDolGlobalString('LDAP_FIELD_FAX')] ?? '';
234 $fuser->email = $ldapuser[getDolGlobalString('LDAP_FIELD_MAIL')] ?? '';
235 $fuser->ldap_sid = $ldapuser[getDolGlobalString('LDAP_FIELD_SID')] ?? '';
236
237 $fuser->job = $ldapuser[getDolGlobalString('LDAP_FIELD_TITLE')] ?? '';
238 $fuser->note = $ldapuser[getDolGlobalString('LDAP_FIELD_DESCRIPTION')] ?? null;
239 $fuser->admin = 0;
240 $fuser->socid = 0;
241 $fuser->contact_id = 0;
242 $fuser->fk_member = 0;
243
244 $fuser->status = 1;
245 // TODO : revoir la gestion du status
246 /*
247 * if (isset($ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_STATUS')])) {
248 * $fuser->datec=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
249 * $fuser->datevalid=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
250 * $fuser->statut=$ldapuser[getDolGlobalString('LDAP_FIELD_MEMBER_STATUS')] ?? null;
251 * }
252 */
253 // if ($fuser->statut > 1) $fuser->statut=1;
254
255 // print_r($ldapuser);
256
257 if ($fuser->id > 0) { // User update
258 print $langs->transnoentities("UserUpdate").' # '.$key.': login='.$fuser->login.', fullname='.$fuser->getFullName($langs);
259 $res = $fuser->update($user);
260
261 if ($res < 0) {
262 $error++;
263 print ' --> '.$res.' '.$fuser->error;
264 } else {
265 print ' --> Updated user id='.$fuser->id.' login='.$fuser->login;
266 }
267 } else { // User creation
268 print $langs->transnoentities("UserCreate").' # '.$key.': login='.$fuser->login.', fullname='.$fuser->getFullName($langs);
269 $res = $fuser->create($user);
270
271 if ($res > 0) {
272 print ' --> Created user id='.$fuser->id.' login='.$fuser->login;
273 } else {
274 $error++;
275 print ' --> '.$res.' '.$fuser->error;
276 }
277 }
278 print "\n";
279 // print_r($fuser);
280
281 // Management of the groups
282 // TODO : Review the group management (or script for syncing groups)
283 /*
284 * if(!$error) {
285 * foreach ($ldapuser[getDolGlobalString('LDAP_FIELD_USERGROUPS') as $groupdn) {
286 * $groupdn;
287 * }
288 * }
289 */
290 }
291
292 if (!$error || $forcecommit) {
293 if (!$error) {
294 print $langs->transnoentities("NoErrorCommitIsDone")."\n";
295 } else {
296 print $langs->transnoentities("ErrorButCommitIsDone")."\n";
297 }
298 $db->commit();
299 } else {
300 print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", (string) $error)."\n";
301 $db->rollback();
302 }
303 print "\n";
304 } else {
305 dol_print_error(null, $ldap->error);
306 $error++;
307 }
308} else {
309 dol_print_error(null, $ldap->error);
310 $error++;
311}
312
313exit($error);
314
315
322function dolValidLdapElement3($element)
323{
324 return (trim($element) != '');
325}
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
dolValidLdapElement3($element)
Function to say if a value is empty or not.