dolibarr 21.0.0-beta
sync_groups_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";
48require_once DOL_DOCUMENT_ROOT."/user/class/usergroup.class.php";
49
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 ".join(',', $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, "dolValidElement")));
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; // On bloque les mails
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=".$conf->db->user."\n";
123print "database=".$conf->db->name."\n";
124print "----- Options:\n";
125print "commitiferror=".$forcecommit."\n";
126print "Mapped LDAP fields=".join(',', $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('', $ldapgroup[getDolGlobalString('LDAP_KEY_GROUPS')]);
155 $group->name = $ldapgroup[getDolGlobalString('LDAP_GROUP_FIELD_FULLNAME')] ?? null;
156 $group->nom = $group->name; // For backward compatibility
157 $group->note = $ldapgroup[getDolGlobalString('LDAP_GROUP_FIELD_DESCRIPTION')] ?? null;
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 foreach ($ldapgroup[getDolGlobalString('LDAP_GROUP_FIELD_GROUPMEMBERS')] as $tmpkey => $userdn) {
193 if ($tmpkey === 'count') {
194 continue;
195 }
196 if (empty($userList[$userdn])) { // Récupération de l'utilisateur
197 // Schéma rfc2307: les membres sont listés dans l'attribut memberUid sous form de login uniquement
198 if (getDolGlobalString('LDAP_GROUP_FIELD_GROUPMEMBERS') === 'memberUid') {
199 $userKey = array($userdn);
200 } else { // Pour les autres schémas, les membres sont listés sous forme de DN completes
201 $userFilter = explode(',', $userdn);
202 $userKey = $ldap->getAttributeValues('('.$userFilter[0].')', getDolGlobalString('LDAP_KEY_USERS'));
203 }
204 if (!is_array($userKey)) {
205 continue;
206 }
207
208 $fuser = new User($db);
209
210 if (getDolGlobalString('LDAP_KEY_USERS') == getDolGlobalString('LDAP_FIELD_SID')) {
211 $fuser->fetch('', '', $userKey[0]); // Chargement du user concerné par le SID
212 } elseif (getDolGlobalString('LDAP_KEY_USERS') == getDolGlobalString('LDAP_FIELD_LOGIN')) {
213 $fuser->fetch('', $userKey[0]); // Chargement du user concerné par le login
214 }
215
216 $userList[$userdn] = $fuser;
217 } else {
218 $fuser = &$userList[$userdn];
219 }
220
221 $userIdList[$userdn] = $fuser->id;
222
223 // Add the user in the group
224 if (!in_array($fuser->id, array_keys($group->members))) {
225 $fuser->SetInGroup($group->id, $group->entity);
226 echo $fuser->login.' added'."\n";
227 }
228 }
229
230 // 2 - Delete users from the Dolibarr group that are no longer in the LDAP group
231 foreach ($group->members as $guser) {
232 if (!in_array($guser->id, $userIdList)) {
233 $guser->RemoveFromGroup($group->id, $group->entity);
234 echo $guser->login.' removed'."\n";
235 }
236 }
237 }
238
239 if (!$error || $forcecommit) {
240 if (!$error) {
241 print $langs->transnoentities("NoErrorCommitIsDone")."\n";
242 } else {
243 print $langs->transnoentities("ErrorButCommitIsDone")."\n";
244 }
245 $db->commit();
246 } else {
247 print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n";
248 $db->rollback();
249 }
250 print "\n";
251 } else {
252 dol_print_error(null, $ldap->error);
253 $error++;
254 }
255} else {
256 dol_print_error(null, $ldap->error);
257 $error++;
258}
259
260exit($error);
261
262
269function dolValidElement($element)
270{
271 return (trim($element) != '');
272}
Class to manage LDAP features.
Class to manage user groups.
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
dolValidElement($element)
Function to say if a value is empty or not.