sync_groups_ldap2dolibarr.php 8.3 KB

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