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