authldap.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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 true 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('language.platform_language');
  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 The 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. * @return boolean Status of the bind assignment. True for success, false for failure.
  300. */
  301. function ldap_handle_bind(&$ldap_handler,&$ldap_bind) {
  302. //error_log('Entering ldap_handle_bind(&$ldap_handler,&$ldap_bind)',0);
  303. global $ldap_rdn,$ldap_pass, $extldap_config;
  304. $ldap_rdn = $extldap_config['admin_dn'];
  305. $ldap_pass = $extldap_config['admin_password'];
  306. if (!empty($ldap_rdn) and !empty($ldap_pass)) {
  307. //error_log('Trying authenticated login :'.$ldap_rdn.'/'.$ldap_pass,0);
  308. $ldap_bind = ldap_bind($ldap_handler,$ldap_rdn,$ldap_pass);
  309. if (!$ldap_bind) {
  310. //error_log('Authenticated login failed',0);
  311. //try in anonymous mode, you never know...
  312. $ldap_bind = ldap_bind($ldap_handler);
  313. }
  314. } else {
  315. // this is an "anonymous" bind, typically read-only access:
  316. $ldap_bind = ldap_bind($ldap_handler);
  317. }
  318. if (!$ldap_bind) {
  319. return false;
  320. } else {
  321. //error_log('Login finally OK',0);
  322. return true;
  323. }
  324. }
  325. /**
  326. * Get the total number of users on the platform
  327. * @see SortableTable#get_total_number_of_items()
  328. * @author Mustapha Alouani
  329. */
  330. function ldap_get_users() {
  331. global $ldap_basedn, $ldap_host, $ldap_port, $ldap_rdn, $ldap_pass, $ldap_search_dn, $extldap_user_correspondance;
  332. $keyword_firstname = isset($_GET['keyword_firstname']) ? trim(Database::escape_string($_GET['keyword_firstname'])): '';
  333. $keyword_lastname = isset($_GET['keyword_lastname']) ? trim(Database::escape_string($_GET['keyword_lastname'])) : '';
  334. $keyword_username = isset($_GET['keyword_username']) ? trim(Database::escape_string($_GET['keyword_username'])) : '';
  335. $keyword_type = isset($_GET['keyword_type']) ? Database::escape_string($_GET['keyword_type']) : '';
  336. $ldap_query=array();
  337. if ($keyword_username != "") {
  338. $ldap_query[] = str_replace('%username%', $keyword_username, $ldap_search_dn);
  339. } else {
  340. if ($keyword_lastname!=""){
  341. $ldap_query[]="(".$extldap_user_correspondance['lastname']."=".$keyword_lastname."*)";
  342. }
  343. if ($keyword_firstname!="") {
  344. $ldap_query[]="(".$extldap_user_correspondance['firstname']."=".$keyword_firstname."*)";
  345. }
  346. }
  347. if ($keyword_type !="" && $keyword_type !="all") {
  348. $ldap_query[]="(employeeType=".$keyword_type.")";
  349. }
  350. if (count($ldap_query)>1){
  351. $str_query.="(& ";
  352. foreach ($ldap_query as $query){
  353. $str_query.=" $query";
  354. }
  355. $str_query.=" )";
  356. } else {
  357. $str_query= count($ldap_query) > 0 ? $ldap_query[0] : null;
  358. }
  359. $ds = ldap_connect($ldap_host, $ldap_port);
  360. ldap_set_version($ds);
  361. if ($ds && count($ldap_query)>0) {
  362. $r = false;
  363. $res = ldap_handle_bind($ds, $r);
  364. //$sr = ldap_search($ds, "ou=test-ou,$ldap_basedn", $str_query);
  365. $sr = ldap_search($ds, $ldap_basedn, $str_query);
  366. //echo "Le nombre de resultats est : ".ldap_count_entries($ds,$sr)."<p>";
  367. $info = ldap_get_entries($ds, $sr);
  368. return $info;
  369. } else {
  370. if (count($ldap_query)!=0)
  371. Display :: display_error_message(get_lang('LDAPConnectionError'));
  372. return array();
  373. }
  374. }
  375. /**
  376. * Get the total number of users on the platform
  377. * @see SortableTable#get_total_number_of_items()
  378. * @author Mustapha Alouani
  379. */
  380. function ldap_get_number_of_users() {
  381. $info = ldap_get_users();
  382. if (count($info)>0) {
  383. return $info['count'];
  384. } else {
  385. return 0;
  386. }
  387. }
  388. /**
  389. * Get the users to display on the current page.
  390. * @see SortableTable#get_table_data($from)
  391. * @author Mustapha Alouani
  392. */
  393. function ldap_get_user_data($from, $number_of_items, $column, $direction) {
  394. global $extldap_user_correspondance;
  395. $users = array();
  396. $is_western_name_order = api_is_western_name_order();
  397. if (isset($_GET['submit'])) {
  398. $info = ldap_get_users();
  399. if ($info['count']>0) {
  400. for ($key = 0; $key < $info["count"]; $key ++) {
  401. $user=array();
  402. // Get uid from dn
  403. //YW: this might be a variation between LDAP 2 and LDAP 3, but in LDAP 3, the uid is in
  404. //the corresponding index of the array
  405. //$dn_array=ldap_explode_dn($info[$key]["dn"],1);
  406. //$user[] = $dn_array[0]; // uid is first key
  407. //$user[] = $dn_array[0]; // uid is first key
  408. $user[] = $info[$key][$extldap_user_correspondance['username']][0];
  409. $user[] = $info[$key][$extldap_user_correspondance['username']][0];
  410. if ($is_western_name_order) {
  411. $user[] = api_convert_encoding($info[$key][$extldap_user_correspondance['firstname']][0], api_get_system_encoding(), 'UTF-8');
  412. $user[] = api_convert_encoding($info[$key][$extldap_user_correspondance['lastname']][0], api_get_system_encoding(), 'UTF-8');
  413. } else {
  414. $user[] = api_convert_encoding($info[$key][$extldap_user_correspondance['firstname']][0], api_get_system_encoding(), 'UTF-8');
  415. $user[] = api_convert_encoding($info[$key][$extldap_user_correspondance['lastname']][0], api_get_system_encoding(), 'UTF-8');
  416. }
  417. $user[] = $info[$key]['mail'][0];
  418. $user[] = $info[$key][$extldap_user_correspondance['username']][0];
  419. $users[] = $user;
  420. }
  421. } else {
  422. Display :: display_error_message(get_lang('NoUser'));
  423. }
  424. }
  425. return $users;
  426. }
  427. /**
  428. * Build the modify-column of the table
  429. * @param int $user_id The user id
  430. * @param string $url_params
  431. * @return string Some HTML-code with modify-buttons
  432. * @author Mustapha Alouani
  433. */
  434. function modify_filter($user_id,$url_params, $row) {
  435. $query_string="id[]=".$row[0];
  436. if (!empty($_GET['id_session'])){
  437. $query_string .= '&amp;id_session='.Security::remove_XSS($_GET['id_session']);
  438. }
  439. //$url_params_id="id=".$row[0];
  440. $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>';
  441. return $result;
  442. }
  443. /**
  444. * Adds a user to the Chamilo database or updates its data
  445. * @param string username (and uid inside LDAP)
  446. * @author Mustapha Alouani
  447. */
  448. function ldap_add_user($login) {
  449. if ($ldap_user = extldap_authenticate($login, 'nopass', true)) {
  450. return extldap_add_user_by_array($ldap_user);
  451. }
  452. }
  453. function ldap_add_user_by_array($data, $update_if_exists = true) {
  454. $lastname = api_convert_encoding($data['sn'][0], api_get_system_encoding(), 'UTF-8');
  455. $firstname = api_convert_encoding($data['cn'][0], api_get_system_encoding(), 'UTF-8');
  456. $email = $data['mail'][0];
  457. // Get uid from dn
  458. $dn_array=ldap_explode_dn($data['dn'],1);
  459. $username = $dn_array[0]; // uid is first key
  460. $outab[] = $data['edupersonprimaryaffiliation'][0]; // Here, "student"
  461. //$val = ldap_get_values_len($ds, $entry, "userPassword");
  462. //$val = ldap_get_values_len($ds, $data, "userPassword");
  463. //$password = $val[0];
  464. // TODO the password, if encrypted at the source, will be encrypted twice, which makes it useless. Try to fix that.
  465. $password = $data['userPassword'][0];
  466. $structure=$data['edupersonprimaryorgunitdn'][0];
  467. $array_structure=explode(",", $structure);
  468. $array_val=explode("=", $array_structure[0]);
  469. $etape=$array_val[1];
  470. $array_val=explode("=", $array_structure[1]);
  471. $annee=$array_val[1];
  472. // To ease management, we add the step-year (etape-annee) code
  473. $official_code=$etape."-".$annee;
  474. $auth_source='ldap';
  475. // No expiration date for students (recover from LDAP's shadow expiry)
  476. $expiration_date='0000-00-00 00:00:00';
  477. $active=1;
  478. if(empty($status)){$status = 5;}
  479. if(empty($phone)){$phone = '';}
  480. if(empty($picture_uri)){$picture_uri = '';}
  481. // Adding user
  482. $user_id = 0;
  483. if (UserManager::is_username_available($username)) {
  484. $user_id = UserManager::create_user(
  485. $firstname,
  486. $lastname,
  487. $status,
  488. $email,
  489. $username,
  490. $password,
  491. $official_code,
  492. api_get_setting('language.platform_language'),
  493. $phone,
  494. $picture_uri,
  495. $auth_source,
  496. $expiration_date,
  497. $active
  498. );
  499. } else {
  500. if ($update_if_exists) {
  501. $user = api_get_user_info($username);
  502. $user_id=$user['user_id'];
  503. UserManager::update_user($user_id, $firstname, $lastname, $username, null, null, $email, $status, $official_code, $phone, $picture_uri, $expiration_date, $active);
  504. }
  505. }
  506. return $user_id;
  507. }
  508. /**
  509. * Adds a list of users to one session
  510. * @param array Array of user ids
  511. * @param string Course code
  512. * @return void
  513. */
  514. function ldap_add_user_to_session($UserList, $id_session) {
  515. // Database Table Definitions
  516. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  517. $tbl_session_rel_class = Database::get_main_table(TABLE_MAIN_SESSION_CLASS);
  518. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  519. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  520. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  521. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  522. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  523. $tbl_class = Database::get_main_table(TABLE_MAIN_CLASS);
  524. $tbl_class_user = Database::get_main_table(TABLE_MAIN_CLASS_USER);
  525. $id_session = (int) $id_session;
  526. // Once users are imported in the users base, we can assign them to the session
  527. $result=Database::query("SELECT c_id FROM $tbl_session_rel_course WHERE session_id ='$id_session'");
  528. $CourseList=array();
  529. while ($row=Database::fetch_array($result)) {
  530. $CourseList[]=$row['c_id'];
  531. }
  532. foreach ($CourseList as $enreg_course) {
  533. foreach ($UserList as $enreg_user) {
  534. $enreg_user = (int) $enreg_user;
  535. Database::query("INSERT IGNORE ".
  536. " INTO $tbl_session_rel_course_rel_user ".
  537. "(session_id,c_id,user_id) VALUES ".
  538. "('$id_session','$enreg_course','$enreg_user')");
  539. }
  540. $sql = "SELECT COUNT(user_id) as nbUsers ".
  541. " FROM $tbl_session_rel_course_rel_user " .
  542. " WHERE session_id='$id_session' ".
  543. " AND c_id='$enreg_course'";
  544. $rs = Database::query($sql);
  545. list($nbr_users) = Database::fetch_array($rs);
  546. Database::query("UPDATE $tbl_session_rel_course ".
  547. " SET nbr_users=$nbr_users " .
  548. " WHERE session_id='$id_session' ".
  549. " AND c_id='$enreg_course'");
  550. }
  551. foreach ($UserList as $enreg_user) {
  552. $enreg_user = (int) $enreg_user;
  553. Database::query("INSERT IGNORE INTO $tbl_session_rel_user ".
  554. " (session_id, user_id, registered_at) " .
  555. " VALUES('$id_session','$enreg_user', '" . api_get_utc_datetime() . "')");
  556. }
  557. // We update the number of users in the session
  558. $sql = "SELECT COUNT(user_id) as nbUsers FROM $tbl_session_rel_user ".
  559. " WHERE session_id='$id_session' ".
  560. " AND relation_type<>".SESSION_RELATION_TYPE_RRHH." ";
  561. $rs = Database::query($sql);
  562. list($nbr_users) = Database::fetch_array($rs);
  563. Database::query("UPDATE $tbl_session SET nbr_users=$nbr_users ".
  564. " WHERE id='$id_session'");
  565. }
  566. function syncro_users() {
  567. global $ldap_basedn, $ldap_host, $ldap_port, $ldap_rdn, $ldap_pass, $ldap_search_dn;
  568. echo "Connecting ...";
  569. $ldap_connect = ldap_connect( $ldap_host, $ldap_port);
  570. ldap_set_version($ldap_connect);
  571. if ($ldap_connect) {
  572. //echo " Connect to LDAP server successful ";
  573. //echo "Binding ...";
  574. $ldap_bind = false;
  575. $ldap_bind_res = ldap_handle_bind($ldap_connect,$ldap_bind);
  576. if ($ldap_bind_res) {
  577. //echo " LDAP bind successful... ";
  578. //echo " Searching for uid... ";
  579. // Search surname entry
  580. //OLD: $sr=ldap_search($ldapconnect,"dc=rug, dc=ac, dc=be", "uid=$login");
  581. //echo "<p> ldapDc = '$LDAPbasedn' </p>";
  582. $all_user_query = "uid=*";
  583. if(!empty($ldap_search_dn)) {
  584. $sr = ldap_search($ldap_connect, $ldap_search_dn, $all_user_query);
  585. } else {
  586. $sr = ldap_search($ldap_connect, $ldap_basedn, $all_user_query);
  587. }
  588. //echo " Number of entries returned is ".ldap_count_entries($ldapconnect,$sr);
  589. //echo " Getting entries ...";
  590. $info = ldap_get_entries($ldap_connect, $sr);
  591. for ($key = 0; $key < $info['count']; $key ++) {
  592. $user_id = ldap_add_user_by_array($info[$key], false);
  593. if ($user_id) {
  594. echo "User #$user_id created ";
  595. } else {
  596. echo "User was not created ";
  597. }
  598. }
  599. //echo "Data for ".$info["count"]." items returned:<p>";
  600. } else {
  601. //echo "LDAP bind failed...";
  602. }
  603. //echo "Closing LDAP connection<hr>";
  604. ldap_close($ldap_connect);
  605. } else {
  606. //echo "<h3>Unable to connect to LDAP server</h3>";
  607. }
  608. }