authldap.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * LDAP module functions
  5. *
  6. * If the application uses LDAP, these functions are used
  7. * for logging in, searching user info, adding this info
  8. * to the Chamilo database...
  9. - function ldap_authentication_check()
  10. - function ldap_find_user_info()
  11. - function ldap_login()
  12. - function ldap_put_user_info_locally()
  13. - ldap_set_version()
  14. known bugs
  15. ----------
  16. - (fixed 18 june 2003) code has been internationalized
  17. - (fixed 07/05/2003) fixed some non-relative urls or includes
  18. - (fixed 28/04/2003) we now use global config.inc variables instead of local ones
  19. - (fixed 22/04/2003) the last name of a user was restricted to the first part
  20. - (fixed 11/04/2003) the user was never registered as a course manager
  21. version history
  22. ---------------
  23. This historial has been discontinued. Please use the Mercurial logs for more
  24. 3.2 - updated to allow for specific term search for teachers identification
  25. 3.1 - updated code to use database settings, to respect coding conventions as much as possible (camel-case removed) and to allow for non-anonymous login
  26. 3.0 - updated to use ldap_var.inc.php instead of ldap_var.inc (deprecated)
  27. (November 2003)
  28. 2.9 - further changes for new login procedure
  29. - (busy) translating french functions to english
  30. (October 2003)
  31. 2.8 - adapted for new Claroline login procedure
  32. - ldap package now becomes a standard, in auth/ldap
  33. 2.7 - uses more standard LDAP field names: mail, sn, givenname (or cn)
  34. instead of mail, preferredsn, preferredgivenname
  35. there are still
  36. - code cleanup
  37. - fixed bug: dc = xx, dc = yy was configured for UGent
  38. and put literally in the code, this is now a variable
  39. in configuration.php ($LDAPbasedn)
  40. with thanks to
  41. - Stefan De Wannemacker (Ghent University)
  42. - Universite Jean Monet (J Dubois / Michel Courbon)
  43. - Michel Panckoucke for reporting and fixing a bug
  44. - Patrick Cool: fixing security hole
  45. * @author Roan Embrechts
  46. * @version 3.0
  47. * @package chamilo.auth.ldap
  48. */
  49. /**
  50. * Code
  51. */
  52. require('ldap_var.inc.php');
  53. /**
  54. * Check login and password with LDAP
  55. * @return true when login & password both OK, false otherwise
  56. * @author Roan Embrechts (based on code from Universit� Jean Monet)
  57. */
  58. function ldap_login($login, $password) {
  59. //error_log('Entering ldap_login('.$login.','.$password.')',0);
  60. $res = ldap_authentication_check($login, $password);
  61. // res=-1 -> the user does not exist in the ldap database
  62. // res=1 -> invalid password (user does exist)
  63. if ($res==1) { //WRONG PASSWORD
  64. //$errorMessage = "LDAP User or password incorrect, try again.<br />";
  65. if (isset($log)) unset($log); if (isset($uid)) unset($uid);
  66. $loginLdapSucces = false;
  67. }
  68. if ($res==-1) { //WRONG USERNAME
  69. //$errorMessage = "LDAP User or password incorrect, try again.<br />";
  70. $login_ldap_success = false;
  71. }
  72. if ($res==0) { //LOGIN & PASSWORD OK - SUCCES
  73. //$errorMessage = "Successful login w/ LDAP.<br>";
  74. $login_ldap_success = true;
  75. }
  76. //$result = "This is the result: $errorMessage";
  77. $result = $login_ldap_success;
  78. return $result;
  79. }
  80. /**
  81. * Find user info in LDAP
  82. * @return array Array with indexes: "firstname", "name", "email", "employeenumber"
  83. * @author Stefan De Wannemacker
  84. * @author Roan Embrechts
  85. */
  86. function ldap_find_user_info ($login) {
  87. //error_log('Entering ldap_find_user_info('.$login.')',0);
  88. global $ldap_host, $ldap_port, $ldap_basedn, $ldap_rdn, $ldap_pass, $ldap_search_dn;
  89. // basic sequence with LDAP is connect, bind, search,
  90. // interpret search result, close connection
  91. //echo "Connecting ...";
  92. $ldap_connect = ldap_connect( $ldap_host, $ldap_port);
  93. ldap_set_version($ldap_connect);
  94. if ($ldap_connect) {
  95. //echo " Connect to LDAP server successful ";
  96. //echo "Binding ...";
  97. $ldap_bind = false;
  98. $ldap_bind_res = ldap_handle_bind($ldap_connect,$ldap_bind);
  99. if ($ldap_bind_res) {
  100. //echo " LDAP bind successful... ";
  101. //echo " Searching for uid... ";
  102. // Search surname entry
  103. //OLD: $sr=ldap_search($ldapconnect,"dc=rug, dc=ac, dc=be", "uid=$login");
  104. //echo "<p> ldapDc = '$LDAPbasedn' </p>";
  105. if(!empty($ldap_search_dn)) {
  106. $sr=ldap_search($ldap_connect, $ldap_search_dn, "uid=$login");
  107. } else {
  108. $sr=ldap_search($ldap_connect, $ldap_basedn, "uid=$login");
  109. }
  110. //echo " Search result is ".$sr;
  111. //echo " Number of entries returned is ".ldap_count_entries($ldapconnect,$sr);
  112. //echo " Getting entries ...";
  113. $info = ldap_get_entries($ldap_connect, $sr);
  114. //echo "Data for ".$info["count"]." items returned:<p>";
  115. } else {
  116. //echo "LDAP bind failed...";
  117. }
  118. //echo "Closing LDAP connection<hr>";
  119. ldap_close($ldap_connect);
  120. } else {
  121. //echo "<h3>Unable to connect to LDAP server</h3>";
  122. }
  123. //DEBUG: $result["firstname"] = "Jan"; $result["name"] = "De Test"; $result["email"] = "email@ugent.be";
  124. $result["firstname"] = $info[0]["cn"][0];
  125. $result["name"] = $info[0]["sn"][0];
  126. $result["email"] = $info[0]["mail"][0];
  127. $tutor_field = api_get_setting('ldap_filled_tutor_field');
  128. $result[$tutor_field] = $info[0][$tutor_field]; //employeenumber by default
  129. return $result;
  130. }
  131. /**
  132. * This function uses the data from ldap_find_user_info()
  133. * to add the userdata to Chamilo
  134. * "firstname", "name", "email", "isEmployee"
  135. * @author Roan Embrechts
  136. */
  137. function ldap_put_user_info_locally($login, $info_array) {
  138. //error_log('Entering ldap_put_user_info_locally('.$login.',info_array)',0);
  139. global $ldap_pass_placeholder;
  140. global $submitRegistration, $submit, $uname, $email,
  141. $nom, $prenom, $password, $password1, $status;
  142. global $platformLanguage;
  143. global $loginFailed, $uidReset, $_user;
  144. /*----------------------------------------------------------
  145. 1. set the necessary variables
  146. ------------------------------------------------------------ */
  147. $uname = $login;
  148. $email = $info_array["email"];
  149. $nom = $info_array["name"];
  150. $prenom = $info_array["firstname"];
  151. $password = $ldap_pass_placeholder;
  152. $password1 = $ldap_pass_placeholder;
  153. $official_code = '';
  154. define ("STUDENT",5);
  155. define ("COURSEMANAGER",1);
  156. $tutor_field = api_get_setting('ldap_filled_tutor_field');
  157. $tutor_value = api_get_setting('ldap_filled_tutor_field_value');
  158. if(empty($tutor_field)) {
  159. $status = STUDENT;
  160. } else {
  161. if(empty($tutor_value)) {
  162. //in this case, we are assuming that the admin didn't give a criteria
  163. // so that if the field is not empty, it is a tutor
  164. if(!empty($info_array[$tutor_field])) {
  165. $status = COURSEMANAGER;
  166. } else {
  167. $status = STUDENT;
  168. }
  169. } else {
  170. //the tutor_value is filled, so we need to check the contents of the LDAP field
  171. if (is_array($info_array[$tutor_field]) && in_array($tutor_value,$info_array[$tutor_field])) {
  172. $status = COURSEMANAGER;
  173. } else {
  174. $status = STUDENT;
  175. }
  176. }
  177. }
  178. //$official_code = xxx; //example: choose an attribute
  179. /*----------------------------------------------------------
  180. 2. add info to Chamilo
  181. ------------------------------------------------------------ */
  182. require_once(api_get_path(LIBRARY_PATH).'usermanager.lib.php');
  183. $language = api_get_setting('platformLanguage');
  184. if (empty($language)) { $language = 'english'; }
  185. $_userId = UserManager::create_user($prenom, $nom, $status,
  186. $email, $uname, $password, $official_code,
  187. $language,'', '', 'ldap');
  188. //echo "new user added to Chamilo, id = $_userId";
  189. //user_id, username, password, auth_source
  190. /*----------------------------------------------------------
  191. 3. register session
  192. ------------------------------------------------------------ */
  193. $uData['user_id'] = $_userId;
  194. $uData['username'] = $uname;
  195. $uData['auth_source'] = "ldap";
  196. $loginFailed = false;
  197. $uidReset = true;
  198. $_user['user_id'] = $uData['user_id'];
  199. Session::write('_uid', $_uid);
  200. }
  201. /*
  202. * The code of UGent uses these functions to authenticate.
  203. * function AuthVerifEnseignant ($uname, $passwd)
  204. * function AuthVerifEtudiant ($uname, $passwd)
  205. * function Authentif ($uname, $passwd)
  206. * @todo translate the comments and code to english
  207. * @todo let these functions use the variables in config.inc instead of ldap_var.inc
  208. */
  209. //*** variables en entree
  210. // $uname : username entre au clavier
  211. // $passwd : password fournit par l'utilisateur
  212. //*** en sortie : 3 valeurs possibles
  213. // 0 -> authentif reussie
  214. // 1 -> password incorrect
  215. // -1 -> ne fait partie du LDAP
  216. //---------------------------------------------------
  217. // verification de l'existence du membre dans le LDAP
  218. function ldap_authentication_check ($uname, $passwd) {
  219. //error_log('Entering ldap_authentication_check('.$uname.','.$passwd.')',0);
  220. global $ldap_host, $ldap_port, $ldap_basedn, $ldap_host2, $ldap_port2,$ldap_rdn,$ldap_pass;
  221. //error_log('Entering ldap_authentication_check('.$uname.','.$passwd.')',0);
  222. // Establish anonymous connection with LDAP server
  223. // Etablissement de la connexion anonyme avec le serveur LDAP
  224. $ds=ldap_connect($ldap_host,$ldap_port);
  225. ldap_set_version($ds);
  226. $test_bind = false;
  227. $test_bind_res = ldap_handle_bind($ds,$test_bind);
  228. //en cas de probleme on utlise le replica
  229. if ($test_bind_res===false) {
  230. $ds=ldap_connect($ldap_host2,$ldap_port2);
  231. ldap_set_version($ds);
  232. } else {
  233. //error_log('Connected to server '.$ldap_host);
  234. }
  235. if ($ds!==false) {
  236. // Creation du filtre contenant les valeurs saisies par l'utilisateur
  237. $filter="(uid=$uname)";
  238. // Open anonymous LDAP connection
  239. // Ouverture de la connection anonyme ldap
  240. $result=false;
  241. $ldap_bind_res = ldap_handle_bind($ds,$result);
  242. // Execution de la recherche avec $filtre en parametre
  243. //error_log('Searching for '.$filter.' on LDAP server',0);
  244. $sr=ldap_search($ds,$ldap_basedn,$filter);
  245. // La variable $info recoit le resultat de la requete
  246. $info = ldap_get_entries($ds, $sr);
  247. $dn=($info[0]["dn"]);
  248. //affichage debug !! echo"<br> dn = $dn<br> pass = $passwd<br>";
  249. // fermeture de la 1ere connexion
  250. ldap_close($ds);
  251. }
  252. // teste le Distinguish Name de la 1ere connection
  253. if ($dn=="") {
  254. return (-1); // ne fait pas partie de l'annuaire
  255. }
  256. //bug ldap.. si password vide.. retourne vrai !!
  257. if ($passwd=="") {
  258. return(1);
  259. }
  260. // Ouverture de la 2em connection Ldap : connexion user pour verif mot de passe
  261. $ds=ldap_connect($ldap_host,$ldap_port);
  262. ldap_set_version($ds);
  263. if (!$test_bind) {
  264. $ds=ldap_connect($ldap_host2,$ldap_port2);
  265. ldap_set_version($ds);
  266. }
  267. // retour en cas d'erreur de connexion password incorrecte
  268. if (@ldap_bind( $ds, $dn , $passwd) === false) {
  269. return (1); // mot passe invalide
  270. } else {// connection correcte
  271. return (0);
  272. }
  273. } // end of check
  274. /**
  275. * Set the protocol version with version from config file (enables LDAP version 3)
  276. * @param resource The LDAP connexion resource, passed by reference.
  277. * @return void
  278. */
  279. function ldap_set_version(&$resource) {
  280. //error_log('Entering ldap_set_version(&$resource)',0);
  281. global $ldap_version;
  282. if ($ldap_version>2) {
  283. if (ldap_set_option($resource, LDAP_OPT_PROTOCOL_VERSION, 3)) {
  284. //ok - don't do anything
  285. } else {
  286. //failure - should switch back to version 2 by default
  287. }
  288. }
  289. }
  290. /**
  291. * Handle bind (whether authenticated or not)
  292. * @param resource The LDAP handler to which we are connecting (by reference)
  293. * @param resource The LDAP bind handler we will be modifying
  294. * @return boolean Status of the bind assignment. True for success, false for failure.
  295. */
  296. function ldap_handle_bind(&$ldap_handler,&$ldap_bind) {
  297. //error_log('Entering ldap_handle_bind(&$ldap_handler,&$ldap_bind)',0);
  298. global $ldap_rdn,$ldap_pass;
  299. if (!empty($ldap_rdn) and !empty($ldap_pass)) {
  300. //error_log('Trying authenticated login :'.$ldap_rdn.'/'.$ldap_pass,0);
  301. $ldap_bind = ldap_bind($ldap_handler,$ldap_rdn,$ldap_pass);
  302. if (!$ldap_bind) {
  303. //error_log('Authenticated login failed',0);
  304. //try in anonymous mode, you never know...
  305. $ldap_bind = ldap_bind($ldap_handler);
  306. }
  307. } else {
  308. // this is an "anonymous" bind, typically read-only access:
  309. $ldap_bind = ldap_bind($ldap_handler);
  310. }
  311. if (!$ldap_bind) {
  312. return false;
  313. } else {
  314. //error_log('Login finally OK',0);
  315. return true;
  316. }
  317. }
  318. /**
  319. * Get the total number of users on the platform
  320. * @see SortableTable#get_total_number_of_items()
  321. * @author Mustapha Alouani
  322. */
  323. function ldap_get_users() {
  324. global $ldap_basedn, $ldap_host, $ldap_port, $ldap_rdn, $ldap_pass;
  325. $keyword_firstname = trim(Database::escape_string($_GET['keyword_firstname']));
  326. $keyword_lastname = trim(Database::escape_string($_GET['keyword_lastname']));
  327. $keyword_username = trim(Database::escape_string($_GET['keyword_username']));
  328. $keyword_type = Database::escape_string($_GET['keyword_type']);
  329. $ldap_query=array();
  330. if ($keyword_username != "") {
  331. $ldap_query[]="(uid=".$keyword_username."*)";
  332. } else if ($keyword_lastname!=""){
  333. $ldap_query[]="(sn=".$keyword_lastname."*)";
  334. if ($keyword_firstname!="") {
  335. $ldap_query[]="(givenName=".$keyword_firstname."*)";
  336. }
  337. }
  338. if ($keyword_type !="" && $keyword_type !="all") {
  339. $ldap_query[]="(employeeType=".$keyword_type.")";
  340. }
  341. if (count($ldap_query)>1){
  342. $str_query.="(& ";
  343. foreach ($ldap_query as $query){
  344. $str_query.=" $query";
  345. }
  346. $str_query.=" )";
  347. } else {
  348. $str_query=$ldap_query[0];
  349. }
  350. $ds = ldap_connect($ldap_host, $ldap_port);
  351. ldap_set_version($ds);
  352. if ($ds && count($ldap_query)>0) {
  353. $r = false;
  354. $res = ldap_handle_bind($ds, $r);
  355. //$sr = ldap_search($ds, "ou=test-ou,$ldap_basedn", $str_query);
  356. $sr = ldap_search($ds, $ldap_basedn, $str_query);
  357. //echo "Le nombre de resultats est : ".ldap_count_entries($ds,$sr)."<p>";
  358. $info = ldap_get_entries($ds, $sr);
  359. return $info;
  360. } else {
  361. if (count($ldap_query)!=0)
  362. Display :: display_error_message(get_lang('LDAPConnectionError'));
  363. return array();
  364. }
  365. }
  366. /**
  367. * Get the total number of users on the platform
  368. * @see SortableTable#get_total_number_of_items()
  369. * @author Mustapha Alouani
  370. */
  371. function ldap_get_number_of_users() {
  372. $info = ldap_get_users();
  373. if (count($info)>0) {
  374. return $info['count'];
  375. } else {
  376. return 0;
  377. }
  378. }
  379. /**
  380. * Get the users to display on the current page.
  381. * @see SortableTable#get_table_data($from)
  382. * @author Mustapha Alouani
  383. */
  384. function ldap_get_user_data($from, $number_of_items, $column, $direction) {
  385. $users = array();
  386. $is_western_name_order = api_is_western_name_order();
  387. if (isset($_GET['submit'])) {
  388. $info = ldap_get_users();
  389. if ($info['count']>0) {
  390. for ($key = 0; $key < $info["count"]; $key ++) {
  391. $user=array();
  392. // Get uid from dn
  393. //YW: this might be a variation between LDAP 2 and LDAP 3, but in LDAP 3, the uid is in
  394. //the corresponding index of the array
  395. //$dn_array=ldap_explode_dn($info[$key]["dn"],1);
  396. //$user[] = $dn_array[0]; // uid is first key
  397. //$user[] = $dn_array[0]; // uid is first key
  398. $user[] = $info[$key]['uid'][0];
  399. $user[] = $info[$key]['uid'][0];
  400. if ($is_western_name_order) {
  401. $user[] = api_convert_encoding($info[$key]['cn'][0], api_get_system_encoding(), 'UTF-8');
  402. $user[] = api_convert_encoding($info[$key]['sn'][0], api_get_system_encoding(), 'UTF-8');
  403. } else {
  404. $user[] = api_convert_encoding($info[$key]['sn'][0], api_get_system_encoding(), 'UTF-8');
  405. $user[] = api_convert_encoding($info[$key]['cn'][0], api_get_system_encoding(), 'UTF-8');
  406. }
  407. $user[] = $info[$key]['mail'][0];
  408. $outab[] = $info[$key]['eduPersonPrimaryAffiliation'][0]; // Ici "student"
  409. $users[] = $user;
  410. }
  411. } else {
  412. Display :: display_error_message(get_lang('NoUser'));
  413. }
  414. }
  415. return $users;
  416. }
  417. /**
  418. * Build the modify-column of the table
  419. * @param int $user_id The user id
  420. * @param string $url_params
  421. * @return string Some HTML-code with modify-buttons
  422. * @author Mustapha Alouani
  423. */
  424. function modify_filter($user_id,$url_params, $row) {
  425. $url_params_id="id[]=".$row[0];
  426. //$url_params_id="id=".$row[0];
  427. $result .= '<a href="ldap_users_list.php?action=add_user&amp;user_id='.$user_id.'&amp;id_session='.Security::remove_XSS($_GET['id_session']).'&amp;'.$url_params_id.'&amp;sec_token='.$_SESSION['sec_token'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES, api_get_system_encoding()))."'".')) return false;">'.Display::return_icon('add_user.gif', get_lang('AddUsers')).'</a>';
  428. return $result;
  429. }
  430. /**
  431. * Adds a user to the Chamilo database or updates its data
  432. * @param string username (and uid inside LDAP)
  433. * @author Mustapha Alouani
  434. */
  435. function ldap_add_user($login) {
  436. global $ldap_basedn, $ldap_host, $ldap_port, $ldap_rdn, $ldap_pass;
  437. $ds = ldap_connect($ldap_host, $ldap_port);
  438. ldap_set_version($ds);
  439. if ($ds) {
  440. $str_query="(uid=".$login.")";
  441. $r = false;
  442. $res = ldap_handle_bind($ds, $r);
  443. $sr = ldap_search($ds, $ldap_basedn, $str_query);
  444. //echo "Le nombre de resultats est : ".ldap_count_entries($ds,$sr)."<p>";
  445. $info = ldap_get_entries($ds, $sr);
  446. for ($key = 0; $key < $info['count']; $key ++) {
  447. $lastname = api_convert_encoding($info[$key]['sn'][0], api_get_system_encoding(), 'UTF-8');
  448. $firstname = api_convert_encoding($info[$key]['cn'][0], api_get_system_encoding(), 'UTF-8');
  449. $email = $info[$key]['mail'][0];
  450. // Get uid from dn
  451. $dn_array=ldap_explode_dn($info[$key]['dn'],1);
  452. $username = $dn_array[0]; // uid is first key
  453. $outab[] = $info[$key]['edupersonprimaryaffiliation'][0]; // Ici "student"
  454. //$val = ldap_get_values_len($ds, $entry, "userPassword");
  455. //$val = ldap_get_values_len($ds, $info[$key], "userPassword");
  456. //$password = $val[0];
  457. // TODO the password, if encrypted at the source, will be encrypted twice, which makes it useless. Try to fix that.
  458. $password = $info[$key]['userPassword'][0];
  459. $structure=$info[$key]['edupersonprimaryorgunitdn'][0];
  460. $array_structure=explode(",", $structure);
  461. $array_val=explode("=", $array_structure[0]);
  462. $etape=$array_val[1];
  463. $array_val=explode("=", $array_structure[1]);
  464. $annee=$array_val[1];
  465. // Pour faciliter la gestion on ajoute le code "etape-annee"
  466. $official_code=$etape."-".$annee;
  467. $auth_source='ldap';
  468. // Pas de date d'expiration d'etudiant (a recuperer par rapport au shadow expire LDAP)
  469. $expiration_date='0000-00-00 00:00:00';
  470. $active=1;
  471. if(empty($status)){$status = 5;}
  472. if(empty($phone)){$phone = '';}
  473. if(empty($picture_uri)){$picture_uri = '';}
  474. // Ajout de l'utilisateur
  475. if (UserManager::is_username_available($username)) {
  476. $user_id = UserManager::create_user($firstname,$lastname,$status,$email,$username,$password,$official_code,api_get_setting('platformLanguage'),$phone,$picture_uri,$auth_source,$expiration_date,$active);
  477. } else {
  478. $user = UserManager::get_user_info($username);
  479. $user_id=$user['user_id'];
  480. UserManager::update_user($user_id, $firstname, $lastname, $username, null, null, $email, $status, $official_code, $phone, $picture_uri, $expiration_date, $active);
  481. }
  482. }
  483. } else {
  484. Display :: display_error_message(get_lang('LDAPConnectionError'));
  485. }
  486. return $user_id;;
  487. }
  488. /**
  489. * Adds a list of users to one session
  490. * @param array Array of user ids
  491. * @param string Course code
  492. * @return void
  493. */
  494. function ldap_add_user_to_session($UserList, $id_session) {
  495. // Database Table Definitions
  496. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  497. $tbl_session_rel_class = Database::get_main_table(TABLE_MAIN_SESSION_CLASS);
  498. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  499. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  500. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  501. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  502. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  503. $tbl_class = Database::get_main_table(TABLE_MAIN_CLASS);
  504. $tbl_class_user = Database::get_main_table(TABLE_MAIN_CLASS_USER);
  505. $id_session = (int) $id_session;
  506. // Une fois les utilisateurs importer dans la base des utilisateurs, on peux les affecter a� la session
  507. $result=Database::query("SELECT course_code FROM $tbl_session_rel_course " .
  508. "WHERE id_session='$id_session'");
  509. $CourseList=array();
  510. while ($row=Database::fetch_array($result)) {
  511. $CourseList[]=$row['course_code'];
  512. }
  513. foreach ($CourseList as $enreg_course) {
  514. foreach ($UserList as $enreg_user) {
  515. $enreg_user = (int) $enreg_user;
  516. Database::query("INSERT IGNORE ".
  517. " INTO $tbl_session_rel_course_rel_user ".
  518. "(id_session,course_code,id_user) VALUES ".
  519. "('$id_session','$enreg_course','$enreg_user')");
  520. }
  521. $sql = "SELECT COUNT(id_user) as nbUsers ".
  522. " FROM $tbl_session_rel_course_rel_user " .
  523. " WHERE id_session='$id_session' ".
  524. " AND course_code='$enreg_course'";
  525. $rs = Database::query($sql);
  526. list($nbr_users) = Database::fetch_array($rs);
  527. Database::query("UPDATE $tbl_session_rel_course ".
  528. " SET nbr_users=$nbr_users " .
  529. " WHERE id_session='$id_session' ".
  530. " AND course_code='$enreg_course'");
  531. }
  532. foreach ($UserList as $enreg_user) {
  533. $enreg_user = (int) $enreg_user;
  534. Database::query("INSERT IGNORE INTO $tbl_session_rel_user ".
  535. " (id_session, id_user) " .
  536. " VALUES('$id_session','$enreg_user')");
  537. }
  538. // On mets a jour le nombre d'utilisateurs dans la session
  539. $sql = "SELECT COUNT(id_user) as nbUsers FROM $tbl_session_rel_user ".
  540. " WHERE id_session='$id_session' ".
  541. " AND relation_type<>".SESSION_RELATION_TYPE_RRHH." ";
  542. $rs = Database::query($sql);
  543. list($nbr_users) = Database::fetch_array($rs);
  544. Database::query("UPDATE $tbl_session SET nbr_users=$nbr_users ".
  545. " WHERE id='$id_session'");
  546. }