sync_groups_ldap2dolibarr.php 7.5 KB

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