authldap.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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_once api_get_path(SYS_CODE_PATH).'auth/external_login/ldap.inc.php';
  61. require 'ldap_var.inc.php';
  62. /**
  63. * Check login and password with LDAP
  64. * @return true when login & password both OK, false otherwise
  65. * @author Roan Embrechts (based on code from Universit� Jean Monet)
  66. */
  67. function ldap_login($login, $password) {
  68. //error_log('Entering ldap_login('.$login.','.$password.')',0);
  69. $res = ldap_authentication_check($login, $password);
  70. // res=-1 -> the user does not exist in the ldap database
  71. // res=1 -> invalid password (user does exist)
  72. if ($res==1) { //WRONG PASSWORD
  73. //$errorMessage = "LDAP User or password incorrect, try again.<br />";
  74. if (isset($log)) unset($log); if (isset($uid)) unset($uid);
  75. $loginLdapSucces = false;
  76. }
  77. if ($res==-1) { //WRONG USERNAME
  78. //$errorMessage = "LDAP User or password incorrect, try again.<br />";
  79. $login_ldap_success = false;
  80. }
  81. if ($res==0) { //LOGIN & PASSWORD OK - SUCCES
  82. //$errorMessage = "Successful login w/ LDAP.<br>";
  83. $login_ldap_success = true;
  84. }
  85. //$result = "This is the result: $errorMessage";
  86. $result = $login_ldap_success;
  87. return $result;
  88. }
  89. /**
  90. * Find user info in LDAP
  91. * @return array Array with indexes: "firstname", "name", "email", "employeenumber"
  92. * @author Stefan De Wannemacker
  93. * @author Roan Embrechts
  94. */
  95. function ldap_find_user_info ($login) {
  96. //error_log('Entering ldap_find_user_info('.$login.')',0);
  97. global $ldap_host, $ldap_port, $ldap_basedn, $ldap_rdn, $ldap_pass, $ldap_search_dn;
  98. // basic sequence with LDAP is connect, bind, search,
  99. // interpret search result, close connection
  100. //echo "Connecting ...";
  101. $ldap_connect = ldap_connect( $ldap_host, $ldap_port);
  102. ldap_set_version($ldap_connect);
  103. if ($ldap_connect) {
  104. //echo " Connect to LDAP server successful ";
  105. //echo "Binding ...";
  106. $ldap_bind = false;
  107. $ldap_bind_res = ldap_handle_bind($ldap_connect,$ldap_bind);
  108. if ($ldap_bind_res) {
  109. //echo " LDAP bind successful... ";
  110. //echo " Searching for uid... ";
  111. // Search surname entry
  112. //OLD: $sr=ldap_search($ldapconnect,"dc=rug, dc=ac, dc=be", "uid=$login");
  113. //echo "<p> ldapDc = '$LDAPbasedn' </p>";
  114. if(!empty($ldap_search_dn)) {
  115. $sr=ldap_search($ldap_connect, $ldap_search_dn, "uid=$login");
  116. } else {
  117. $sr=ldap_search($ldap_connect, $ldap_basedn, "uid=$login");
  118. }
  119. //echo " Search result is ".$sr;
  120. //echo " Number of entries returned is ".ldap_count_entries($ldapconnect,$sr);
  121. //echo " Getting entries ...";
  122. $info = ldap_get_entries($ldap_connect, $sr);
  123. //echo "Data for ".$info["count"]." items returned:<p>";
  124. } else {
  125. //echo "LDAP bind failed...";
  126. }
  127. //echo "Closing LDAP connection<hr>";
  128. ldap_close($ldap_connect);
  129. } else {
  130. //echo "<h3>Unable to connect to LDAP server</h3>";
  131. }
  132. //DEBUG: $result["firstname"] = "Jan"; $result["name"] = "De Test"; $result["email"] = "email@ugent.be";
  133. $result["firstname"] = $info[0]["cn"][0];
  134. $result["name"] = $info[0]["sn"][0];
  135. $result["email"] = $info[0]["mail"][0];
  136. $tutor_field = api_get_setting('ldap_filled_tutor_field');
  137. $result[$tutor_field] = $info[0][$tutor_field]; //employeenumber by default
  138. return $result;
  139. }
  140. /**
  141. * This function uses the data from ldap_find_user_info()
  142. * to add the userdata to Chamilo
  143. * "firstname", "name", "email", "isEmployee"
  144. * @author Roan Embrechts
  145. */
  146. function ldap_put_user_info_locally($login, $info_array) {
  147. //error_log('Entering ldap_put_user_info_locally('.$login.',info_array)',0);
  148. global $ldap_pass_placeholder;
  149. global $submitRegistration, $submit, $uname, $email,
  150. $nom, $prenom, $password, $password1, $status;
  151. global $platformLanguage;
  152. global $loginFailed, $uidReset, $_user;
  153. /*----------------------------------------------------------
  154. 1. set the necessary variables
  155. ------------------------------------------------------------ */
  156. $uname = $login;
  157. $email = $info_array["email"];
  158. $nom = $info_array["name"];
  159. $prenom = $info_array["firstname"];
  160. $password = $ldap_pass_placeholder;
  161. $password1 = $ldap_pass_placeholder;
  162. $official_code = '';
  163. define ("STUDENT",5);
  164. define ("COURSEMANAGER",1);
  165. $tutor_field = api_get_setting('ldap_filled_tutor_field');
  166. $tutor_value = api_get_setting('ldap_filled_tutor_field_value');
  167. if(empty($tutor_field)) {
  168. $status = STUDENT;
  169. } else {
  170. if(empty($tutor_value)) {
  171. //in this case, we are assuming that the admin didn't give a criteria
  172. // so that if the field is not empty, it is a tutor
  173. if(!empty($info_array[$tutor_field])) {
  174. $status = COURSEMANAGER;
  175. } else {
  176. $status = STUDENT;
  177. }
  178. } else {
  179. //the tutor_value is filled, so we need to check the contents of the LDAP field
  180. if (is_array($info_array[$tutor_field]) && in_array($tutor_value,$info_array[$tutor_field])) {
  181. $status = COURSEMANAGER;
  182. } else {
  183. $status = STUDENT;
  184. }
  185. }
  186. }
  187. //$official_code = xxx; //example: choose an attribute
  188. /*----------------------------------------------------------
  189. 2. add info to Chamilo
  190. ------------------------------------------------------------ */
  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, $extldap_config;
  303. $ldap_rdn = $extldap_config['admin_dn'];
  304. $ldap_pass = $extldap_config['admin_password'];
  305. if (!empty($ldap_rdn) and !empty($ldap_pass)) {
  306. //error_log('Trying authenticated login :'.$ldap_rdn.'/'.$ldap_pass,0);
  307. $ldap_bind = ldap_bind($ldap_handler,$ldap_rdn,$ldap_pass);
  308. if (!$ldap_bind) {
  309. //error_log('Authenticated login failed',0);
  310. //try in anonymous mode, you never know...
  311. $ldap_bind = ldap_bind($ldap_handler);
  312. }
  313. } else {
  314. // this is an "anonymous" bind, typically read-only access:
  315. $ldap_bind = ldap_bind($ldap_handler);
  316. }
  317. if (!$ldap_bind) {
  318. return false;
  319. } else {
  320. //error_log('Login finally OK',0);
  321. return true;
  322. }
  323. }
  324. /**
  325. * Get the total number of users on the platform
  326. * @see SortableTable#get_total_number_of_items()
  327. * @author Mustapha Alouani
  328. */
  329. function ldap_get_users() {
  330. global $ldap_basedn, $ldap_host, $ldap_port, $ldap_rdn, $ldap_pass, $ldap_search_dn, $extldap_user_correspondance;
  331. $keyword_firstname = isset($_GET['keyword_firstname']) ? trim(Database::escape_string($_GET['keyword_firstname'])): '';
  332. $keyword_lastname = isset($_GET['keyword_lastname']) ? trim(Database::escape_string($_GET['keyword_lastname'])) : '';
  333. $keyword_username = isset($_GET['keyword_username']) ? trim(Database::escape_string($_GET['keyword_username'])) : '';
  334. $keyword_type = isset($_GET['keyword_type']) ? Database::escape_string($_GET['keyword_type']) : '';
  335. $ldap_query=array();
  336. if ($keyword_username != "") {
  337. $ldap_query[] = str_replace('%username%', $keyword_username, $ldap_search_dn);
  338. } else {
  339. if ($keyword_lastname!=""){
  340. $ldap_query[]="(".$extldap_user_correspondance['lastname']."=".$keyword_lastname."*)";
  341. }
  342. if ($keyword_firstname!="") {
  343. $ldap_query[]="(".$extldap_user_correspondance['firstname']."=".$keyword_firstname."*)";
  344. }
  345. }
  346. if ($keyword_type !="" && $keyword_type !="all") {
  347. $ldap_query[]="(employeeType=".$keyword_type.")";
  348. }
  349. if (count($ldap_query)>1){
  350. $str_query.="(& ";
  351. foreach ($ldap_query as $query){
  352. $str_query.=" $query";
  353. }
  354. $str_query.=" )";
  355. } else {
  356. $str_query= count($ldap_query) > 0 ? $ldap_query[0] : null;
  357. }
  358. $ds = ldap_connect($ldap_host, $ldap_port);
  359. ldap_set_version($ds);
  360. if ($ds && count($ldap_query)>0) {
  361. $r = false;
  362. $res = ldap_handle_bind($ds, $r);
  363. //$sr = ldap_search($ds, "ou=test-ou,$ldap_basedn", $str_query);
  364. $sr = ldap_search($ds, $ldap_basedn, $str_query);
  365. //echo "Le nombre de resultats est : ".ldap_count_entries($ds,$sr)."<p>";
  366. $info = ldap_get_entries($ds, $sr);
  367. return $info;
  368. } else {
  369. if (count($ldap_query)!=0)
  370. Display :: display_error_message(get_lang('LDAPConnectionError'));
  371. return array();
  372. }
  373. }
  374. /**
  375. * Get the total number of users on the platform
  376. * @see SortableTable#get_total_number_of_items()
  377. * @author Mustapha Alouani
  378. */
  379. function ldap_get_number_of_users() {
  380. $info = ldap_get_users();
  381. if (count($info)>0) {
  382. return $info['count'];
  383. } else {
  384. return 0;
  385. }
  386. }
  387. /**
  388. * Get the users to display on the current page.
  389. * @see SortableTable#get_table_data($from)
  390. * @author Mustapha Alouani
  391. */
  392. function ldap_get_user_data($from, $number_of_items, $column, $direction) {
  393. global $extldap_user_correspondance;
  394. $users = array();
  395. $is_western_name_order = api_is_western_name_order();
  396. if (isset($_GET['submit'])) {
  397. $info = ldap_get_users();
  398. if ($info['count']>0) {
  399. for ($key = 0; $key < $info["count"]; $key ++) {
  400. $user=array();
  401. // Get uid from dn
  402. //YW: this might be a variation between LDAP 2 and LDAP 3, but in LDAP 3, the uid is in
  403. //the corresponding index of the array
  404. //$dn_array=ldap_explode_dn($info[$key]["dn"],1);
  405. //$user[] = $dn_array[0]; // uid is first key
  406. //$user[] = $dn_array[0]; // uid is first key
  407. $user[] = $info[$key][$extldap_user_correspondance['username']][0];
  408. $user[] = $info[$key][$extldap_user_correspondance['username']][0];
  409. if ($is_western_name_order) {
  410. $user[] = api_convert_encoding($info[$key][$extldap_user_correspondance['firstname']][0], api_get_system_encoding(), 'UTF-8');
  411. $user[] = api_convert_encoding($info[$key][$extldap_user_correspondance['lastname']][0], api_get_system_encoding(), 'UTF-8');
  412. } else {
  413. $user[] = api_convert_encoding($info[$key][$extldap_user_correspondance['firstname']][0], api_get_system_encoding(), 'UTF-8');
  414. $user[] = api_convert_encoding($info[$key][$extldap_user_correspondance['lastname']][0], api_get_system_encoding(), 'UTF-8');
  415. }
  416. $user[] = $info[$key]['mail'][0];
  417. $user[] = $info[$key][$extldap_user_correspondance['username']][0];
  418. $users[] = $user;
  419. }
  420. } else {
  421. Display :: display_error_message(get_lang('NoUser'));
  422. }
  423. }
  424. return $users;
  425. }
  426. /**
  427. * Build the modify-column of the table
  428. * @param int $user_id The user id
  429. * @param string $url_params
  430. * @return string Some HTML-code with modify-buttons
  431. * @author Mustapha Alouani
  432. */
  433. function modify_filter($user_id,$url_params, $row) {
  434. $query_string="id[]=".$row[0];
  435. if (!empty($_GET['id_session'])){
  436. $query_string .= '&amp;id_session='.Security::remove_XSS($_GET['id_session']);
  437. }
  438. //$url_params_id="id=".$row[0];
  439. $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>';
  440. return $result;
  441. }
  442. /**
  443. * Adds a user to the Chamilo database or updates its data
  444. * @param string username (and uid inside LDAP)
  445. * @author Mustapha Alouani
  446. */
  447. function ldap_add_user($login) {
  448. if ($ldap_user = extldap_authenticate($login, 'nopass', true)) {
  449. return extldap_add_user_by_array($ldap_user);
  450. }
  451. }
  452. function ldap_add_user_by_array($data, $update_if_exists = true) {
  453. $lastname = api_convert_encoding($data['sn'][0], api_get_system_encoding(), 'UTF-8');
  454. $firstname = api_convert_encoding($data['cn'][0], api_get_system_encoding(), 'UTF-8');
  455. $email = $data['mail'][0];
  456. // Get uid from dn
  457. $dn_array=ldap_explode_dn($data['dn'],1);
  458. $username = $dn_array[0]; // uid is first key
  459. $outab[] = $data['edupersonprimaryaffiliation'][0]; // Here, "student"
  460. //$val = ldap_get_values_len($ds, $entry, "userPassword");
  461. //$val = ldap_get_values_len($ds, $data, "userPassword");
  462. //$password = $val[0];
  463. // TODO the password, if encrypted at the source, will be encrypted twice, which makes it useless. Try to fix that.
  464. $password = $data['userPassword'][0];
  465. $structure=$data['edupersonprimaryorgunitdn'][0];
  466. $array_structure=explode(",", $structure);
  467. $array_val=explode("=", $array_structure[0]);
  468. $etape=$array_val[1];
  469. $array_val=explode("=", $array_structure[1]);
  470. $annee=$array_val[1];
  471. // To ease management, we add the step-year (etape-annee) code
  472. $official_code=$etape."-".$annee;
  473. $auth_source='ldap';
  474. // No expiration date for students (recover from LDAP's shadow expiry)
  475. $expiration_date='0000-00-00 00:00:00';
  476. $active=1;
  477. if(empty($status)){$status = 5;}
  478. if(empty($phone)){$phone = '';}
  479. if(empty($picture_uri)){$picture_uri = '';}
  480. // Adding user
  481. $user_id = 0;
  482. if (UserManager::is_username_available($username)) {
  483. $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);
  484. } else {
  485. if ($update_if_exists) {
  486. $user = UserManager::get_user_info($username);
  487. $user_id=$user['user_id'];
  488. UserManager::update_user($user_id, $firstname, $lastname, $username, null, null, $email, $status, $official_code, $phone, $picture_uri, $expiration_date, $active);
  489. }
  490. }
  491. return $user_id;
  492. }
  493. /**
  494. * Adds a list of users to one session
  495. * @param array Array of user ids
  496. * @param string Course code
  497. * @return void
  498. */
  499. function ldap_add_user_to_session($UserList, $id_session) {
  500. // Database Table Definitions
  501. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  502. $tbl_session_rel_class = Database::get_main_table(TABLE_MAIN_SESSION_CLASS);
  503. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  504. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  505. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  506. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  507. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  508. $tbl_class = Database::get_main_table(TABLE_MAIN_CLASS);
  509. $tbl_class_user = Database::get_main_table(TABLE_MAIN_CLASS_USER);
  510. $id_session = (int) $id_session;
  511. // Once users are imported in the users base, we can assign them to the session
  512. $result=Database::query("SELECT c_id FROM $tbl_session_rel_course WHERE session_id ='$id_session'");
  513. $CourseList=array();
  514. while ($row=Database::fetch_array($result)) {
  515. $CourseList[]=$row['c_id'];
  516. }
  517. foreach ($CourseList as $enreg_course) {
  518. foreach ($UserList as $enreg_user) {
  519. $enreg_user = (int) $enreg_user;
  520. Database::query("INSERT IGNORE ".
  521. " INTO $tbl_session_rel_course_rel_user ".
  522. "(session_id,c_id,user_id) VALUES ".
  523. "('$id_session','$enreg_course','$enreg_user')");
  524. }
  525. $sql = "SELECT COUNT(user_id) as nbUsers ".
  526. " FROM $tbl_session_rel_course_rel_user " .
  527. " WHERE session_id='$id_session' ".
  528. " AND c_id='$enreg_course'";
  529. $rs = Database::query($sql);
  530. list($nbr_users) = Database::fetch_array($rs);
  531. Database::query("UPDATE $tbl_session_rel_course ".
  532. " SET nbr_users=$nbr_users " .
  533. " WHERE session_id='$id_session' ".
  534. " AND c_id='$enreg_course'");
  535. }
  536. foreach ($UserList as $enreg_user) {
  537. $enreg_user = (int) $enreg_user;
  538. Database::query("INSERT IGNORE INTO $tbl_session_rel_user ".
  539. " (session_id, user_id, registered_at) " .
  540. " VALUES('$id_session','$enreg_user', '" . api_get_utc_datetime() . "')");
  541. }
  542. // We update the number of users in the session
  543. $sql = "SELECT COUNT(user_id) as nbUsers FROM $tbl_session_rel_user ".
  544. " WHERE session_id='$id_session' ".
  545. " AND relation_type<>".SESSION_RELATION_TYPE_RRHH." ";
  546. $rs = Database::query($sql);
  547. list($nbr_users) = Database::fetch_array($rs);
  548. Database::query("UPDATE $tbl_session SET nbr_users=$nbr_users ".
  549. " WHERE id='$id_session'");
  550. }
  551. function syncro_users() {
  552. global $ldap_basedn, $ldap_host, $ldap_port, $ldap_rdn, $ldap_pass, $ldap_search_dn;
  553. echo "Connecting ...";
  554. $ldap_connect = ldap_connect( $ldap_host, $ldap_port);
  555. ldap_set_version($ldap_connect);
  556. if ($ldap_connect) {
  557. //echo " Connect to LDAP server successful ";
  558. //echo "Binding ...";
  559. $ldap_bind = false;
  560. $ldap_bind_res = ldap_handle_bind($ldap_connect,$ldap_bind);
  561. if ($ldap_bind_res) {
  562. //echo " LDAP bind successful... ";
  563. //echo " Searching for uid... ";
  564. // Search surname entry
  565. //OLD: $sr=ldap_search($ldapconnect,"dc=rug, dc=ac, dc=be", "uid=$login");
  566. //echo "<p> ldapDc = '$LDAPbasedn' </p>";
  567. $all_user_query = "uid=*";
  568. if(!empty($ldap_search_dn)) {
  569. $sr = ldap_search($ldap_connect, $ldap_search_dn, $all_user_query);
  570. } else {
  571. $sr = ldap_search($ldap_connect, $ldap_basedn, $all_user_query);
  572. }
  573. //echo " Number of entries returned is ".ldap_count_entries($ldapconnect,$sr);
  574. //echo " Getting entries ...";
  575. $info = ldap_get_entries($ldap_connect, $sr);
  576. for ($key = 0; $key < $info['count']; $key ++) {
  577. $user_id = ldap_add_user_by_array($info[$key], false);
  578. if ($user_id) {
  579. echo "User #$user_id created ";
  580. } else {
  581. echo "User was not created ";
  582. }
  583. }
  584. //echo "Data for ".$info["count"]." items returned:<p>";
  585. } else {
  586. //echo "LDAP bind failed...";
  587. }
  588. //echo "Closing LDAP connection<hr>";
  589. ldap_close($ldap_connect);
  590. } else {
  591. //echo "<h3>Unable to connect to LDAP server</h3>";
  592. }
  593. }