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