authldap.php 26 KB

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