dolibarr 25.0.0-alpha
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";
52require_once DOL_DOCUMENT_ROOT.'/core/lib/functionscli.lib.php';
53require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php";
54require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php";
55require_once DOL_DOCUMENT_ROOT."/user/class/user.class.php";
56require_once DOL_DOCUMENT_ROOT."/user/class/usergroup.class.php";
57
58$langs->loadLangs(array("main", "errors"));
59
60// Global variables
61$version = DOL_VERSION;
62$error = 0;
63$forcecommit = 0;
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(getDolGlobalString('LDAP_KEY_GROUPS'), getDolGlobalString('LDAP_GROUP_FIELD_FULLNAME'), getDolGlobalString('LDAP_GROUP_FIELD_DESCRIPTION'), getDolGlobalString('LDAP_GROUP_FIELD_GROUPMEMBERS'));
79
80// Remove from required_fields all entries not configured in LDAP (empty) and duplicated
81$required_fields = array_unique(array_values(array_filter($required_fields, "dolValidLdapElement2")));
82
83if (!isset($argv[1])) {
84 // print "Usage: $script_file (nocommitiferror|commitiferror) [id_group]\n";
85 print "Usage: $script_file (nocommitiferror|commitiferror) [--server=ldapserverhost] [--excludeuser=user1,user2...] [-y]\n";
86 exit(1);
87}
88
89foreach ($argv as $key => $val) {
90 if ($val == 'commitiferror') {
91 $forcecommit = 1;
92 }
93 if (preg_match('/--server=([^\s]+)$/', $val, $reg)) {
94 $conf->global->LDAP_SERVER_HOST = $reg[1];
95 }
96 if (preg_match('/--excludeuser=([^\s]+)$/', $val, $reg)) {
97 $excludeuser = explode(',', $reg[1]);
98 }
99 if (preg_match('/-y$/', $val, $reg)) {
100 $confirmed = 1;
101 }
102}
103
104print "Mails sending disabled (useless in batch mode)\n";
105$conf->global->MAIN_DISABLE_ALL_MAILS = 1; // We block email sending
106print "\n";
107print "----- Synchronize all records from LDAP database:\n";
108print "host=" . getDolGlobalString('LDAP_SERVER_HOST')."\n";
109print "port=" . getDolGlobalString('LDAP_SERVER_PORT')."\n";
110print "login=" . getDolGlobalString('LDAP_ADMIN_DN')."\n";
111print "pass=".preg_replace('/./i', '*', getDolGlobalString('LDAP_ADMIN_PASS'))."\n";
112print "DN to extract=" . getDolGlobalString('LDAP_GROUP_DN')."\n";
113if (getDolGlobalString('LDAP_GROUP_FILTER')) {
114 print 'Filter=(' . getDolGlobalString('LDAP_GROUP_FILTER').')'."\n"; // Note: filter is defined into function getRecords
115} else {
116 print 'Filter=(' . getDolGlobalString('LDAP_KEY_GROUPS').'=*)'."\n";
117}
118print "----- To Dolibarr database:\n";
119print "type=".$conf->db->type."\n";
120print "host=".$conf->db->host."\n";
121print "port=".$conf->db->port."\n";
122print "login=".(string) $conf->db->user."\n";
123print "database=".$conf->db->name."\n";
124print "----- Options:\n";
125print "commitiferror=".$forcecommit."\n";
126print "Mapped LDAP fields=".implode(',', $required_fields)."\n";
127print "\n";
128
129if (!$confirmed) {
130 print "Hit Enter to continue or CTRL+C to stop...\n";
131 $input = trim(fgets(STDIN));
132}
133
134if (!getDolGlobalString('LDAP_GROUP_DN')) {
135 print $langs->trans("Error").': '.$langs->trans("LDAP setup for groups not defined inside Dolibarr");
136 exit(1);
137}
138
139$ldap = new Ldap();
140$result = $ldap->connectBind();
141if ($result >= 0) {
142 $justthese = array();
143
144 // We disable synchro Dolibarr-LDAP
145 $conf->global->LDAP_SYNCHRO_ACTIVE = 0;
146
147 $ldaprecords = $ldap->getRecords('*', getDolGlobalString('LDAP_GROUP_DN'), getDolGlobalString('LDAP_KEY_GROUPS'), $required_fields, 'group', array(getDolGlobalString('LDAP_GROUP_FIELD_GROUPMEMBERS')));
148 if (is_array($ldaprecords)) {
149 $db->begin();
150
151 // Warning $ldapuser has a key in lowercase
152 foreach ($ldaprecords as $key => $ldapgroup) {
153 $group = new UserGroup($db);
154
155 $group->fetch(0, $ldapgroup[getDolGlobalString('LDAP_KEY_GROUPS')], true); // Fetch LDAP groups AND members
156 // fetch() searches by group name, but LDAP_KEY_GROUPS may not be the name (ex: 'member' on Active Directory).
157 // If the group was not found, try again with the name so that existing groups are updated, not created twice.
158 if (empty($group->id) && !empty($ldapgroup[getDolGlobalString('LDAP_GROUP_FIELD_FULLNAME')])) {
159 $group->fetch(0, $ldapgroup[getDolGlobalString('LDAP_GROUP_FIELD_FULLNAME')]);
160 }
161 $group->name = $ldapgroup[getDolGlobalString('LDAP_GROUP_FIELD_FULLNAME')] ?? '';
162 $group->nom = $group->name; // For backward compatibility
163 $group->note = $ldapgroup[getDolGlobalString('LDAP_GROUP_FIELD_DESCRIPTION')] ?? '';
164 $group->entity = $conf->entity;
165
166 // print_r($ldapgroup);
167
168 if ($group->id > 0) { // Group update
169 print $langs->transnoentities("GroupUpdate").' # '.$key.': name='.$group->name;
170 $res = $group->update();
171
172 if ($res > 0) {
173 print ' --> Updated group id='.$group->id.' name='.$group->name;
174 } else {
175 $error++;
176 print ' --> '.$res.' '.$group->error;
177 }
178 print "\n";
179 } else { // Group creation
180 print $langs->transnoentities("GroupCreate").' # '.$key.': name='.$group->name;
181 $res = $group->create();
182
183 if ($res > 0) {
184 print ' --> Created group id='.$group->id.' name='.$group->name;
185 } else {
186 $error++;
187 print ' --> '.$res.' '.$group->error;
188 }
189 print "\n";
190 }
191
192 // print_r($group);
193
194 // Management of the users associated with the group
195 // 1 - Association of users in the LDAP group with the Dolibarr group
196 $userList = array();
197 $userIdList = array();
198 $groupMembers = $ldapgroup[getDolGlobalString('LDAP_GROUP_FIELD_GROUPMEMBERS')];
199 if (!is_array($groupMembers)) {
200 $groupMembers = array();
201 }
202 foreach ($groupMembers as $tmpkey => $userdn) { // @phpstan-ignore-line
203 if ($tmpkey === 'count') { // @phpstan-ignore-line
204 continue;
205 }
206 if (empty($userList[$userdn])) { // Fetch the user
207 // rfc2307 schema: members are listed in the memberUid attribute as login names only
208 if (getDolGlobalString('LDAP_GROUP_FIELD_GROUPMEMBERS') === 'memberUid') {
209 $userKey = array($userdn);
210 } else { // For other schemas, members are listed as full DNs
211 $userFilter = explode(',', $userdn);
212 $userKey = $ldap->getAttributeValues('('.$userFilter[0].')', getDolGlobalString('LDAP_KEY_USERS'));
213 }
214 if (!is_array($userKey)) {
215 continue;
216 }
217
218 $fuser = new User($db);
219
220 if (getDolGlobalString('LDAP_KEY_USERS') == getDolGlobalString('LDAP_FIELD_SID')) {
221 $fuser->fetch(0, '', $userKey[0]); // Load the user matched by SID
222 } elseif (getDolGlobalString('LDAP_KEY_USERS') == getDolGlobalString('LDAP_FIELD_LOGIN')) {
223 $fuser->fetch(0, $userKey[0]); // Load the user matched by login
224 }
225
226 $userList[$userdn] = $fuser;
227 } else {
228 $fuser = &$userList[$userdn];
229 }
230
231 if (empty($fuser->id)) {
232 // Member of the LDAP group but not a Dolibarr user: nothing to link
233 continue;
234 }
235
236 $userIdList[$userdn] = $fuser->id;
237
238 // Add the user in the group
239 if (!in_array($fuser->id, array_keys($group->members))) {
240 $fuser->SetInGroup($group->id, $group->entity);
241 echo $fuser->login.' added'."\n";
242 }
243 }
244
245 // 2 - Delete users from the Dolibarr group that are no longer in the LDAP group
246 foreach ($group->members as $guser) {
247 if (!in_array($guser->id, $userIdList)) {
248 $guser->RemoveFromGroup($group->id, $group->entity);
249 echo $guser->login.' removed'."\n";
250 }
251 }
252 }
253
254 if (!$error || $forcecommit) {
255 if (!$error) {
256 print $langs->transnoentities("NoErrorCommitIsDone")."\n";
257 } else {
258 print $langs->transnoentities("ErrorButCommitIsDone")."\n";
259 }
260 $db->commit();
261 } else {
262 print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", (string) $error)."\n";
263 $db->rollback();
264 }
265 print "\n";
266 } else {
267 dol_print_error(null, $ldap->error);
268 $error++;
269 }
270} else {
271 dol_print_error(null, $ldap->error);
272 $error++;
273}
274
275exit($error);
276
277
284function dolValidLdapElement2($element)
285{
286 return (trim($element) != '');
287}
Class to manage LDAP features.
Class to manage user groups.
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:
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.