authldap.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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. * Note:
  49. * If you are using a firewall, you might need to check port 389 is open in
  50. * order for Chamilo to communicate with the LDAP server.
  51. * See http://support.chamilo.org/issues/4675 for details.
  52. */
  53. /**
  54. * Inclusions
  55. */
  56. use \ChamiloSession as Session;
  57. /**
  58. * Code
  59. */
  60. require 'ldap_var.inc.php';
  61. /**
  62. * Check login and password with LDAP
  63. * @return true when login & password both OK, false otherwise
  64. * @author Roan Embrechts (based on code from Universit� Jean Monet)
  65. */
  66. function ldap_login($login, $password) {
  67. //error_log('Entering ldap_login('.$login.','.$password.')',0);
  68. $res = ldap_authentication_check($login, $password);
  69. // res=-1 -> the user does not exist in the ldap database
  70. // res=1 -> invalid password (user does exist)
  71. if ($res==1) { //WRONG PASSWORD
  72. //$errorMessage = "LDAP User or password incorrect, try again.<br />";
  73. if (isset($log)) unset($log); if (isset($uid)) unset($uid);
  74. $loginLdapSucces = false;
  75. }
  76. if ($res==-1) { //WRONG USERNAME
  77. //$errorMessage = "LDAP User or password incorrect, try again.<br />";
  78. $login_ldap_success = false;
  79. }
  80. if ($res==0) { //LOGIN & PASSWORD OK - SUCCES
  81. //$errorMessage = "Successful login w/ LDAP.<br>";
  82. $login_ldap_success = true;
  83. }
  84. //$result = "This is the result: $errorMessage";
  85. $result = $login_ldap_success;
  86. return $result;
  87. }
  88. /**
  89. * Find user info in LDAP
  90. * @return array Array with indexes: "firstname", "name", "email", "employeenumber"
  91. * @author Stefan De Wannemacker
  92. * @author Roan Embrechts
  93. */
  94. function ldap_find_user_info ($login) {
  95. //error_log('Entering ldap_find_user_info('.$login.')',0);
  96. global $ldap_host, $ldap_port, $ldap_basedn, $ldap_rdn, $ldap_pass, $ldap_search_dn;
  97. // basic sequence with LDAP is connect, bind, search,
  98. // interpret search result, close connection
  99. //echo "Connecting ...";
  100. $ldap_connect = ldap_connect( $ldap_host, $ldap_port);
  101. ldap_set_version($ldap_connect);
  102. if ($ldap_connect) {
  103. //echo " Connect to LDAP server successful ";
  104. //echo "Binding ...";
  105. $ldap_bind = false;
  106. $ldap_bind_res = ldap_handle_bind($ldap_connect,$ldap_bind);
  107. if ($ldap_bind_res) {
  108. //echo " LDAP bind successful... ";
  109. //echo " Searching for uid... ";
  110. // Search surname entry
  111. //OLD: $sr=ldap_search($ldapconnect,"dc=rug, dc=ac, dc=be", "uid=$login");
  112. //echo "<p> ldapDc = '$LDAPbasedn' </p>";
  113. if(!empty($ldap_search_dn)) {
  114. $sr=ldap_search($ldap_connect, $ldap_search_dn, "uid=$login");
  115. } else {
  116. $sr=ldap_search($ldap_connect, $ldap_basedn, "uid=$login");
  117. }
  118. //echo " Search result is ".$sr;
  119. //echo " Number of entries returned is ".ldap_count_entries($ldapconnect,$sr);
  120. //echo " Getting entries ...";
  121. $info = ldap_get_entries($ldap_connect, $sr);
  122. //echo "Data for ".$info["count"]." items returned:<p>";
  123. } else {
  124. //echo "LDAP bind failed...";
  125. }
  126. //echo "Closing LDAP connection<hr>";
  127. ldap_close($ldap_connect);
  128. } else {
  129. //echo "<h3>Unable to connect to LDAP server</h3>";
  130. }
  131. //DEBUG: $result["firstname"] = "Jan"; $result["name"] = "De Test"; $result["email"] = "email@ugent.be";
  132. $result["firstname"] = $info[0]["cn"][0];
  133. $result["name"] = $info[0]["sn"][0];
  134. $result["email"] = $info[0]["mail"][0];
  135. $tutor_field = api_get_setting('ldap_filled_tutor_field');
  136. $result[$tutor_field] = $info[0][$tutor_field]; //employeenumber by default
  137. return $result;
  138. }
  139. /**
  140. * This function uses the data from ldap_find_user_info()
  141. * to add the userdata to Chamilo
  142. * "firstname", "name", "email", "isEmployee"
  143. * @author Roan Embrechts
  144. */
  145. function ldap_put_user_info_locally($login, $info_array) {
  146. //error_log('Entering ldap_put_user_info_locally('.$login.',info_array)',0);
  147. global $ldap_pass_placeholder;
  148. global $submitRegistration, $submit, $uname, $email,
  149. $nom, $prenom, $password, $password1, $status;
  150. global $platformLanguage;
  151. global $loginFailed, $uidReset, $_user;
  152. /*----------------------------------------------------------
  153. 1. set the necessary variables
  154. ------------------------------------------------------------ */
  155. $uname = $login;
  156. $email = $info_array["email"];
  157. $nom = $info_array["name"];
  158. $prenom = $info_array["firstname"];
  159. $password = $ldap_pass_placeholder;
  160. $password1 = $ldap_pass_placeholder;
  161. $official_code = '';
  162. define ("STUDENT",5);
  163. define ("COURSEMANAGER",1);
  164. $tutor_field = api_get_setting('ldap_filled_tutor_field');
  165. $tutor_value = api_get_setting('ldap_filled_tutor_field_value');
  166. if(empty($tutor_field)) {
  167. $status = STUDENT;
  168. } else {
  169. if(empty($tutor_value)) {
  170. //in this case, we are assuming that the admin didn't give a criteria
  171. // so that if the field is not empty, it is a tutor
  172. if(!empty($info_array[$tutor_field])) {
  173. $status = COURSEMANAGER;
  174. } else {
  175. $status = STUDENT;
  176. }
  177. } else {
  178. //the tutor_value is filled, so we need to check the contents of the LDAP field
  179. if (is_array($info_array[$tutor_field]) && in_array($tutor_value,$info_array[$tutor_field])) {
  180. $status = COURSEMANAGER;
  181. } else {
  182. $status = STUDENT;
  183. }
  184. }
  185. }
  186. //$official_code = xxx; //example: choose an attribute
  187. /*----------------------------------------------------------
  188. 2. add info to Chamilo
  189. ------------------------------------------------------------ */
  190. require_once(api_get_path(LIBRARY_PATH).'usermanager.lib.php');
  191. $language = api_get_setting('platformLanguage');
  192. if (empty($language)) { $language = 'english'; }
  193. $_userId = UserManager::create_user($prenom, $nom, $status,
  194. $email, $uname, $password, $official_code,
  195. $language,'', '', 'ldap');
  196. //echo "new user added to Chamilo, id = $_userId";
  197. //user_id, username, password, auth_source
  198. /*----------------------------------------------------------
  199. 3. register session
  200. ------------------------------------------------------------ */
  201. $uData['user_id'] = $_userId;
  202. $uData['username'] = $uname;
  203. $uData['auth_source'] = "ldap";
  204. $loginFailed = false;
  205. $uidReset = true;
  206. $_user['user_id'] = $uData['user_id'];
  207. Session::write('_uid', $_uid);
  208. }
  209. /**
  210. * The code of UGent uses these functions to authenticate.
  211. * function AuthVerifEnseignant ($uname, $passwd)
  212. * function AuthVerifEtudiant ($uname, $passwd)
  213. * function Authentif ($uname, $passwd)
  214. * @todo translate the comments and code to english
  215. * @todo let these functions use the variables in config.inc instead of ldap_var.inc
  216. */
  217. /**
  218. * Checks the existence of a member in LDAP
  219. * @param string username input on keyboard
  220. * @param string password given by user
  221. * @return int 0 if authentication succeeded, 1 if password was incorrect, -1 if it didn't belong to LDAP
  222. */
  223. function ldap_authentication_check ($uname, $passwd) {
  224. //error_log('Entering ldap_authentication_check('.$uname.','.$passwd.')',0);
  225. global $ldap_host, $ldap_port, $ldap_basedn, $ldap_host2, $ldap_port2,$ldap_rdn,$ldap_pass;
  226. //error_log('Entering ldap_authentication_check('.$uname.','.$passwd.')',0);
  227. // Establish anonymous connection with LDAP server
  228. // Etablissement de la connexion anonyme avec le serveur LDAP
  229. $ds=ldap_connect($ldap_host,$ldap_port);
  230. ldap_set_version($ds);
  231. $test_bind = false;
  232. $test_bind_res = ldap_handle_bind($ds,$test_bind);
  233. //if problem, use the replica
  234. if ($test_bind_res===false) {
  235. $ds=ldap_connect($ldap_host2,$ldap_port2);
  236. ldap_set_version($ds);
  237. } else {
  238. //error_log('Connected to server '.$ldap_host);
  239. }
  240. if ($ds!==false) {
  241. //Creation of filter containing values input by the user
  242. // Here it might be necessary to use $filter="(samaccountName=$uname)"; - see http://support.chamilo.org/issues/4675
  243. $filter="(uid=$uname)";
  244. // Open anonymous LDAP connection
  245. $result=false;
  246. $ldap_bind_res = ldap_handle_bind($ds,$result);
  247. // Executing the search with the $filter parametr
  248. //error_log('Searching for '.$filter.' on LDAP server',0);
  249. $sr=ldap_search($ds,$ldap_basedn,$filter);
  250. $info = ldap_get_entries($ds, $sr);
  251. $dn=($info[0]["dn"]);
  252. // debug !! echo"<br> dn = $dn<br> pass = $passwd<br>";
  253. // closing 1st connection
  254. ldap_close($ds);
  255. }
  256. // test the Distinguish Name from the 1st connection
  257. if ($dn=="") {
  258. return (-1); // doesn't belong to the addressbook
  259. }
  260. //bug ldap.. if password empty, return 1!
  261. if ($passwd=="") {
  262. return(1);
  263. }
  264. // Opening 2nd LDAP connection : Connection user for password check
  265. $ds=ldap_connect($ldap_host,$ldap_port);
  266. ldap_set_version($ds);
  267. if (!$test_bind) {
  268. $ds=ldap_connect($ldap_host2,$ldap_port2);
  269. ldap_set_version($ds);
  270. }
  271. // return in case of wrong password connection error
  272. if (@ldap_bind( $ds, $dn , $passwd) === false) {
  273. return (1); // invalid password
  274. } else {// connection successfull
  275. return (0);
  276. }
  277. } // end of check
  278. /**
  279. * Set the protocol version with version from config file (enables LDAP version 3)
  280. * @param resource The LDAP connexion resource, passed by reference.
  281. * @return void
  282. */
  283. function ldap_set_version(&$resource) {
  284. //error_log('Entering ldap_set_version(&$resource)',0);
  285. global $ldap_version;
  286. if ($ldap_version>2) {
  287. if (ldap_set_option($resource, LDAP_OPT_PROTOCOL_VERSION, 3)) {
  288. //ok - don't do anything
  289. } else {
  290. //failure - should switch back to version 2 by default
  291. }
  292. }
  293. }
  294. /**
  295. * Handle bind (whether authenticated or not)
  296. * @param resource The LDAP handler to which we are connecting (by reference)
  297. * @param resource The LDAP bind handler we will be modifying
  298. * @return boolean Status of the bind assignment. True for success, false for failure.
  299. */
  300. function ldap_handle_bind(&$ldap_handler,&$ldap_bind) {
  301. //error_log('Entering ldap_handle_bind(&$ldap_handler,&$ldap_bind)',0);
  302. global $ldap_rdn,$ldap_pass;
  303. if (!empty($ldap_rdn) and !empty($ldap_pass)) {
  304. //error_log('Trying authenticated login :'.$ldap_rdn.'/'.$ldap_pass,0);
  305. $ldap_bind = ldap_bind($ldap_handler,$ldap_rdn,$ldap_pass);
  306. if (!$ldap_bind) {
  307. //error_log('Authenticated login failed',0);
  308. //try in anonymous mode, you never know...
  309. $ldap_bind = ldap_bind($ldap_handler);
  310. }
  311. } else {
  312. // this is an "anonymous" bind, typically read-only access:
  313. $ldap_bind = ldap_bind($ldap_handler);
  314. }
  315. if (!$ldap_bind) {
  316. return false;
  317. } else {
  318. //error_log('Login finally OK',0);
  319. return true;
  320. }
  321. }
  322. /**
  323. * Get the total number of users on the platform
  324. * @see SortableTable#get_total_number_of_items()
  325. * @author Mustapha Alouani
  326. */
  327. function ldap_get_users() {
  328. global $ldap_basedn, $ldap_host, $ldap_port, $ldap_rdn, $ldap_pass;
  329. $keyword_firstname = trim(Database::escape_string($_GET['keyword_firstname']));
  330. $keyword_lastname = trim(Database::escape_string($_GET['keyword_lastname']));
  331. $keyword_username = trim(Database::escape_string($_GET['keyword_username']));
  332. $keyword_type = Database::escape_string($_GET['keyword_type']);
  333. $ldap_query=array();
  334. if ($keyword_username != "") {
  335. $ldap_query[]="(uid=".$keyword_username."*)";
  336. } else if ($keyword_lastname!=""){
  337. $ldap_query[]="(sn=".$keyword_lastname."*)";
  338. if ($keyword_firstname!="") {
  339. $ldap_query[]="(givenName=".$keyword_firstname."*)";
  340. }
  341. }
  342. if ($keyword_type !="" && $keyword_type !="all") {
  343. $ldap_query[]="(employeeType=".$keyword_type.")";
  344. }
  345. if (count($ldap_query)>1){
  346. $str_query.="(& ";
  347. foreach ($ldap_query as $query){
  348. $str_query.=" $query";
  349. }
  350. $str_query.=" )";
  351. } else {
  352. $str_query=$ldap_query[0];
  353. }
  354. $ds = ldap_connect($ldap_host, $ldap_port);
  355. ldap_set_version($ds);
  356. if ($ds && count($ldap_query)>0) {
  357. $r = false;
  358. $res = ldap_handle_bind($ds, $r);
  359. //$sr = ldap_search($ds, "ou=test-ou,$ldap_basedn", $str_query);
  360. $sr = ldap_search($ds, $ldap_basedn, $str_query);
  361. //echo "Le nombre de resultats est : ".ldap_count_entries($ds,$sr)."<p>";
  362. $info = ldap_get_entries($ds, $sr);
  363. return $info;
  364. } else {
  365. if (count($ldap_query)!=0)
  366. Display :: display_error_message(get_lang('LDAPConnectionError'));
  367. return array();
  368. }
  369. }
  370. /**
  371. * Get the total number of users on the platform
  372. * @see SortableTable#get_total_number_of_items()
  373. * @author Mustapha Alouani
  374. */
  375. function ldap_get_number_of_users() {
  376. $info = ldap_get_users();
  377. if (count($info)>0) {
  378. return $info['count'];
  379. } else {
  380. return 0;
  381. }
  382. }
  383. /**
  384. * Get the users to display on the current page.
  385. * @see SortableTable#get_table_data($from)
  386. * @author Mustapha Alouani
  387. */
  388. function ldap_get_user_data($from, $number_of_items, $column, $direction) {
  389. $users = array();
  390. $is_western_name_order = api_is_western_name_order();
  391. if (isset($_GET['submit'])) {
  392. $info = ldap_get_users();
  393. if ($info['count']>0) {
  394. for ($key = 0; $key < $info["count"]; $key ++) {
  395. $user=array();
  396. // Get uid from dn
  397. //YW: this might be a variation between LDAP 2 and LDAP 3, but in LDAP 3, the uid is in
  398. //the corresponding index of the array
  399. //$dn_array=ldap_explode_dn($info[$key]["dn"],1);
  400. //$user[] = $dn_array[0]; // uid is first key
  401. //$user[] = $dn_array[0]; // uid is first key
  402. $user[] = $info[$key]['uid'][0];
  403. $user[] = $info[$key]['uid'][0];
  404. if ($is_western_name_order) {
  405. $user[] = api_convert_encoding($info[$key]['cn'][0], api_get_system_encoding(), 'UTF-8');
  406. $user[] = api_convert_encoding($info[$key]['sn'][0], api_get_system_encoding(), 'UTF-8');
  407. } else {
  408. $user[] = api_convert_encoding($info[$key]['sn'][0], api_get_system_encoding(), 'UTF-8');
  409. $user[] = api_convert_encoding($info[$key]['cn'][0], api_get_system_encoding(), 'UTF-8');
  410. }
  411. $user[] = $info[$key]['mail'][0];
  412. $outab[] = $info[$key]['eduPersonPrimaryAffiliation'][0]; // Ici "student"
  413. $users[] = $user;
  414. }
  415. } else {
  416. Display :: display_error_message(get_lang('NoUser'));
  417. }
  418. }
  419. return $users;
  420. }
  421. /**
  422. * Build the modify-column of the table
  423. * @param int $user_id The user id
  424. * @param string $url_params
  425. * @return string Some HTML-code with modify-buttons
  426. * @author Mustapha Alouani
  427. */
  428. function modify_filter($user_id,$url_params, $row) {
  429. $url_params_id="id[]=".$row[0];
  430. //$url_params_id="id=".$row[0];
  431. $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='.Security::getCurrentToken().'" 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>';
  432. return $result;
  433. }
  434. /**
  435. * Adds a user to the Chamilo database or updates its data
  436. * @param string username (and uid inside LDAP)
  437. * @author Mustapha Alouani
  438. */
  439. function ldap_add_user($login) {
  440. global $ldap_basedn, $ldap_host, $ldap_port, $ldap_rdn, $ldap_pass;
  441. $ds = ldap_connect($ldap_host, $ldap_port);
  442. ldap_set_version($ds);
  443. $user_id = 0;
  444. if ($ds) {
  445. $str_query="(uid=".$login.")";
  446. $r = false;
  447. $res = ldap_handle_bind($ds, $r);
  448. $sr = ldap_search($ds, $ldap_basedn, $str_query);
  449. //echo "Number of results is : ".ldap_count_entries($ds,$sr)."<p>";
  450. $info = ldap_get_entries($ds, $sr);
  451. for ($key = 0; $key < $info['count']; $key ++) {
  452. $user_id = ldap_add_user_by_array($info[$key]);
  453. }
  454. } else {
  455. Display :: display_error_message(get_lang('LDAPConnectionError'));
  456. }
  457. return $user_id;
  458. }
  459. function ldap_add_user_by_array($data, $update_if_exists = true) {
  460. $lastname = api_convert_encoding($data['sn'][0], api_get_system_encoding(), 'UTF-8');
  461. $firstname = api_convert_encoding($data['cn'][0], api_get_system_encoding(), 'UTF-8');
  462. $email = $data['mail'][0];
  463. // Get uid from dn
  464. $dn_array=ldap_explode_dn($data['dn'],1);
  465. $username = $dn_array[0]; // uid is first key
  466. $outab[] = $data['edupersonprimaryaffiliation'][0]; // Here, "student"
  467. //$val = ldap_get_values_len($ds, $entry, "userPassword");
  468. //$val = ldap_get_values_len($ds, $data, "userPassword");
  469. //$password = $val[0];
  470. // TODO the password, if encrypted at the source, will be encrypted twice, which makes it useless. Try to fix that.
  471. $password = $data['userPassword'][0];
  472. $structure=$data['edupersonprimaryorgunitdn'][0];
  473. $array_structure=explode(",", $structure);
  474. $array_val=explode("=", $array_structure[0]);
  475. $etape=$array_val[1];
  476. $array_val=explode("=", $array_structure[1]);
  477. $annee=$array_val[1];
  478. // To ease management, we add the step-year (etape-annee) code
  479. $official_code=$etape."-".$annee;
  480. $auth_source='ldap';
  481. // No expiration date for students (recover from LDAP's shadow expiry)
  482. $expiration_date='0000-00-00 00:00:00';
  483. $active=1;
  484. if(empty($status)){$status = 5;}
  485. if(empty($phone)){$phone = '';}
  486. if(empty($picture_uri)){$picture_uri = '';}
  487. // Adding user
  488. $user_id = 0;
  489. if (UserManager::is_username_available($username)) {
  490. $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);
  491. } else {
  492. if ($update_if_exists) {
  493. $user = UserManager::get_user_info($username);
  494. $user_id=$user['user_id'];
  495. UserManager::update_user($user_id, $firstname, $lastname, $username, null, null, $email, $status, $official_code, $phone, $picture_uri, $expiration_date, $active);
  496. }
  497. }
  498. return $user_id;
  499. }
  500. /**
  501. * Adds a list of users to one session
  502. * @param array Array of user ids
  503. * @param string Course code
  504. * @return void
  505. */
  506. function ldap_add_user_to_session($UserList, $id_session) {
  507. // Database Table Definitions
  508. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  509. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  510. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  511. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  512. $id_session = (int) $id_session;
  513. // Once users are imported in the users base, we can assign them to the session
  514. $result=Database::query("SELECT c_id FROM $tbl_session_rel_course " .
  515. "WHERE id_session='$id_session'");
  516. $CourseList=array();
  517. while ($row=Database::fetch_array($result)) {
  518. $CourseList[]=$row['c_id'];
  519. }
  520. foreach ($CourseList as $enreg_course) {
  521. foreach ($UserList as $enreg_user) {
  522. $enreg_user = (int) $enreg_user;
  523. Database::query("INSERT IGNORE ".
  524. " INTO $tbl_session_rel_course_rel_user ".
  525. "(id_session,c_id,id_user) VALUES ".
  526. "('$id_session','$enreg_course','$enreg_user')");
  527. }
  528. $sql = "SELECT COUNT(id_user) as nbUsers ".
  529. " FROM $tbl_session_rel_course_rel_user " .
  530. " WHERE id_session='$id_session' ".
  531. " AND c_id='$enreg_course'";
  532. $rs = Database::query($sql);
  533. list($nbr_users) = Database::fetch_array($rs);
  534. Database::query("UPDATE $tbl_session_rel_course ".
  535. " SET nbr_users=$nbr_users " .
  536. " WHERE id_session='$id_session' ".
  537. " AND c_id='$enreg_course'");
  538. }
  539. foreach ($UserList as $enreg_user) {
  540. $enreg_user = (int) $enreg_user;
  541. Database::query("INSERT IGNORE INTO $tbl_session_rel_user ".
  542. " (id_session, id_user) " .
  543. " VALUES('$id_session','$enreg_user')");
  544. }
  545. // We update the number of users in the session
  546. $sql = "SELECT COUNT(id_user) as nbUsers FROM $tbl_session_rel_user ".
  547. " WHERE id_session='$id_session' ".
  548. " AND relation_type<>".SESSION_RELATION_TYPE_RRHH." ";
  549. $rs = Database::query($sql);
  550. list($nbr_users) = Database::fetch_array($rs);
  551. Database::query("UPDATE $tbl_session SET nbr_users=$nbr_users ".
  552. " WHERE id='$id_session'");
  553. }
  554. function syncro_users() {
  555. global $ldap_basedn, $ldap_host, $ldap_port, $ldap_rdn, $ldap_pass, $ldap_search_dn;
  556. echo "Connecting ...";
  557. $ldap_connect = ldap_connect( $ldap_host, $ldap_port);
  558. ldap_set_version($ldap_connect);
  559. if ($ldap_connect) {
  560. //echo " Connect to LDAP server successful ";
  561. //echo "Binding ...";
  562. $ldap_bind = false;
  563. $ldap_bind_res = ldap_handle_bind($ldap_connect,$ldap_bind);
  564. if ($ldap_bind_res) {
  565. //echo " LDAP bind successful... ";
  566. //echo " Searching for uid... ";
  567. // Search surname entry
  568. //OLD: $sr=ldap_search($ldapconnect,"dc=rug, dc=ac, dc=be", "uid=$login");
  569. //echo "<p> ldapDc = '$LDAPbasedn' </p>";
  570. $all_user_query = "uid=*";
  571. if(!empty($ldap_search_dn)) {
  572. $sr = ldap_search($ldap_connect, $ldap_search_dn, $all_user_query);
  573. } else {
  574. $sr = ldap_search($ldap_connect, $ldap_basedn, $all_user_query);
  575. }
  576. //echo " Number of entries returned is ".ldap_count_entries($ldapconnect,$sr);
  577. //echo " Getting entries ...";
  578. $info = ldap_get_entries($ldap_connect, $sr);
  579. for ($key = 0; $key < $info['count']; $key ++) {
  580. $user_id = ldap_add_user_by_array($info[$key], false);
  581. if ($user_id) {
  582. echo "User #$user_id created ";
  583. } else {
  584. echo "User was not created ";
  585. }
  586. }
  587. //echo "Data for ".$info["count"]." items returned:<p>";
  588. } else {
  589. //echo "LDAP bind failed...";
  590. }
  591. //echo "Closing LDAP connection<hr>";
  592. ldap_close($ldap_connect);
  593. } else {
  594. //echo "<h3>Unable to connect to LDAP server</h3>";
  595. }
  596. }