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