authldap.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  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. *
  48. * @version 3.0
  49. *
  50. * @package chamilo.auth.ldap
  51. * Note:
  52. * If you are using a firewall, you might need to check port 389 is open in
  53. * order for Chamilo to communicate with the LDAP server.
  54. * See http://support.chamilo.org/issues/4675 for details.
  55. */
  56. /**
  57. * Inclusions.
  58. */
  59. use ChamiloSession as Session;
  60. /**
  61. * Code.
  62. */
  63. require_once api_get_path(SYS_CODE_PATH).'auth/external_login/ldap.inc.php';
  64. require 'ldap_var.inc.php';
  65. /**
  66. * Check login and password with LDAP.
  67. *
  68. * @return bool when login & password both OK, false otherwise
  69. *
  70. * @author Roan Embrechts (based on code from Universit� Jean Monet)
  71. */
  72. function ldap_login($login, $password)
  73. {
  74. //error_log('Entering ldap_login('.$login.','.$password.')',0);
  75. $res = ldap_authentication_check($login, $password);
  76. // res=-1 -> the user does not exist in the ldap database
  77. // res=1 -> invalid password (user does exist)
  78. if ($res == 1) { //WRONG PASSWORD
  79. //$errorMessage = "LDAP User or password incorrect, try again.<br />";
  80. if (isset($log)) {
  81. unset($log);
  82. }
  83. if (isset($uid)) {
  84. unset($uid);
  85. }
  86. $loginLdapSucces = false;
  87. }
  88. if ($res == -1) { //WRONG USERNAME
  89. //$errorMessage = "LDAP User or password incorrect, try again.<br />";
  90. $login_ldap_success = false;
  91. }
  92. if ($res == 0) { //LOGIN & PASSWORD OK - SUCCES
  93. //$errorMessage = "Successful login w/ LDAP.<br>";
  94. $login_ldap_success = true;
  95. }
  96. //$result = "This is the result: $errorMessage";
  97. $result = $login_ldap_success;
  98. return $result;
  99. }
  100. /**
  101. * Find user info in LDAP.
  102. *
  103. * @return array Array with indexes: "firstname", "name", "email", "employeenumber"
  104. *
  105. * @author Stefan De Wannemacker
  106. * @author Roan Embrechts
  107. */
  108. function ldap_find_user_info($login)
  109. {
  110. //error_log('Entering ldap_find_user_info('.$login.')',0);
  111. global $ldap_host, $ldap_port, $ldap_basedn, $ldap_rdn, $ldap_pass, $ldap_search_dn;
  112. // basic sequence with LDAP is connect, bind, search,
  113. // interpret search result, close connection
  114. //echo "Connecting ...";
  115. $ldap_connect = ldap_connect($ldap_host, $ldap_port);
  116. ldap_set_version($ldap_connect);
  117. if ($ldap_connect) {
  118. //echo " Connect to LDAP server successful ";
  119. //echo "Binding ...";
  120. $ldap_bind = false;
  121. $ldap_bind_res = ldap_handle_bind($ldap_connect, $ldap_bind);
  122. if ($ldap_bind_res) {
  123. //echo " LDAP bind successful... ";
  124. //echo " Searching for uid... ";
  125. // Search surname entry
  126. //OLD: $sr=ldap_search($ldapconnect,"dc=rug, dc=ac, dc=be", "uid=$login");
  127. //echo "<p> ldapDc = '$LDAPbasedn' </p>";
  128. if (!empty($ldap_search_dn)) {
  129. $sr = ldap_search($ldap_connect, $ldap_search_dn, "uid=$login");
  130. } else {
  131. $sr = ldap_search($ldap_connect, $ldap_basedn, "uid=$login");
  132. }
  133. //echo " Search result is ".$sr;
  134. //echo " Number of entries returned is ".ldap_count_entries($ldapconnect,$sr);
  135. //echo " Getting entries ...";
  136. $info = ldap_get_entries($ldap_connect, $sr);
  137. //echo "Data for ".$info["count"]." items returned:<p>";
  138. } // else could echo "LDAP bind failed...";
  139. //echo "Closing LDAP connection<hr>";
  140. ldap_close($ldap_connect);
  141. } // else could echo "<h3>Unable to connect to LDAP server</h3>";
  142. //DEBUG: $result["firstname"] = "Jan"; $result["name"] = "De Test"; $result["email"] = "email@ugent.be";
  143. $result["firstname"] = $info[0]["cn"][0];
  144. $result["name"] = $info[0]["sn"][0];
  145. $result["email"] = $info[0]["mail"][0];
  146. $tutor_field = api_get_setting('ldap_filled_tutor_field');
  147. $result[$tutor_field] = $info[0][$tutor_field]; //employeenumber by default
  148. return $result;
  149. }
  150. /**
  151. * This function uses the data from ldap_find_user_info()
  152. * to add the userdata to Chamilo
  153. * "firstname", "name", "email", "isEmployee".
  154. *
  155. * @author Roan Embrechts
  156. */
  157. function ldap_put_user_info_locally($login, $info_array)
  158. {
  159. //error_log('Entering ldap_put_user_info_locally('.$login.',info_array)',0);
  160. global $ldap_pass_placeholder;
  161. global $submitRegistration, $submit, $uname, $email,
  162. $nom, $prenom, $password, $password1, $status;
  163. global $platformLanguage;
  164. global $loginFailed, $uidReset, $_user;
  165. /*----------------------------------------------------------
  166. 1. set the necessary variables
  167. ------------------------------------------------------------ */
  168. $uname = $login;
  169. $email = $info_array["email"];
  170. $nom = $info_array["name"];
  171. $prenom = $info_array["firstname"];
  172. $password = $ldap_pass_placeholder;
  173. $password1 = $ldap_pass_placeholder;
  174. $official_code = '';
  175. define("STUDENT", 5);
  176. define("COURSEMANAGER", 1);
  177. $tutor_field = api_get_setting('ldap_filled_tutor_field');
  178. $tutor_value = api_get_setting('ldap_filled_tutor_field_value');
  179. if (empty($tutor_field)) {
  180. $status = STUDENT;
  181. } else {
  182. if (empty($tutor_value)) {
  183. //in this case, we are assuming that the admin didn't give a criteria
  184. // so that if the field is not empty, it is a tutor
  185. if (!empty($info_array[$tutor_field])) {
  186. $status = COURSEMANAGER;
  187. } else {
  188. $status = STUDENT;
  189. }
  190. } else {
  191. //the tutor_value is filled, so we need to check the contents of the LDAP field
  192. if (is_array($info_array[$tutor_field]) && in_array($tutor_value, $info_array[$tutor_field])) {
  193. $status = COURSEMANAGER;
  194. } else {
  195. $status = STUDENT;
  196. }
  197. }
  198. }
  199. //$official_code = xxx; //example: choose an attribute
  200. /*----------------------------------------------------------
  201. 2. add info to Chamilo
  202. ------------------------------------------------------------ */
  203. $language = api_get_setting('platformLanguage');
  204. if (empty($language)) {
  205. $language = 'english';
  206. }
  207. $_userId = UserManager::create_user(
  208. $prenom,
  209. $nom,
  210. $status,
  211. $email,
  212. $uname,
  213. $password,
  214. $official_code,
  215. $language,
  216. '',
  217. '',
  218. 'ldap'
  219. );
  220. //echo "new user added to Chamilo, id = $_userId";
  221. //user_id, username, password, auth_source
  222. /*----------------------------------------------------------
  223. 3. register session
  224. ------------------------------------------------------------ */
  225. $uData['user_id'] = $_userId;
  226. $uData['username'] = $uname;
  227. $uData['auth_source'] = "ldap";
  228. $loginFailed = false;
  229. $uidReset = true;
  230. $_user['user_id'] = $uData['user_id'];
  231. Session::write('_uid', $_user['user_id']);
  232. }
  233. /**
  234. * The code of UGent uses these functions to authenticate.
  235. * function AuthVerifEnseignant ($uname, $passwd)
  236. * function AuthVerifEtudiant ($uname, $passwd)
  237. * function Authentif ($uname, $passwd).
  238. *
  239. * @todo translate the comments and code to english
  240. * @todo let these functions use the variables in config.inc instead of ldap_var.inc
  241. */
  242. /**
  243. * Checks the existence of a member in LDAP.
  244. *
  245. * @param string username input on keyboard
  246. * @param string password given by user
  247. *
  248. * @return int 0 if authentication succeeded, 1 if password was incorrect, -1 if it didn't belong to LDAP
  249. */
  250. function ldap_authentication_check($uname, $passwd)
  251. {
  252. //error_log('Entering ldap_authentication_check('.$uname.','.$passwd.')',0);
  253. global $ldap_host, $ldap_port, $ldap_basedn, $ldap_host2, $ldap_port2, $ldap_rdn, $ldap_pass;
  254. //error_log('Entering ldap_authentication_check('.$uname.','.$passwd.')',0);
  255. // Establish anonymous connection with LDAP server
  256. // Etablissement de la connexion anonyme avec le serveur LDAP
  257. $ds = ldap_connect($ldap_host, $ldap_port);
  258. ldap_set_version($ds);
  259. $test_bind = false;
  260. $test_bind_res = ldap_handle_bind($ds, $test_bind);
  261. //if problem, use the replica
  262. if ($test_bind_res === false) {
  263. $ds = ldap_connect($ldap_host2, $ldap_port2);
  264. ldap_set_version($ds);
  265. } // else: error_log('Connected to server '.$ldap_host);
  266. if ($ds !== false) {
  267. //Creation of filter containing values input by the user
  268. // Here it might be necessary to use $filter="(samaccountName=$uname)"; - see http://support.chamilo.org/issues/4675
  269. $filter = "(uid=$uname)";
  270. // Open anonymous LDAP connection
  271. $result = false;
  272. $ldap_bind_res = ldap_handle_bind($ds, $result);
  273. // Executing the search with the $filter parametr
  274. //error_log('Searching for '.$filter.' on LDAP server',0);
  275. $sr = ldap_search($ds, $ldap_basedn, $filter);
  276. $info = ldap_get_entries($ds, $sr);
  277. $dn = ($info[0]["dn"]);
  278. // debug !! echo"<br> dn = $dn<br> pass = $passwd<br>";
  279. // closing 1st connection
  280. ldap_close($ds);
  281. }
  282. // test the Distinguish Name from the 1st connection
  283. if ($dn == "") {
  284. return -1; // doesn't belong to the addressbook
  285. }
  286. //bug ldap.. if password empty, return 1!
  287. if ($passwd == "") {
  288. return 1;
  289. }
  290. // Opening 2nd LDAP connection : Connection user for password check
  291. $ds = ldap_connect($ldap_host, $ldap_port);
  292. ldap_set_version($ds);
  293. if (!$test_bind) {
  294. $ds = ldap_connect($ldap_host2, $ldap_port2);
  295. ldap_set_version($ds);
  296. }
  297. // return in case of wrong password connection error
  298. if (@ldap_bind($ds, $dn, $passwd) === false) {
  299. return 1; // invalid password
  300. } else {// connection successfull
  301. return 0;
  302. }
  303. } // end of check
  304. /**
  305. * Set the protocol version with version from config file (enables LDAP version 3).
  306. *
  307. * @param resource resource LDAP connexion resource, passed by reference
  308. */
  309. function ldap_set_version(&$resource)
  310. {
  311. //error_log('Entering ldap_set_version(&$resource)',0);
  312. global $ldap_version;
  313. if ($ldap_version > 2) {
  314. ldap_set_option($resource, LDAP_OPT_PROTOCOL_VERSION, 3);
  315. //ok - don't do anything
  316. //failure - should switch back to version 2 by default
  317. }
  318. }
  319. /**
  320. * Handle bind (whether authenticated or not).
  321. *
  322. * @param resource The LDAP handler to which we are connecting (by reference)
  323. * @param resource The LDAP bind handler we will be modifying
  324. * @param bool $ldap_bind
  325. *
  326. * @return bool Status of the bind assignment. True for success, false for failure.
  327. */
  328. function ldap_handle_bind(&$ldap_handler, &$ldap_bind)
  329. {
  330. //error_log('Entering ldap_handle_bind(&$ldap_handler,&$ldap_bind)',0);
  331. global $ldap_rdn, $ldap_pass, $extldap_config;
  332. $ldap_rdn = $extldap_config['admin_dn'];
  333. $ldap_pass = $extldap_config['admin_password'];
  334. if (!empty($ldap_rdn) and !empty($ldap_pass)) {
  335. //error_log('Trying authenticated login :'.$ldap_rdn.'/'.$ldap_pass,0);
  336. $ldap_bind = ldap_bind($ldap_handler, $ldap_rdn, $ldap_pass);
  337. if (!$ldap_bind) {
  338. //error_log('Authenticated login failed',0);
  339. //try in anonymous mode, you never know...
  340. $ldap_bind = ldap_bind($ldap_handler);
  341. }
  342. } else {
  343. // this is an "anonymous" bind, typically read-only access:
  344. $ldap_bind = ldap_bind($ldap_handler);
  345. }
  346. if (!$ldap_bind) {
  347. return false;
  348. } else {
  349. //error_log('Login finally OK',0);
  350. return true;
  351. }
  352. }
  353. /**
  354. * Get the total number of users on the platform.
  355. *
  356. * @see SortableTable#get_total_number_of_items()
  357. *
  358. * @author Mustapha Alouani
  359. */
  360. function ldap_get_users()
  361. {
  362. global $ldap_basedn, $ldap_host, $ldap_port, $ldap_rdn, $ldap_pass, $ldap_search_dn, $extldap_user_correspondance;
  363. $keyword_firstname = isset($_GET['keyword_firstname']) ? trim(Database::escape_string($_GET['keyword_firstname'])) : '';
  364. $keyword_lastname = isset($_GET['keyword_lastname']) ? trim(Database::escape_string($_GET['keyword_lastname'])) : '';
  365. $keyword_username = isset($_GET['keyword_username']) ? trim(Database::escape_string($_GET['keyword_username'])) : '';
  366. $keyword_type = isset($_GET['keyword_type']) ? Database::escape_string($_GET['keyword_type']) : '';
  367. $ldap_query = [];
  368. if ($keyword_username != "") {
  369. $ldap_query[] = str_replace('%username%', $keyword_username, $ldap_search_dn);
  370. } else {
  371. if ($keyword_lastname != "") {
  372. $ldap_query[] = "(".$extldap_user_correspondance['lastname']."=".$keyword_lastname."*)";
  373. }
  374. if ($keyword_firstname != "") {
  375. $ldap_query[] = "(".$extldap_user_correspondance['firstname']."=".$keyword_firstname."*)";
  376. }
  377. }
  378. if ($keyword_type != "" && $keyword_type != "all") {
  379. $ldap_query[] = "(employeeType=".$keyword_type.")";
  380. }
  381. if (count($ldap_query) > 1) {
  382. $str_query = "(& ";
  383. foreach ($ldap_query as $query) {
  384. $str_query .= " $query";
  385. }
  386. $str_query .= " )";
  387. } else {
  388. $str_query = count($ldap_query) > 0 ? $ldap_query[0] : null;
  389. }
  390. $ds = ldap_connect($ldap_host, $ldap_port);
  391. ldap_set_version($ds);
  392. if ($ds && count($ldap_query) > 0) {
  393. $r = false;
  394. $res = ldap_handle_bind($ds, $r);
  395. //$sr = ldap_search($ds, "ou=test-ou,$ldap_basedn", $str_query);
  396. $sr = ldap_search($ds, $ldap_basedn, $str_query);
  397. //echo "Le nombre de resultats est : ".ldap_count_entries($ds,$sr)."<p>";
  398. $info = ldap_get_entries($ds, $sr);
  399. return $info;
  400. } else {
  401. if (count($ldap_query) != 0) {
  402. echo Display::return_message(get_lang('LDAPConnectionError'), 'error');
  403. }
  404. return [];
  405. }
  406. }
  407. /**
  408. * Get the total number of users on the platform.
  409. *
  410. * @see SortableTable#get_total_number_of_items()
  411. *
  412. * @author Mustapha Alouani
  413. */
  414. function ldap_get_number_of_users()
  415. {
  416. $info = ldap_get_users();
  417. if (count($info) > 0) {
  418. return $info['count'];
  419. } else {
  420. return 0;
  421. }
  422. }
  423. /**
  424. * Get the users to display on the current page.
  425. *
  426. * @see SortableTable#get_table_data($from)
  427. *
  428. * @author Mustapha Alouani
  429. */
  430. function ldap_get_user_data($from, $number_of_items, $column, $direction)
  431. {
  432. global $extldap_user_correspondance;
  433. $users = [];
  434. $is_western_name_order = api_is_western_name_order();
  435. if (isset($_GET['submit'])) {
  436. $info = ldap_get_users();
  437. if ($info['count'] > 0) {
  438. for ($key = 0; $key < $info["count"]; $key++) {
  439. $user = [];
  440. // Get uid from dn
  441. //YW: this might be a variation between LDAP 2 and LDAP 3, but in LDAP 3, the uid is in
  442. //the corresponding index of the array
  443. //$dn_array=ldap_explode_dn($info[$key]["dn"],1);
  444. //$user[] = $dn_array[0]; // uid is first key
  445. //$user[] = $dn_array[0]; // uid is first key
  446. $user[] = $info[$key][$extldap_user_correspondance['username']][0];
  447. $user[] = $info[$key][$extldap_user_correspondance['username']][0];
  448. if ($is_western_name_order) {
  449. $user[] = api_convert_encoding($info[$key][$extldap_user_correspondance['firstname']][0], api_get_system_encoding(), 'UTF-8');
  450. $user[] = api_convert_encoding($info[$key][$extldap_user_correspondance['lastname']][0], api_get_system_encoding(), 'UTF-8');
  451. } else {
  452. $user[] = api_convert_encoding($info[$key][$extldap_user_correspondance['firstname']][0], api_get_system_encoding(), 'UTF-8');
  453. $user[] = api_convert_encoding($info[$key][$extldap_user_correspondance['lastname']][0], api_get_system_encoding(), 'UTF-8');
  454. }
  455. $user[] = $info[$key]['mail'][0];
  456. $user[] = $info[$key][$extldap_user_correspondance['username']][0];
  457. $users[] = $user;
  458. }
  459. } else {
  460. echo Display::return_message(get_lang('NoUser'), 'error');
  461. }
  462. }
  463. return $users;
  464. }
  465. /**
  466. * Build the modify-column of the table.
  467. *
  468. * @param int $user_id The user id
  469. * @param string $url_params
  470. *
  471. * @return string Some HTML-code with modify-buttons
  472. *
  473. * @author Mustapha Alouani
  474. */
  475. function modify_filter($user_id, $url_params, $row)
  476. {
  477. $query_string = "id[]=".$row[0];
  478. if (!empty($_GET['id_session'])) {
  479. $query_string .= '&amp;id_session='.Security::remove_XSS($_GET['id_session']);
  480. }
  481. $icon = '';
  482. if (UserManager::is_username_available($user_id)) {
  483. $icon = 'invitation_friend.png';
  484. } else {
  485. $icon = 'reload.png';
  486. }
  487. //$url_params_id="id=".$row[0];
  488. $result = '<a href="ldap_users_list.php?action=add_user&amp;user_id='.$user_id.'&amp;'.$query_string.'&amp;sec_token='.Security::getTokenFromSession().'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES, api_get_system_encoding()))."'".')) return false;">'.Display::return_icon($icon, get_lang('AddUsers')).'</a>';
  489. return $result;
  490. }
  491. /**
  492. * Adds a user to the Chamilo database or updates its data.
  493. *
  494. * @param string username (and uid inside LDAP)
  495. *
  496. * @author Mustapha Alouani
  497. */
  498. function ldap_add_user($login)
  499. {
  500. if ($ldap_user = extldap_authenticate($login, 'nopass', true)) {
  501. return extldap_add_user_by_array($ldap_user);
  502. }
  503. }
  504. function ldap_add_user_by_array($data, $update_if_exists = true)
  505. {
  506. $lastname = api_convert_encoding($data['sn'][0], api_get_system_encoding(), 'UTF-8');
  507. $firstname = api_convert_encoding($data['cn'][0], api_get_system_encoding(), 'UTF-8');
  508. $email = $data['mail'][0];
  509. // Get uid from dn
  510. $dn_array = ldap_explode_dn($data['dn'], 1);
  511. $username = $dn_array[0]; // uid is first key
  512. $outab[] = $data['edupersonprimaryaffiliation'][0]; // Here, "student"
  513. //$val = ldap_get_values_len($ds, $entry, "userPassword");
  514. //$val = ldap_get_values_len($ds, $data, "userPassword");
  515. //$password = $val[0];
  516. // TODO the password, if encrypted at the source, will be encrypted twice, which makes it useless. Try to fix that.
  517. $password = $data['userPassword'][0];
  518. $structure = $data['edupersonprimaryorgunitdn'][0];
  519. $array_structure = explode(",", $structure);
  520. $array_val = explode("=", $array_structure[0]);
  521. $etape = $array_val[1];
  522. $array_val = explode("=", $array_structure[1]);
  523. $annee = $array_val[1];
  524. // To ease management, we add the step-year (etape-annee) code
  525. $official_code = $etape."-".$annee;
  526. $auth_source = 'ldap';
  527. // No expiration date for students (recover from LDAP's shadow expiry)
  528. $expiration_date = '';
  529. $active = 1;
  530. if (empty($status)) {
  531. $status = 5;
  532. }
  533. if (empty($phone)) {
  534. $phone = '';
  535. }
  536. if (empty($picture_uri)) {
  537. $picture_uri = '';
  538. }
  539. // Adding user
  540. $user_id = 0;
  541. if (UserManager::is_username_available($username)) {
  542. $user_id = UserManager::create_user(
  543. $firstname,
  544. $lastname,
  545. $status,
  546. $email,
  547. $username,
  548. $password,
  549. $official_code,
  550. api_get_setting('platformLanguage'),
  551. $phone,
  552. $picture_uri,
  553. $auth_source,
  554. $expiration_date,
  555. $active
  556. );
  557. } else {
  558. if ($update_if_exists) {
  559. $user = api_get_user_info($username);
  560. $user_id = $user['user_id'];
  561. UserManager::update_user(
  562. $user_id,
  563. $firstname,
  564. $lastname,
  565. $username,
  566. null,
  567. null,
  568. $email,
  569. $status,
  570. $official_code,
  571. $phone,
  572. $picture_uri,
  573. $expiration_date,
  574. $active
  575. );
  576. }
  577. }
  578. return $user_id;
  579. }
  580. /**
  581. * Adds a list of users to one session.
  582. *
  583. * @param array Array of user ids
  584. * @param string Course code
  585. */
  586. function ldap_add_user_to_session($UserList, $id_session)
  587. {
  588. // Database Table Definitions
  589. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  590. $tbl_session_rel_class = Database::get_main_table(TABLE_MAIN_SESSION_CLASS);
  591. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  592. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  593. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  594. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  595. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  596. $tbl_class = Database::get_main_table(TABLE_MAIN_CLASS);
  597. $tbl_class_user = Database::get_main_table(TABLE_MAIN_CLASS_USER);
  598. $id_session = (int) $id_session;
  599. // Once users are imported in the users base, we can assign them to the session
  600. $result = Database::query("SELECT c_id FROM $tbl_session_rel_course WHERE session_id ='$id_session'");
  601. $CourseList = [];
  602. while ($row = Database::fetch_array($result)) {
  603. $CourseList[] = $row['c_id'];
  604. }
  605. foreach ($CourseList as $enreg_course) {
  606. foreach ($UserList as $enreg_user) {
  607. $enreg_user = (int) $enreg_user;
  608. Database::query("INSERT IGNORE ".
  609. " INTO $tbl_session_rel_course_rel_user ".
  610. "(session_id,c_id,user_id) VALUES ".
  611. "('$id_session','$enreg_course','$enreg_user')");
  612. }
  613. $sql = "SELECT COUNT(user_id) as nbUsers ".
  614. " FROM $tbl_session_rel_course_rel_user ".
  615. " WHERE session_id='$id_session' ".
  616. " AND c_id='$enreg_course'";
  617. $rs = Database::query($sql);
  618. list($nbr_users) = Database::fetch_array($rs);
  619. Database::query("UPDATE $tbl_session_rel_course ".
  620. " SET nbr_users=$nbr_users ".
  621. " WHERE session_id='$id_session' ".
  622. " AND c_id='$enreg_course'");
  623. }
  624. foreach ($UserList as $enreg_user) {
  625. $enreg_user = (int) $enreg_user;
  626. Database::query("INSERT IGNORE INTO $tbl_session_rel_user ".
  627. " (session_id, user_id, registered_at) ".
  628. " VALUES('$id_session','$enreg_user', '".api_get_utc_datetime()."')");
  629. }
  630. // We update the number of users in the session
  631. $sql = "SELECT COUNT(user_id) as nbUsers FROM $tbl_session_rel_user ".
  632. " WHERE session_id='$id_session' ".
  633. " AND relation_type<>".SESSION_RELATION_TYPE_RRHH." ";
  634. $rs = Database::query($sql);
  635. list($nbr_users) = Database::fetch_array($rs);
  636. Database::query("UPDATE $tbl_session SET nbr_users=$nbr_users ".
  637. " WHERE id='$id_session'");
  638. }
  639. /**
  640. * Synchronize users from the configured LDAP connection (in auth.conf.php). If
  641. * configured to disable old users,.
  642. *
  643. * @param bool $disableOldUsers Whether to disable users who have disappeared from LDAP (true) or just leave them be (default: false)
  644. * @param bool $deleteStudents Go one step further and delete completely students missing from LDAP
  645. * @param bool $deleteTeachers Go even one step further and also delete completely teachers missing from LDAP
  646. *
  647. * @return int Total number of users added (not counting possible removals)
  648. */
  649. function syncro_users(
  650. $disableOldUsers = false,
  651. $deleteStudents = false,
  652. $deleteTeachers = false
  653. ) {
  654. global $ldap_basedn, $ldap_host, $ldap_port, $ldap_rdn, $ldap_pass, $ldap_search_dn, $debug;
  655. $i = 0;
  656. if ($debug) {
  657. error_log('Connecting... ('.__FUNCTION__.')');
  658. }
  659. $ldapConnect = ldap_connect($ldap_host, $ldap_port);
  660. ldap_set_version($ldapConnect);
  661. if ($ldapConnect) {
  662. if ($debug) {
  663. error_log('Connected to LDAP server successfully! Binding... ('.__FUNCTION__.')');
  664. }
  665. $ldapBind = false;
  666. $ldapBindRes = ldap_handle_bind($ldapConnect, $ldapBind);
  667. if ($ldapBindRes) {
  668. if ($debug) {
  669. error_log('Bind successful! Searching for uid in LDAP DC: '.$ldap_search_dn);
  670. }
  671. $allUserQuery = "uid=*";
  672. if (!empty($ldap_search_dn)) {
  673. $sr = ldap_search($ldapConnect, $ldap_search_dn, $allUserQuery);
  674. } else {
  675. //OLD: $sr=ldap_search($ldapconnect,"dc=rug, dc=ac, dc=be", "uid=$login");
  676. $sr = ldap_search($ldapConnect, $ldap_basedn, $allUserQuery);
  677. }
  678. if ($debug) {
  679. error_log('Entries returned: '.ldap_count_entries($ldapConnect, $sr));
  680. }
  681. $info = ldap_get_entries($ldapConnect, $sr);
  682. for ($key = 0; $key < $info['count']; $key++) {
  683. $user_id = ldap_add_user_by_array($info[$key], false);
  684. if ($user_id) {
  685. if ($debug) {
  686. error_log('User #'.$user_id.' created from LDAP');
  687. }
  688. $i++;
  689. } else {
  690. if ($debug) {
  691. error_log('User '.$info[$key]['sn'][0].' ('.$info[$key]['mail'][0].') could not be created');
  692. }
  693. }
  694. }
  695. if ($disableOldUsers === true) {
  696. if ($debug) {
  697. error_log('Disable mode selected in '.__FUNCTION__);
  698. if ($deleteStudents) {
  699. error_log('...with complete deletion of users if disabled');
  700. }
  701. }
  702. // Get a big array of all user IDs, usernames only if they are
  703. // registered as auth_source = 'ldap'
  704. // This array will take about 60 bytes per user in memory, so
  705. // having 100K users should only take a few (6?) MB and will
  706. // highly reduce the number of DB queries
  707. $usersDBShortList = [];
  708. $usersLDAPShortList = [];
  709. $sql = "SELECT id, username, status FROM user WHERE auth_source = 'ldap' ORDER BY username";
  710. $res = Database::query($sql);
  711. if ($res !== false) {
  712. // First build a list of users present in LDAP
  713. for ($key = 0; $key < $info['count']; $key++) {
  714. $dn_array = ldap_explode_dn($info[$key]['dn'], 1);
  715. $usersLDAPShortList[$dn_array[0]] = 1;
  716. }
  717. // Go through all 'extldap' users. For any that cannot
  718. // be found in the LDAP list, disable
  719. while ($row = Database::fetch_assoc($res)) {
  720. $usersDBShortList[$row['username']] = $row['id'];
  721. // If any of those users is NOT in LDAP, disable or remove
  722. if (empty($usersLDAPShortList[$row['username']])) {
  723. if ($deleteStudents === true && $row['status'] == 5) {
  724. UserManager::delete_user($usersDBShortList[$row['username']]);
  725. if ($debug) {
  726. error_log('Student '.$row['username'].' removed from Chamilo');
  727. }
  728. } elseif ($deleteTeachers === true && $row['status'] == 1) {
  729. UserManager::delete_user($usersDBShortList[$row['username']]);
  730. if ($debug) {
  731. error_log('Teacher '.$row['username'].' removed from Chamilo');
  732. }
  733. } else {
  734. UserManager::disable($usersDBShortList[$row['username']]);
  735. if ($debug) {
  736. error_log('User '.$row['username'].' disabled in Chamilo');
  737. }
  738. }
  739. }
  740. }
  741. }
  742. }
  743. if ($debug) {
  744. error_log('Data for '.$info['count'].' items processed');
  745. }
  746. //echo "Data for ".$info["count"]." items returned:<p>";
  747. } else {
  748. error_log('Could not bind to LDAP server');
  749. }
  750. ldap_close($ldapConnect);
  751. } else {
  752. error_log('Could not connect to LDAP server');
  753. }
  754. error_log('Ended execution of function '.__FUNCTION__);
  755. }