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