dolibarr 23.0.3
sync_groups_ldap2dolibarr.php
Go to the documentation of this file.
1#!/usr/bin/env php
2<?php
30if (!defined('NOSESSION')) {
31 define('NOSESSION', '1');
32}
33
34$sapi_type = php_sapi_name();
35$script_file = basename(__FILE__);
36$path = __DIR__.'/';
37
38// Test if batch mode
39if (substr($sapi_type, 0, 3) == 'cgi') {
40 echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
41 exit(1);
42}
43
44require_once $path."../../htdocs/master.inc.php";
45require_once DOL_DOCUMENT_ROOT.'/core/lib/functionscli.lib.php';
46require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php";
47require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php";
48require_once DOL_DOCUMENT_ROOT."/user/class/user.class.php";
49require_once DOL_DOCUMENT_ROOT."/user/class/usergroup.class.php";
50
59$langs->loadLangs(array("main", "errors"));
60
61// Global variables
62$version = DOL_VERSION;
63$error = 0;
64$forcecommit = 0;
65$confirmed = 0;
66
67$hookmanager->initHooks(array('cli'));
68
69
70/*
71 * Main
72 */
73
74@set_time_limit(0);
75print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
76dol_syslog($script_file." launched with arg ".implode(',', $argv));
77
78// List of fields to get from LDAP
79$required_fields = array(getDolGlobalString('LDAP_KEY_GROUPS'), getDolGlobalString('LDAP_GROUP_FIELD_FULLNAME'), getDolGlobalString('LDAP_GROUP_FIELD_DESCRIPTION'), getDolGlobalString('LDAP_GROUP_FIELD_GROUPMEMBERS'));
80
81// Remove from required_fields all entries not configured in LDAP (empty) and duplicated
82$required_fields = array_unique(array_values(array_filter($required_fields, "dolValidLdapElement2")));
83
84if (!isset($argv[1])) {
85 // print "Usage: $script_file (nocommitiferror|commitiferror) [id_group]\n";
86 print "Usage: $script_file (nocommitiferror|commitiferror) [--server=ldapserverhost] [--excludeuser=user1,user2...] [-y]\n";
87 exit(1);
88}
89
90foreach ($argv as $key => $val) {
91 if ($val == 'commitiferror') {
92 $forcecommit = 1;
93 }
94 if (preg_match('/--server=([^\s]+)$/', $val, $reg)) {
95 $conf->global->LDAP_SERVER_HOST = $reg[1];
96 }
97 if (preg_match('/--excludeuser=([^\s]+)$/', $val, $reg)) {
98 $excludeuser = explode(',', $reg[1]);
99 }
100 if (preg_match('/-y$/', $val, $reg)) {
101 $confirmed = 1;
102 }
103}
104
105print "Mails sending disabled (useless in batch mode)\n";
106$conf->global->MAIN_DISABLE_ALL_MAILS = 1; // We block email sending
107print "\n";
108print "----- Synchronize all records from LDAP database:\n";
109print "host=" . getDolGlobalString('LDAP_SERVER_HOST')."\n";
110print "port=" . getDolGlobalString('LDAP_SERVER_PORT')."\n";
111print "login=" . getDolGlobalString('LDAP_ADMIN_DN')."\n";
112print "pass=".preg_replace('/./i', '*', getDolGlobalString('LDAP_ADMIN_PASS'))."\n";
113print "DN to extract=" . getDolGlobalString('LDAP_GROUP_DN')."\n";
114if (getDolGlobalString('LDAP_GROUP_FILTER')) {
115 print 'Filter=(' . getDolGlobalString('LDAP_GROUP_FILTER').')'."\n"; // Note: filter is defined into function getRecords
116} else {
117 print 'Filter=(' . getDolGlobalString('LDAP_KEY_GROUPS').'=*)'."\n";
118}
119print "----- To Dolibarr database:\n";
120print "type=".$conf->db->type."\n";
121print "host=".$conf->db->host."\n";
122print "port=".$conf->db->port."\n";
123print "login=".$conf->db->user."\n";
124print "database=".$conf->db->name."\n";
125print "----- Options:\n";
126print "commitiferror=".$forcecommit."\n";
127print "Mapped LDAP fields=".implode(',', $required_fields)."\n";
128print "\n";
129
130if (!$confirmed) {
131 print "Hit Enter to continue or CTRL+C to stop...\n";
132 $input = trim(fgets(STDIN));
133}
134
135if (!getDolGlobalString('LDAP_GROUP_DN')) {
136 print $langs->trans("Error").': '.$langs->trans("LDAP setup for groups not defined inside Dolibarr");
137 exit(1);
138}
139
140$ldap = new Ldap();
141$result = $ldap->connectBind();
142if ($result >= 0) {
143 $justthese = array();
144
145 // We disable synchro Dolibarr-LDAP
146 $conf->global->LDAP_SYNCHRO_ACTIVE = 0;
147
148 $ldaprecords = $ldap->getRecords('*', getDolGlobalString('LDAP_GROUP_DN'), getDolGlobalString('LDAP_KEY_GROUPS'), $required_fields, 'group', array(getDolGlobalString('LDAP_GROUP_FIELD_GROUPMEMBERS')));
149 if (is_array($ldaprecords)) {
150 $db->begin();
151
152 // Warning $ldapuser has a key in lowercase
153 foreach ($ldaprecords as $key => $ldapgroup) {
154 $group = new UserGroup($db);
155 $group->fetch(0, $ldapgroup[getDolGlobalString('LDAP_KEY_GROUPS')], true); // Fetch LDAP groups AND members
156 $group->name = $ldapgroup[getDolGlobalString('LDAP_GROUP_FIELD_FULLNAME')] ?? '';
157 $group->nom = $group->name; // For backward compatibility
158 $group->note = $ldapgroup[getDolGlobalString('LDAP_GROUP_FIELD_DESCRIPTION')] ?? '';
159 $group->entity = $conf->entity;
160
161 // print_r($ldapgroup);
162
163 if ($group->id > 0) { // Group update
164 print $langs->transnoentities("GroupUpdate").' # '.$key.': name='.$group->name;
165 $res = $group->update();
166
167 if ($res > 0) {
168 print ' --> Updated group id='.$group->id.' name='.$group->name;
169 } else {
170 $error++;
171 print ' --> '.$res.' '.$group->error;
172 }
173 print "\n";
174 } else { // Group creation
175 print $langs->transnoentities("GroupCreate").' # '.$key.': name='.$group->name;
176 $res = $group->create();
177
178 if ($res > 0) {
179 print ' --> Created group id='.$group->id.' name='.$group->name;
180 } else {
181 $error++;
182 print ' --> '.$res.' '.$group->error;
183 }
184 print "\n";
185 }
186
187 // print_r($group);
188
189 // Management of the users associated with the group
190 // 1 - Association of users in the LDAP group with the Dolibarr group
191 $userList = array();
192 $userIdList = array();
193 $groupMembers = $ldapgroup[getDolGlobalString('LDAP_GROUP_FIELD_GROUPMEMBERS')];
194 if (!is_array($groupMembers)) {
195 $groupMembers = array();
196 }
197 foreach ($groupMembers as $tmpkey => $userdn) { // @phpstan-ignore-line
198 if ($tmpkey === 'count') { // @phpstan-ignore-line
199 continue;
200 }
201 if (empty($userList[$userdn])) { // Récupération de l'utilisateur
202 // Schéma rfc2307: les membres sont listés dans l'attribut memberUid sous form de login uniquement
203 if (getDolGlobalString('LDAP_GROUP_FIELD_GROUPMEMBERS') === 'memberUid') {
204 $userKey = array($userdn);
205 } else { // Pour les autres schémas, les membres sont listés sous forme de DN completes
206 $userFilter = explode(',', $userdn);
207 $userKey = $ldap->getAttributeValues('('.$userFilter[0].')', getDolGlobalString('LDAP_KEY_USERS'));
208 }
209 if (!is_array($userKey)) {
210 continue;
211 }
212
213 $fuser = new User($db);
214
215 if (getDolGlobalString('LDAP_KEY_USERS') == getDolGlobalString('LDAP_FIELD_SID')) {
216 $fuser->fetch(0, '', $userKey[0]); // Chargement du user concerné par le SID
217 } elseif (getDolGlobalString('LDAP_KEY_USERS') == getDolGlobalString('LDAP_FIELD_LOGIN')) {
218 $fuser->fetch(0, $userKey[0]); // Chargement du user concerné par le login
219 }
220
221 $userList[$userdn] = $fuser;
222 } else {
223 $fuser = &$userList[$userdn];
224 }
225
226 $userIdList[$userdn] = $fuser->id;
227
228 // Add the user in the group
229 if (!in_array($fuser->id, array_keys($group->members))) {
230 $fuser->SetInGroup($group->id, $group->entity);
231 echo $fuser->login.' added'."\n";
232 }
233 }
234
235 // 2 - Delete users from the Dolibarr group that are no longer in the LDAP group
236 foreach ($group->members as $guser) {
237 if (!in_array($guser->id, $userIdList)) {
238 $guser->RemoveFromGroup($group->id, $group->entity);
239 echo $guser->login.' removed'."\n";
240 }
241 }
242 }
243
244 if (!$error || $forcecommit) {
245 if (!$error) {
246 print $langs->transnoentities("NoErrorCommitIsDone")."\n";
247 } else {
248 print $langs->transnoentities("ErrorButCommitIsDone")."\n";
249 }
250 $db->commit();
251 } else {
252 print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", (string) $error)."\n";
253 $db->rollback();
254 }
255 print "\n";
256 } else {
257 dol_print_error(null, $ldap->error);
258 $error++;
259 }
260} else {
261 dol_print_error(null, $ldap->error);
262 $error++;
263}
264
265exit($error);
266
267
274function dolValidLdapElement2($element)
275{
276 return (trim($element) != '');
277}
Class to manage LDAP features.
Class to manage user groups.
Class to manage Dolibarr users.
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.
dolValidLdapElement2($element)
Function to say if a value is empty or not.