authldap.php 26 KB

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