activedirectory.plugin.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. <?php
  2. /*
  3. @name Connexion AD (LDAP)
  4. @author Valentin CARRUESCO <valentin.carruesco@idleman.fr>
  5. @link http://www.idleman.fr
  6. @licence Copyright IdleCorp
  7. @version 1.0.0
  8. @description Plugin pour l'identification sur Active Directory (LDAP)
  9. */
  10. //Recuperation d'un instance ldap avec les configuraiton serveur
  11. function ldap_instance(){
  12. require_once(__DIR__.SLASH.'ActiveDirectory.class.php');
  13. global $conf;
  14. $ldap = new ActiveDirectory();
  15. $ldap->server = $conf->get('plugin_activedirectory_server');
  16. $ldap->port = $conf->get('plugin_activedirectory_port');
  17. $ldap->userRoot = $conf->get('plugin_activedirectory_user_root');
  18. $ldap->groupRoot = $conf->get('plugin_activedirectory_group_root');
  19. $ldap->domain = $conf->get('plugin_activedirectory_domain');
  20. $ldap->protocolVersion = 3;
  21. return $ldap;
  22. }
  23. //Récuperation de l'ensemble des utilisateurs en LDAP (appellé par User::getAll)
  24. function ldap_plugin_all_users(&$users, $loadRights=false){
  25. require_once(__DIR__.SLASH.'ActiveDirectory.class.php');
  26. global $conf;
  27. if(empty($conf->get('plugin_activedirectory_reader_login')) || empty($conf->get('plugin_activedirectory_reader_password')) || empty($conf->get('plugin_activedirectory_user_root')) ) return;
  28. try{
  29. $ldap = ldap_instance();
  30. $ldap->connect($conf->get('plugin_activedirectory_reader_login'),$conf->get('plugin_activedirectory_reader_password'));
  31. $infos = $ldap->populate($conf->get('plugin_activedirectory_user_root'));
  32. if($infos["count"] == 0) return $ldap->disconnect();
  33. $allUsers = array();
  34. foreach($infos as $info){
  35. if( isset($info['userprincipalname'][0]) && trim($info['userprincipalname'][0])!=''){
  36. $newUser = new User();
  37. ldap_user_fill($ldap,$newUser,$info,true,false);
  38. if($loadRights) user_rank_firm_by_group($newUser);
  39. $manager = new User();
  40. if(isset($info['manager'][0])){
  41. foreach($infos as $info2){
  42. if(!isset($info2['distinguishedname'][0]) || $info2['distinguishedname'][0] != $info['manager'][0]) continue;
  43. ldap_user_fill($ldap,$manager,$info2,false,false);
  44. }
  45. }
  46. $newUser->manager = $manager;
  47. $allUsers[] = $newUser;
  48. }
  49. }
  50. $users = $allUsers;
  51. }catch(Exception $e){
  52. $ldap->disconnect();
  53. throw $e;
  54. }
  55. }
  56. //Récuperation d'un utilisateur précis en LDAP (appellé par User::check)
  57. function ldap_plugin_identification(&$user,$login,$password,$loadRight,$loadManager=true,$noPassword=false){
  58. global $_,$conf;
  59. require_once(__DIR__.SLASH.'ActiveDirectory.class.php');
  60. if($user != false) return;
  61. $ldap = ldap_instance();
  62. try{
  63. if($noPassword){
  64. $ldap->connect($conf->get('plugin_activedirectory_reader_login'), $conf->get('plugin_activedirectory_reader_password'));
  65. }else{
  66. $ldap->connect($login.$ldap->domain, $password);
  67. }
  68. $infos = $ldap->search($conf->get('plugin_activedirectory_user_root'),"(userprincipalname=".$login.$ldap->domain.")");
  69. if($infos["count"]>0){
  70. $user = new User();
  71. ldap_user_fill($ldap,$user,$infos[0],$loadRight,$loadManager);
  72. user_rank_firm_by_group($user);
  73. }
  74. $avatarPath = __ROOT__.FILE_PATH.AVATAR_PATH.$user->login.'.jpg';
  75. if(!file_exists($avatarPath) && isset($user->meta['ldap_avatar'])){
  76. if(!file_exists(__ROOT__.FILE_PATH.AVATAR_PATH)) mkdir(__ROOT__.FILE_PATH.AVATAR_PATH,0755,true);
  77. file_put_contents($avatarPath,base64_decode($user->meta['ldap_avatar']));
  78. }
  79. }catch(Exception $e){
  80. //nothing to do
  81. }
  82. $ldap->disconnect();
  83. }
  84. //Remplissage d'une classe User en fonction des atttributs LDAPS
  85. function ldap_user_fill($ldap,&$user,$infos,$loadRight=false,$loadManager = false){
  86. require_once(__DIR__.SLASH.'ActiveDirectory.class.php');
  87. //Vérifie que le compte n'est pas expiré (nb : 0 et 9223372036854775807 sont les deux valeurs possibles pour un n'expire jamais (allez comprendre la logique microsoft...))
  88. if(isset($infos['accountexpires'][0]) && $infos['accountexpires'][0]!=0 && $infos['accountexpires'][0]!=9223372036854775807){
  89. //Convertion en seconds
  90. $seconds = (float)($infos['accountexpires'][0] / 10000000);
  91. //Convertion d'un timestamp AD en timestamp UNIX
  92. $timestamp = round($seconds - (((1970-1601) * 365.242190) * 86400));
  93. if($timestamp <= time()) return;
  94. }
  95. if(isset($infos['sn'][0])) $user->setName($infos['sn'][0]);
  96. if(isset($infos['givenname'][0])) $user->setFirstName($infos['givenname'][0]);
  97. if(isset($infos['mail'][0])) $user->setMail($infos['mail'][0]);
  98. if(isset($infos['telephonenumber'][0])) $user->setPhone($infos['telephonenumber'][0]);
  99. if(isset($infos['mobile'][0])) $user->setMobile($infos['mobile'][0]);
  100. if(isset($infos['title'][0])) $user->setFunction($infos['title'][0]);
  101. if(isset($infos['samaccountname'][0])) $user->login = mb_strtolower($infos['samaccountname'][0]);
  102. if(isset($infos['department'][0])) $user->service = $infos['department'][0];
  103. if(isset($infos['thumbnailphoto'][0])) $user->meta['ldap_avatar'] = base64_encode($infos['thumbnailphoto'][0]);
  104. if(isset($infos['jpegphoto'][0])) $user->meta['ldap_avatar'] = base64_encode($infos['jpegphoto'][0]);
  105. global $conf;
  106. $metafields = explode(PHP_EOL,$conf->get('plugin_activedirectory_metafields'));
  107. foreach ($metafields as $line) {
  108. $metaInfos = explode(':',$line);
  109. if(count($metaInfos)<4) continue;
  110. list($label,$type,$adslug,$slug) = $metaInfos;
  111. if(isset($infos[$adslug][0])) $user->meta[$slug] = $infos[$adslug][0];
  112. }
  113. if(isset($infos['whencreated'][0]) && strlen($infos['whencreated'][0])>=12 ){
  114. $created = substr($infos['whencreated'][0],0,8).' '.substr($infos['whencreated'][0],8,2).':'.substr($infos['whencreated'][0],10,2);
  115. $user->created = strtotime($created);
  116. }
  117. if(isset($infos['manager'][0])){
  118. $user->manager = $infos['manager'][0];
  119. if($loadManager){
  120. $managerEntry = $ldap->userFromCn($infos['manager'][0]);
  121. if($managerEntry['count'] > 0 ){
  122. $manager = new User();
  123. ldap_user_fill($ldap,$manager,$managerEntry[0],$loadRight,false);
  124. if(isset($infos['sn'][0])) $manager->setName($managerEntry[0]['sn'][0]);
  125. if(isset($infos['givenname'][0])) $manager->setFirstName($managerEntry[0]['givenname'][0]);
  126. if(isset($infos['mail'][0])) $manager->setMail($managerEntry[0]['mail'][0]);
  127. if(isset($infos['telephonenumber'][0])) $manager->setPhone($managerEntry[0]['telephonenumber'][0]);
  128. if(isset($infos['mobile'][0])) $manager->setMobile($managerEntry[0]['mobile'][0]);
  129. if(isset($infos['title'][0])) $manager->function = $managerEntry[0]['title'][0];
  130. if(isset($infos['samaccountname'][0])) $manager->login = mb_strtolower($managerEntry[0]['samaccountname'][0]);
  131. $user->manager = $manager;
  132. }
  133. }
  134. }
  135. $user->origin = 'active_directory';
  136. if($loadRight){
  137. $groups = array();
  138. if(isset($infos['memberof'])){
  139. for($i=0; $i<count($infos['memberof'])-1; ++$i){
  140. $groupCN = $infos['memberof'][$i];
  141. list($group,$root) = explode(',',$groupCN);
  142. list($entity,$group) = explode('=',$group);
  143. //TODO decommenter une fois les pb de perf résolus
  144. //$ldap->recursiveGroups($groups,$groupCN);
  145. $groups[] = $group;
  146. }
  147. }
  148. $user->groups = $groups;
  149. }
  150. }
  151. function activedirectory_user_save(&$user,$userForm,&$response){
  152. if($user->origin != 'active_directory') return;
  153. if($user->login != $userForm->login) throw new Exception("L'identifiant n'est pas modifiable");
  154. if(json_encode($userForm->meta) != json_encode($user->meta)) throw new Exception("Cette fonctionnalité n'est pas disponible pour des utilisateurs active directory");
  155. global $_,$conf;
  156. require_once(__DIR__.SLASH.'ActiveDirectory.class.php');
  157. $response['warning'] = 'Vous êtes sur un compte de société, seules les informations suivantes ont été modifiées :<br/>
  158. - Téléphone<br/>
  159. - Mobile<br/>';
  160. $ldap = ldap_instance();
  161. if($conf->get('plugin_activedirectory_admin_login')=='') throw new Exception("Le compte AD admin n'est pas configuré, veuillez contacter un administrateur");
  162. $ldap->connect($conf->get('plugin_activedirectory_admin_login'),$conf->get('plugin_activedirectory_admin_password'));
  163. $cn = $ldap->cnFromLogin($user->login);
  164. if(!$cn) throw new Exception("Impossible de trouver l'utilsateur dans la base AD");
  165. $user->phone = $userForm->phone;
  166. $user->mobile = $userForm->mobile;
  167. $ldap->set($cn,'telephoneNumber',$userForm->phone);
  168. $ldap->set($cn,'mobile',$userForm->mobile);
  169. $ldap->disconnect();
  170. }
  171. function user_rank_firm_by_group(&$user){
  172. require_once(__DIR__.SLASH.'ActiveDirectoryGroup.class.php');
  173. global $conf, $myFirm;
  174. $firms = array();
  175. $ranks = array();
  176. $groups = ActiveDirectoryGroup::loadAll(array(), null, null, array('*'),1);
  177. if(empty($groups)) throw new Exception("Etablissements et accès non paramétrés, veuillez contacter un administrateur");
  178. if(!isset($user->groups)) $user->groups = array();
  179. foreach($groups as $group){
  180. if(!in_array($group->adgroup,$user->groups)) continue;
  181. $firm = $group->join('firm');
  182. $rank = $group->join('rank');
  183. $firms[$firm->id] = $firm;
  184. if(!isset($ranks[$firm->id])) $ranks[$firm->id] = array();
  185. $ranks[$firm->id][] = $rank;
  186. }
  187. if (!empty($ranks)) {
  188. $user->setFirms($firms);
  189. $defaultFirm = !empty($user->preference('default_firm')) ? $user->preferences['default_firm'] : key($firms);
  190. $myFirm = $firms[$defaultFirm];
  191. }
  192. $user->ranks = $ranks;
  193. $user->loadRights();
  194. }
  195. function activedirectory_action(){
  196. global $_;
  197. require_once(__DIR__.SLASH.'action.php');
  198. }
  199. function activedirectory_plugin_menu(&$settingMenu){
  200. global $_, $myUser;
  201. if($myUser->can('activedirectory','configure'))
  202. $settingMenu[]= array(
  203. 'sort' =>1,
  204. 'url' => 'setting.php?section=activedirectory',
  205. 'icon' => 'fas fa-angle-right',
  206. 'label' => 'Active Directory'
  207. );
  208. }
  209. function activedirectory_plugin_page(){
  210. global $_;
  211. if(in_array($_['section'],array('activedirectory')) && file_exists(__DIR__.SLASH.'setting.'.$_['section'].'.php'))
  212. require_once(__DIR__.SLASH.'setting.'.$_['section'].'.php');
  213. }
  214. function activedirectory_plugin_section(&$sections){
  215. $sections['activedirectory'] = 'Gestion des droits sur les échanges avec l\'AD';
  216. }
  217. function activedirectory_plugin_install($id){
  218. if($id != 'fr.idleman.activedirectory') return;
  219. Entity::install(__DIR__);
  220. }
  221. function activedirectory_plugin_uninstall($id){
  222. if($id != 'fr.idleman.activedirectory') return;
  223. Entity::uninstall(__DIR__);
  224. }
  225. function activedirectory_directory_list(&$usermapping){
  226. foreach ($usermapping as $login => $infos) {
  227. $user = $infos['object'];
  228. //todo à dynamiser en fct de plugin_activedirectory_metafields
  229. if(isset($user->meta['personalPhone'])) $usermapping[$login]['values']['Portable (perso)'] = '<a href="tel: '.$user->meta['personalPhone'].'">'.$user->meta['personalPhone'].'</a>';
  230. }
  231. }
  232. function activedirectory_account_global(){
  233. global $myUser,$conf;
  234. $metafields = explode(PHP_EOL,$conf->get('plugin_activedirectory_metafields'));
  235. ?>
  236. <div class="row">
  237. <?php
  238. foreach ($metafields as $line) :
  239. $metaInfos = explode(':',$line);
  240. if(count($metaInfos)<4) continue;
  241. list($label,$type,$adslug,$slug) = $metaInfos;
  242. ?>
  243. <div class="col-md-6">
  244. <label for="<?php echo $slug; ?>"><?php echo $label ?>:</label>
  245. <input id="<?php echo $slug; ?>" name="<?php echo $slug; ?>" class="form-control-plaintext" readonly="readonly" type="text" value="<?php echo isset($myUser->meta[$slug])?$myUser->meta[$slug]:''; ?>">
  246. </div>
  247. <?php
  248. endforeach;
  249. ?>
  250. </div>
  251. <?php
  252. }
  253. Plugin::addJs('/js/main.js?v=1.0');
  254. Plugin::addCss('/css/main.css?v=1.0');
  255. Plugin::addHook('directory_list',"activedirectory_directory_list");
  256. Plugin::addHook("account_global", "activedirectory_account_global");
  257. Plugin::addHook("install", "activedirectory_plugin_install");
  258. Plugin::addHook("uninstall", "activedirectory_plugin_uninstall");
  259. Plugin::addHook("user_login", "ldap_plugin_identification");
  260. Plugin::addHook("user_load", "ldap_plugin_all_users");
  261. Plugin::addHook("user_save","activedirectory_user_save");
  262. Plugin::addHook("user_rank_firm", "user_rank_firm_by_group");
  263. Plugin::addHook("section", "activedirectory_plugin_section");
  264. Plugin::addHook("action", "activedirectory_action");
  265. Plugin::addHook("menu_setting", "activedirectory_plugin_menu");
  266. Plugin::addHook("content_setting", "activedirectory_plugin_page");
  267. ?>