1#!/usr/bin/env php 2<?php 3/** 4 * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org> 5 * Copyright (C) 2006-2012 Laurent Destailleur <eldy@users.sourceforge.net> 6 * Copyright (C) 2013 Maxime Kohlhaas <maxime@atm-consulting.fr> 7 * 8 * This program is free software; you can redistribute it and/or modify 9 * it under the terms of the GNU General Public License as published by 10 * the Free Software Foundation; either version 3 of the License, or 11 * (at your option) any later version. 12 * 13 * This program is distributed in the hope that it will be useful, 14 * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 * GNU General Public License for more details. 17 * 18 * You should have received a copy of the GNU General Public License 19 * along with this program. If not, see <https://www.gnu.org/licenses/>. 20 */ 21 22/** 23 * \file scripts/user/sync_groups_ldap2dolibarr.php 24 * \ingroup ldap member 25 * \brief Script to update groups into Dolibarr from LDAP 26 */ 27 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($conf->global->LDAP_KEY_GROUPS, $conf->global->LDAP_GROUP_FIELD_FULLNAME, $conf->global->LDAP_GROUP_FIELD_DESCRIPTION, $conf->global->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=".$conf->global->LDAP_SERVER_HOST."\n"; 96print "port=".$conf->global->LDAP_SERVER_PORT."\n"; 97print "login=".$conf->global->LDAP_ADMIN_DN."\n"; 98print "pass=".preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)."\n"; 99print "DN to extract=".$conf->global->LDAP_GROUP_DN."\n"; 100if (!empty($conf->global->LDAP_GROUP_FILTER)) { 101 print 'Filter=('.$conf->global->LDAP_GROUP_FILTER.')'."\n"; // Note: filter is defined into function getRecords 102} else { 103 print 'Filter=('.$conf->global->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 (empty($conf->global->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('*', $conf->global->LDAP_GROUP_DN, $conf->global->LDAP_KEY_GROUPS, $required_fields, 'group', array($conf->global->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[$conf->global->LDAP_KEY_GROUPS]); 142 $group->name = $ldapgroup[$conf->global->LDAP_GROUP_FIELD_FULLNAME]; 143 $group->nom = $group->name; // For backward compatibility 144 $group->note = $ldapgroup[$conf->global->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[$conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS] as $key => $userdn) { 180 if ($key === '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 ($conf->global->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].')', $conf->global->LDAP_KEY_USERS); 190 } 191 if (!is_array($userKey)) { 192 continue; 193 } 194 195 $fuser = new User($db); 196 197 if ($conf->global->LDAP_KEY_USERS == $conf->global->LDAP_FIELD_SID) { 198 $fuser->fetch('', '', $userKey[0]); // Chargement du user concerné par le SID 199 } elseif ($conf->global->LDAP_KEY_USERS == $conf->global->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 250/** 251 * Function to say if a value is empty or not 252 * 253 * @param string $element Value to test 254 * @return boolean True of false 255 */ 256function dolValidElement($element) 257{ 258 return (trim($element) != ''); 259} 260