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