sync_groups_ldap2dolibarr.php 8.1 KB

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