dolibarr 24.0.0-beta
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 $group->fetch(0, $ldapgroup[getDolGlobalString('LDAP_KEY_GROUPS')], true); // Fetch LDAP groups AND members
155 $group->name = $ldapgroup[getDolGlobalString('LDAP_GROUP_FIELD_FULLNAME')] ?? '';
156 $group->nom = $group->name; // For backward compatibility
157 $group->note = $ldapgroup[getDolGlobalString('LDAP_GROUP_FIELD_DESCRIPTION')] ?? '';
158 $group->entity = $conf->entity;
159
160 // print_r($ldapgroup);
161
162 if ($group->id > 0) { // Group update
163 print $langs->transnoentities("GroupUpdate").' # '.$key.': name='.$group->name;
164 $res = $group->update();
165
166 if ($res > 0) {
167 print ' --> Updated group id='.$group->id.' name='.$group->name;
168 } else {
169 $error++;
170 print ' --> '.$res.' '.$group->error;
171 }
172 print "\n";
173 } else { // Group creation
174 print $langs->transnoentities("GroupCreate").' # '.$key.': name='.$group->name;
175 $res = $group->create();
176
177 if ($res > 0) {
178 print ' --> Created group id='.$group->id.' name='.$group->name;
179 } else {
180 $error++;
181 print ' --> '.$res.' '.$group->error;
182 }
183 print "\n";
184 }
185
186 // print_r($group);
187
188 // Management of the users associated with the group
189 // 1 - Association of users in the LDAP group with the Dolibarr group
190 $userList = array();
191 $userIdList = array();
192 $groupMembers = $ldapgroup[getDolGlobalString('LDAP_GROUP_FIELD_GROUPMEMBERS')];
193 if (!is_array($groupMembers)) {
194 $groupMembers = array();
195 }
196 foreach ($groupMembers as $tmpkey => $userdn) { // @phpstan-ignore-line
197 if ($tmpkey === 'count') { // @phpstan-ignore-line
198 continue;
199 }
200 if (empty($userList[$userdn])) { // Fetch the user
201 // rfc2307 schema: members are listed in the memberUid attribute as login names only
202 if (getDolGlobalString('LDAP_GROUP_FIELD_GROUPMEMBERS') === 'memberUid') {
203 $userKey = array($userdn);
204 } else { // For other schemas, members are listed as full DNs
205 $userFilter = explode(',', $userdn);
206 $userKey = $ldap->getAttributeValues('('.$userFilter[0].')', getDolGlobalString('LDAP_KEY_USERS'));
207 }
208 if (!is_array($userKey)) {
209 continue;
210 }
211
212 $fuser = new User($db);
213
214 if (getDolGlobalString('LDAP_KEY_USERS') == getDolGlobalString('LDAP_FIELD_SID')) {
215 $fuser->fetch(0, '', $userKey[0]); // Load the user matched by SID
216 } elseif (getDolGlobalString('LDAP_KEY_USERS') == getDolGlobalString('LDAP_FIELD_LOGIN')) {
217 $fuser->fetch(0, $userKey[0]); // Load the user matched by login
218 }
219
220 $userList[$userdn] = $fuser;
221 } else {
222 $fuser = &$userList[$userdn];
223 }
224
225 $userIdList[$userdn] = $fuser->id;
226
227 // Add the user in the group
228 if (!in_array($fuser->id, array_keys($group->members))) {
229 $fuser->SetInGroup($group->id, $group->entity);
230 echo $fuser->login.' added'."\n";
231 }
232 }
233
234 // 2 - Delete users from the Dolibarr group that are no longer in the LDAP group
235 foreach ($group->members as $guser) {
236 if (!in_array($guser->id, $userIdList)) {
237 $guser->RemoveFromGroup($group->id, $group->entity);
238 echo $guser->login.' removed'."\n";
239 }
240 }
241 }
242
243 if (!$error || $forcecommit) {
244 if (!$error) {
245 print $langs->transnoentities("NoErrorCommitIsDone")."\n";
246 } else {
247 print $langs->transnoentities("ErrorButCommitIsDone")."\n";
248 }
249 $db->commit();
250 } else {
251 print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", (string) $error)."\n";
252 $db->rollback();
253 }
254 print "\n";
255 } else {
256 dol_print_error(null, $ldap->error);
257 $error++;
258 }
259} else {
260 dol_print_error(null, $ldap->error);
261 $error++;
262}
263
264exit($error);
265
266
273function dolValidLdapElement2($element)
274{
275 return (trim($element) != '');
276}
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:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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.