login.lib.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. <?php
  2. use \ChamiloSession as Session;
  3. /* For licensing terms, see /license.txt */
  4. /**
  5. * Code library for login process
  6. *
  7. * @author Olivier Cauberghe <olivier.cauberghe@UGent.be>, Ghent University
  8. * @author Julio Montoya <gugli100@gmail.com>
  9. * @package chamilo.login
  10. */
  11. /**
  12. * Class
  13. * @package chamilo.login
  14. */
  15. class Login
  16. {
  17. /**
  18. * Get user account list
  19. *
  20. * @param array $user array with keys: email, password, uid, loginName
  21. * @param boolean $reset
  22. * @param boolean $by_username
  23. * @return unknown
  24. */
  25. public static function get_user_account_list($user, $reset = false, $by_username = false)
  26. {
  27. global $_configuration;
  28. $portal_url = api_get_path(WEB_PATH);
  29. if ($_configuration['multiple_access_urls']) {
  30. $access_url_id = api_get_current_access_url_id();
  31. if ($access_url_id != -1) {
  32. $url = api_get_access_url($access_url_id);
  33. $portal_url = $url['url'];
  34. }
  35. }
  36. if ($reset) {
  37. if ($by_username) {
  38. $secret_word = self::get_secret_word($user['email']);
  39. if ($reset) {
  40. $reset_link = $portal_url . "main/auth/lostPassword.php?reset=" . $secret_word . "&id=" . $user['uid'];
  41. } else {
  42. $reset_link = get_lang('Pass') . " : $user[password]";
  43. }
  44. $user_account_list = get_lang('YourRegistrationData') . " : \n" . get_lang('UserName') . ' : ' . $user['loginName'] . "\n" . get_lang('ResetLink') . ' : ' . $reset_link . '';
  45. if ($user_account_list) {
  46. $user_account_list = "\n-----------------------------------------------\n" . $user_account_list;
  47. }
  48. } else {
  49. foreach ($user as $this_user) {
  50. $secret_word = self::get_secret_word($this_user['email']);
  51. if ($reset) {
  52. $reset_link = $portal_url . "main/auth/lostPassword.php?reset=" . $secret_word . "&id=" . $this_user['uid'];
  53. } else {
  54. $reset_link = get_lang('Pass') . " : $this_user[password]";
  55. }
  56. $user_account_list[] = get_lang('YourRegistrationData') . " : \n" . get_lang('UserName') . ' : ' . $this_user['loginName'] . "\n" . get_lang('ResetLink') . ' : ' . $reset_link . '';
  57. }
  58. if ($user_account_list) {
  59. $user_account_list = implode("\n-----------------------------------------------\n", $user_account_list);
  60. }
  61. }
  62. } else {
  63. if (!$by_username) {
  64. $user = $user[0];
  65. }
  66. $reset_link = get_lang('Pass') . " : $user[password]";
  67. $user_account_list = get_lang('YourRegistrationData') . " : \n" . get_lang('UserName') . ' : ' . $user['loginName'] . "\n" . $reset_link . '';
  68. }
  69. return $user_account_list;
  70. }
  71. /**
  72. * This function sends the actual password to the user
  73. *
  74. * @param int $user
  75. * @author Olivier Cauberghe <olivier.cauberghe@UGent.be>, Ghent University
  76. */
  77. public static function send_password_to_user($user, $by_username = false) {
  78. global $_configuration;
  79. $email_subject = "[" . api_get_setting('siteName') . "] " . get_lang('LoginRequest'); // SUBJECT
  80. if ($by_username) { // Show only for lost password
  81. $user_account_list = self::get_user_account_list($user, false, $by_username); // BODY
  82. $email_to = $user['email'];
  83. } else {
  84. $user_account_list = self::get_user_account_list($user); // BODY
  85. $email_to = $user[0]['email'];
  86. }
  87. $portal_url = api_get_path(WEB_PATH);
  88. if ($_configuration['multiple_access_urls']) {
  89. $access_url_id = api_get_current_access_url_id();
  90. if ($access_url_id != -1) {
  91. $url = api_get_access_url($access_url_id);
  92. $portal_url = $url['url'];
  93. }
  94. }
  95. $email_body = get_lang('YourAccountParam') . " " . $portal_url . "\n\n$user_account_list";
  96. // SEND MESSAGE
  97. $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
  98. $email_admin = api_get_setting('emailAdministrator');
  99. if (api_mail_html('', $email_to, $email_subject, $email_body, $sender_name, $email_admin) == 1) {
  100. return get_lang('YourPasswordHasBeenReset');
  101. } else {
  102. $admin_email = Display :: encrypted_mailto_link(api_get_setting('emailAdministrator'), api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname')));
  103. return sprintf(get_lang('ThisPlatformWasUnableToSendTheEmailPleaseContactXForMoreInformation'), $admin_email);
  104. }
  105. }
  106. /**
  107. * Handle encrypted password, send an email to a user with his password
  108. *
  109. * @param int user id
  110. * @param bool $by_username
  111. *
  112. * @author Olivier Cauberghe <olivier.cauberghe@UGent.be>, Ghent University
  113. */
  114. public static function handle_encrypted_password($user, $by_username = false) {
  115. $email_subject = "[" . api_get_setting('siteName') . "] " . get_lang('LoginRequest'); // SUBJECT
  116. if ($by_username) { // Show only for lost password
  117. $user_account_list = self::get_user_account_list($user, true, $by_username); // BODY
  118. $email_to = $user['email'];
  119. } else {
  120. $user_account_list = self::get_user_account_list($user, true); // BODY
  121. $email_to = $user[0]['email'];
  122. }
  123. $email_body = get_lang('DearUser') . " :\n" . get_lang('password_request') . "\n";
  124. $email_body .= $user_account_list . "\n-----------------------------------------------\n\n";
  125. $email_body .= get_lang('PasswordEncryptedForSecurity');
  126. $email_body .= "\n\n" . get_lang('SignatureFormula') . ",\n" . api_get_setting('administratorName') . " " . api_get_setting('administratorSurname') . "\n" . get_lang('PlataformAdmin') . " - " . api_get_setting('siteName');
  127. $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
  128. $email_admin = api_get_setting('emailAdministrator');
  129. if (@api_mail_html('', $email_to, $email_subject, $email_body, $sender_name, $email_admin) == 1) {
  130. if (CustomPages::enabled()) {
  131. return get_lang('YourPasswordHasBeenEmailed');
  132. } else {
  133. Display::display_confirmation_message(get_lang('YourPasswordHasBeenEmailed'));
  134. }
  135. } else {
  136. $admin_email = Display :: encrypted_mailto_link(api_get_setting('emailAdministrator'), api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname')));
  137. $message = sprintf(get_lang('ThisPlatformWasUnableToSendTheEmailPleaseContactXForMoreInformation'), $admin_email);
  138. if (CustomPages::enabled()) {
  139. return $message;
  140. } else {
  141. Display::display_error_message($message, false);
  142. }
  143. }
  144. }
  145. /**
  146. * Gets the secret word
  147. * @author Olivier Cauberghe <olivier.cauberghe@UGent.be>, Ghent University
  148. */
  149. public static function get_secret_word($add)
  150. {
  151. return $secret_word = sha1($add);
  152. }
  153. /**
  154. * Resets a password
  155. * @author Olivier Cauberghe <olivier.cauberghe@UGent.be>, Ghent University
  156. */
  157. public static function reset_password($secret, $id, $by_username = false)
  158. {
  159. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  160. $id = intval($id);
  161. $sql = "SELECT user_id AS uid, lastname AS lastName, firstname AS firstName, username AS loginName, password, email FROM " . $tbl_user . " WHERE user_id=$id";
  162. $result = Database::query($sql);
  163. $num_rows = Database::num_rows($result);
  164. if ($result && $num_rows > 0) {
  165. $user = Database::fetch_array($result);
  166. } else {
  167. return get_lang('CouldNotResetPassword');
  168. }
  169. if (self::get_secret_word($user['email']) == $secret) {
  170. // OK, secret word is good. Now change password and mail it.
  171. $user['password'] = api_generate_password();
  172. $crypted = api_get_encrypted_password($user['password']);
  173. $sql = "UPDATE " . $tbl_user . " SET password='$crypted' WHERE user_id = $id";
  174. Database::query($sql);
  175. return self::send_password_to_user($user, $by_username);
  176. } else {
  177. return get_lang('NotAllowed');
  178. }
  179. }
  180. /**
  181. *
  182. * @global bool $is_platformAdmin
  183. * @global bool $is_allowedCreateCourse
  184. * @global object $_user
  185. */
  186. public static function init_user($user_id, $reset)
  187. {
  188. global $is_platformAdmin;
  189. global $is_allowedCreateCourse;
  190. global $_user;
  191. if (isset($reset) && $reset) { // session data refresh requested
  192. unset($_SESSION['_user']['uidReset']);
  193. $is_platformAdmin = false;
  194. $is_allowedCreateCourse = false;
  195. $_user['user_id'] = $user_id;
  196. if (isset($_user['user_id']) && $_user['user_id'] && !api_is_anonymous()) {
  197. // a uid is given (log in succeeded)
  198. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  199. $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
  200. $track_e_login = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  201. $sql = "SELECT user.*, a.user_id is_admin, UNIX_TIMESTAMP(login.login_date) login_date
  202. FROM $user_table
  203. LEFT JOIN $admin_table a
  204. ON user.user_id = a.user_id
  205. LEFT JOIN $track_e_login login
  206. ON user.user_id = login.login_user_id
  207. WHERE user.user_id = '" . $_user['user_id'] . "'
  208. ORDER BY login.login_date DESC LIMIT 1";
  209. $result = Database::query($sql);
  210. if (Database::num_rows($result) > 0) {
  211. // Extracting the user data
  212. $uData = Database::fetch_array($result);
  213. $_user['firstName'] = $uData['firstname'];
  214. $_user['lastName'] = $uData['lastname'];
  215. $_user['mail'] = $uData['email'];
  216. $_user['lastLogin'] = $uData['login_date'];
  217. $_user['official_code'] = $uData['official_code'];
  218. $_user['picture_uri'] = $uData['picture_uri'];
  219. $_user['user_id'] = $uData['user_id'];
  220. $_user['language'] = $uData['language'];
  221. $_user['auth_source'] = $uData['auth_source'];
  222. $_user['theme'] = $uData['theme'];
  223. $_user['status'] = $uData['status'];
  224. $is_platformAdmin = (bool) (!is_null($uData['is_admin']));
  225. $is_allowedCreateCourse = (bool) (($uData ['status'] == 1) or (api_get_setting('drhCourseManagerRights') and $uData['status'] == 4));
  226. ConditionalLogin::check_conditions($uData);
  227. Session::write('_user', $_user);
  228. UserManager::update_extra_field_value($_user['user_id'], 'already_logged_in', 'true');
  229. Session::write('is_platformAdmin', $is_platformAdmin);
  230. Session::write('is_allowedCreateCourse', $is_allowedCreateCourse);
  231. //
  232. //
  233. // // If request_uri is setted we have to go further to have course permissions
  234. // if (empty($_SESSION['request_uri']) || !isset($_SESSION['request_uri'])) {
  235. // if (isset($_SESSION['noredirection'])) {
  236. // //If we just want to reset info without redirecting user
  237. // unset($_SESSION['noredirection']);
  238. // } else {
  239. // LoginRedirection::redirect();
  240. // }
  241. // }
  242. } else {
  243. header('location:' . api_get_path(WEB_PATH));
  244. //exit("WARNING UNDEFINED UID !! ");
  245. }
  246. } else { // no uid => logout or Anonymous
  247. Session::erase('_user');
  248. Session::erase('_uid');
  249. }
  250. Session::write('is_platformAdmin', $is_platformAdmin);
  251. Session::write('is_allowedCreateCourse', $is_allowedCreateCourse);
  252. } else { // continue with the previous values
  253. $_user = $_SESSION['_user'];
  254. $is_platformAdmin = $_SESSION['is_platformAdmin'];
  255. $is_allowedCreateCourse = $_SESSION['is_allowedCreateCourse'];
  256. }
  257. }
  258. /**
  259. *
  260. * @global bool $is_platformAdmin
  261. * @global bool $is_allowedCreateCourse
  262. * @global object $_user
  263. * @global int $_cid
  264. * @global array $_course
  265. * @global type $_real_cid
  266. * @global type $_courseUser
  267. * @global type $is_courseAdmin
  268. * @global type $is_courseTutor
  269. * @global type $is_courseCoach
  270. * @global type $is_courseMember
  271. * @global type $is_sessionAdmin
  272. * @global type $is_allowed_in_course
  273. *
  274. * @param type $course_id
  275. * @param type $reset
  276. */
  277. static function init_course($course_id, $reset)
  278. {
  279. global $_configuration;
  280. global $is_platformAdmin;
  281. global $is_allowedCreateCourse;
  282. global $_user;
  283. global $_cid;
  284. global $_course;
  285. global $_real_cid;
  286. global $_courseUser;
  287. global $is_courseAdmin; //course teacher
  288. global $is_courseTutor; //course teacher - some rights
  289. global $is_courseCoach; //course coach
  290. global $is_courseMember; //course student
  291. global $is_sessionAdmin;
  292. global $is_allowed_in_course;
  293. if ($reset) {
  294. // Course session data refresh requested or empty data
  295. if ($course_id) {
  296. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  297. $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  298. $sql = "SELECT course.*, course_category.code faCode, course_category.name faName
  299. FROM $course_table
  300. LEFT JOIN $course_cat_table
  301. ON course.category_code = course_category.code
  302. WHERE course.code = '$course_id'";
  303. $result = Database::query($sql);
  304. if (Database::num_rows($result) > 0) {
  305. $course_data = Database::fetch_array($result);
  306. //@TODO real_cid should be cid, for working with numeric course id
  307. $_real_cid = $course_data['id'];
  308. $_cid = $course_data['code'];
  309. $_course = array();
  310. $_course['real_id'] = $course_data['id'];
  311. $_course['id'] = $course_data['code']; //auto-assigned integer
  312. $_course['code'] = $course_data['code'];
  313. $_course['name'] = $course_data['title'];
  314. $_course['title'] = $course_data['title'];
  315. $_course['official_code'] = $course_data['visual_code']; // use in echo
  316. $_course['sysCode'] = $course_data['code']; // use as key in db
  317. $_course['path'] = $course_data['directory']; // use as key in path
  318. $_course['dbName'] = $course_data['db_name']; // use as key in db list
  319. $_course['db_name'] = $course_data['db_name']; // not needed in Chamilo 1.9
  320. $_course['dbNameGlu'] = $_configuration['table_prefix'] . $course_data['db_name'] . $_configuration['db_glue']; // use in all queries //not needed in Chamilo 1.9
  321. $_course['titular'] = $course_data['tutor_name']; // this should be deprecated and use the table course_rel_user
  322. $_course['language'] = $course_data['course_language'];
  323. $_course['extLink']['url'] = $course_data['department_url'];
  324. $_course['extLink']['name'] = $course_data['department_name'];
  325. $_course['categoryCode'] = $course_data['faCode'];
  326. $_course['categoryName'] = $course_data['faName'];
  327. $_course['visibility'] = $course_data['visibility'];
  328. $_course['subscribe_allowed'] = $course_data['subscribe'];
  329. $_course['unsubscribe'] = $course_data['unsubscribe'];
  330. $_course['activate_legal'] = $course_data['activate_legal'];
  331. $_course['show_score'] = $course_data['show_score']; //used in the work tool
  332. Session::write('_cid', $_cid);
  333. Session::write('_course', $_course);
  334. //@TODO real_cid should be cid, for working with numeric course id
  335. Session::write('_real_cid', $_real_cid);
  336. // if a session id has been given in url, we store the session
  337. // Database Table Definitions
  338. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  339. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  340. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  341. if (!empty($_GET['id_session'])) {
  342. $_SESSION['id_session'] = intval($_GET['id_session']);
  343. $sql = 'SELECT name FROM ' . $tbl_session . ' WHERE id="' . intval($_SESSION['id_session']) . '"';
  344. $rs = Database::query($sql);
  345. list($_SESSION['session_name']) = Database::fetch_array($rs);
  346. } else {
  347. Session::erase('session_name');
  348. Session::erase('id_session');
  349. }
  350. if (!isset($_SESSION['login_as'])) {
  351. //Course login
  352. if (isset($_user['user_id'])) {
  353. event_course_login($_course['sysCode'], $_user['user_id'], api_get_session_id());
  354. }
  355. }
  356. } else {
  357. //exit("WARNING UNDEFINED CID !! ");
  358. header('location:' . api_get_path(WEB_PATH));
  359. }
  360. } else {
  361. Session::erase('_cid');
  362. Session::erase('_real_cid');
  363. Session::erase('_course');
  364. if (!empty($_SESSION)) {
  365. foreach ($_SESSION as $key => $session_item) {
  366. if (strpos($key, 'lp_autolunch_') === false) {
  367. continue;
  368. } else {
  369. if (isset($_SESSION[$key])) {
  370. Session::erase($key);
  371. }
  372. }
  373. }
  374. }
  375. //Deleting session info
  376. if (api_get_session_id()) {
  377. Session::erase('id_session');
  378. Session::erase('session_name');
  379. }
  380. }
  381. } else {
  382. // Continue with the previous values
  383. if (empty($_SESSION['_course']) OR empty($_SESSION['_cid'])) { //no previous values...
  384. $_cid = -1; //set default values that will be caracteristic of being unset
  385. $_course = -1;
  386. } else {
  387. $_cid = $_SESSION['_cid'];
  388. $_course = $_SESSION['_course'];
  389. // these lines are usefull for tracking. Indeed we can have lost the id_session and not the cid.
  390. // Moreover, if we want to track a course with another session it can be usefull
  391. if (!empty($_GET['id_session'])) {
  392. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  393. $sql = 'SELECT name FROM ' . $tbl_session . ' WHERE id="' . intval($_SESSION['id_session']) . '"';
  394. $rs = Database::query($sql);
  395. list($_SESSION['session_name']) = Database::fetch_array($rs);
  396. $_SESSION['id_session'] = intval($_GET['id_session']);
  397. }
  398. if (!isset($_SESSION['login_as'])) {
  399. $save_course_access = true;
  400. //The value $_dont_save_user_course_access should be added before the call of global.inc.php see the main/inc/chat.ajax.php file
  401. //Disables the updates in the TRACK_E_COURSE_ACCESS table
  402. if (isset($_dont_save_user_course_access) && $_dont_save_user_course_access == true) {
  403. $save_course_access = false;
  404. }
  405. if ($save_course_access) {
  406. $course_tracking_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  407. /*
  408. * When $_configuration['session_lifetime'] is too big 100 hours (in order to let users take exercises with no problems)
  409. * the function Tracking::get_time_spent_on_the_course() returns big values (200h) due the condition:
  410. * login_course_date > now() - INTERVAL $session_lifetime SECOND
  411. *
  412. */
  413. /*
  414. if (isset($_configuration['session_lifetime'])) {
  415. $session_lifetime = $_configuration['session_lifetime'];
  416. } else {
  417. $session_lifetime = 3600; // 1 hour
  418. } */
  419. $session_lifetime = 3600; // 1 hour
  420. $course_code = $_course['sysCode'];
  421. $time = api_get_utc_datetime();
  422. if (isset($_user['user_id']) && !empty($_user['user_id'])) {
  423. //We select the last record for the current course in the course tracking table
  424. //But only if the login date is < than now + max_life_time
  425. $sql = "SELECT course_access_id FROM $course_tracking_table
  426. WHERE user_id = " . intval($_user ['user_id']) . " AND
  427. course_code = '$course_code' AND
  428. session_id = " . api_get_session_id() . " AND
  429. login_course_date > now() - INTERVAL $session_lifetime SECOND
  430. ORDER BY login_course_date DESC LIMIT 0,1";
  431. $result = Database::query($sql);
  432. if (Database::num_rows($result) > 0) {
  433. $i_course_access_id = Database::result($result, 0, 0);
  434. //We update the course tracking table
  435. $sql = "UPDATE $course_tracking_table SET logout_course_date = '$time', counter = counter+1
  436. WHERE course_access_id = " . intval($i_course_access_id) . " AND session_id = " . api_get_session_id();
  437. //error_log($sql);
  438. Database::query($sql);
  439. } else {
  440. $sql = "INSERT INTO $course_tracking_table (course_code, user_id, login_course_date, logout_course_date, counter, session_id)" .
  441. "VALUES('" . $course_code . "', '" . $_user['user_id'] . "', '$time', '$time', '1','" . api_get_session_id() . "')";
  442. //error_log($sql);
  443. Database::query($sql);
  444. }
  445. }
  446. }
  447. }
  448. }
  449. }
  450. /* COURSE / USER REL. INIT */
  451. $session_id = api_get_session_id();
  452. $user_id = isset($_user['user_id']) ? $_user['user_id'] : null;
  453. //Course permissions
  454. $is_courseAdmin = false; //course teacher
  455. $is_courseTutor = false; //course teacher - some rights
  456. $is_courseMember = false; //course student
  457. //Course - User permissions
  458. $is_sessionAdmin = false;
  459. if ($reset) {
  460. if (isset($user_id) && $user_id && isset($_cid) && $_cid) {
  461. //Check if user is subscribed in a course
  462. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  463. $sql = "SELECT * FROM $course_user_table
  464. WHERE user_id = '" . $user_id . "' AND relation_type <> " . COURSE_RELATION_TYPE_RRHH . "
  465. AND course_code = '$course_id'";
  466. $result = Database::query($sql);
  467. $cuData = null;
  468. if (Database::num_rows($result) > 0) { // this user have a recorded state for this course
  469. $cuData = Database::fetch_array($result, 'ASSOC');
  470. $is_courseAdmin = (bool) ($cuData['status'] == 1 );
  471. $is_courseTutor = (bool) ($cuData['tutor_id'] == 1 );
  472. $is_courseMember = true;
  473. //Checking if the user filled the course legal agreement
  474. if ($_course['activate_legal'] == 1 && !api_is_platform_admin()) {
  475. $user_is_subscribed = CourseManager::is_user_accepted_legal($user_id, $_course['id'], $session_id);
  476. if (!$user_is_subscribed) {
  477. $url = api_get_path(WEB_CODE_PATH) . 'course_info/legal.php?course_code=' . $_course['code'] . '&session_id=' . $session_id;
  478. header('Location: ' . $url);
  479. exit;
  480. }
  481. }
  482. $_courseUser['role'] = $cuData['role'];
  483. Session::write('_courseUser', $_courseUser);
  484. }
  485. //We are in a session course? Check session permissions
  486. if (!empty($session_id)) {
  487. //I'm not the teacher of the course
  488. if ($is_courseAdmin == false) {
  489. // this user has no status related to this course
  490. // The user is subscribed in a session? The user is a Session coach a Session admin ?
  491. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  492. $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
  493. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  494. //Session coach, session admin, course coach admin
  495. $sql = "SELECT session.id_coach, session_admin_id, session_rcru.id_user
  496. FROM $tbl_session session, $tbl_session_course_user session_rcru
  497. WHERE session_rcru.id_session = session.id AND
  498. session_rcru.course_code = '$_cid' AND
  499. session_rcru.id_user = '$user_id' AND
  500. session_rcru.id_session = $session_id AND
  501. session_rcru.status = 2";
  502. $result = Database::query($sql);
  503. $row = Database::store_result($result);
  504. //I'm a session admin?
  505. if (isset($row) && isset($row[0]) && $row[0]['session_admin_id'] == $user_id) {
  506. $_courseUser['role'] = 'Professor';
  507. $is_courseMember = false;
  508. $is_courseTutor = false;
  509. $is_courseAdmin = false;
  510. $is_courseCoach = false;
  511. $is_sessionAdmin = true;
  512. } else {
  513. //Im a coach or a student?
  514. $sql = "SELECT id_user, status FROM " . $tbl_session_course_user . "
  515. WHERE course_code = '$_cid' AND
  516. id_user = '" . $user_id . "' AND
  517. id_session = '" . $session_id . "'
  518. LIMIT 1";
  519. $result = Database::query($sql);
  520. if (Database::num_rows($result)) {
  521. $row = Database::fetch_array($result, 'ASSOC');
  522. $session_course_status = $row['status'];
  523. switch ($session_course_status) {
  524. case '2': // coach - teacher
  525. $_courseUser['role'] = 'Professor';
  526. $is_courseMember = true;
  527. $is_courseTutor = true;
  528. $is_courseCoach = true;
  529. $is_sessionAdmin = false;
  530. if (api_get_setting('extend_rights_for_coach') == 'true') {
  531. $is_courseAdmin = true;
  532. } else {
  533. $is_courseAdmin = false;
  534. }
  535. Session::write('_courseUser', $_courseUser);
  536. break;
  537. case '0': //student
  538. $is_courseMember = true;
  539. $is_courseTutor = false;
  540. $is_courseAdmin = false;
  541. $is_sessionAdmin = false;
  542. Session::write('_courseUser', $_courseUser);
  543. break;
  544. default:
  545. //unregister user
  546. $is_courseMember = false;
  547. $is_courseTutor = false;
  548. $is_courseAdmin = false;
  549. $is_sessionAdmin = false;
  550. Session::erase('_courseUser');
  551. break;
  552. }
  553. } else {
  554. //unregister user
  555. $is_courseMember = false;
  556. $is_courseTutor = false;
  557. $is_courseAdmin = false;
  558. $is_sessionAdmin = false;
  559. Session::erase('_courseUser');
  560. }
  561. }
  562. }
  563. //If I'm the admin platform i'm a teacher of the course
  564. if ($is_platformAdmin) {
  565. $is_courseAdmin = true;
  566. }
  567. }
  568. } else { // keys missing => not anymore in the course - user relation
  569. // course
  570. $is_courseMember = false;
  571. $is_courseAdmin = false;
  572. $is_courseTutor = false;
  573. $is_courseCoach = false;
  574. $is_sessionAdmin = false;
  575. Session::erase('_courseUser');
  576. }
  577. //Checking the course access
  578. $is_allowed_in_course = false;
  579. if (isset($_course)) {
  580. switch ($_course['visibility']) {
  581. case COURSE_VISIBILITY_OPEN_WORLD: //3
  582. $is_allowed_in_course = true;
  583. break;
  584. case COURSE_VISIBILITY_OPEN_PLATFORM : //2
  585. if (isset($user_id) && !api_is_anonymous($user_id)) {
  586. $is_allowed_in_course = true;
  587. }
  588. break;
  589. case COURSE_VISIBILITY_REGISTERED: //1
  590. if ($is_platformAdmin || $is_courseMember) {
  591. $is_allowed_in_course = true;
  592. }
  593. break;
  594. case COURSE_VISIBILITY_CLOSED: //0
  595. if ($is_platformAdmin || $is_courseAdmin) {
  596. $is_allowed_in_course = true;
  597. }
  598. break;
  599. case COURSE_VISIBILITY_HIDDEN: //4
  600. if ($is_platformAdmin) {
  601. $is_allowed_in_course = true;
  602. }
  603. break;
  604. }
  605. }
  606. // check the session visibility
  607. if ($is_allowed_in_course == true) {
  608. //if I'm in a session
  609. if ($session_id != 0) {
  610. if (!$is_platformAdmin) {
  611. // admin and session coach are *not* affected to the invisible session mode
  612. // the coach is not affected because he can log in some days after the end date of a session
  613. $session_visibility = api_get_session_visibility($session_id);
  614. switch ($session_visibility) {
  615. case SESSION_INVISIBLE:
  616. $is_allowed_in_course = false;
  617. break;
  618. }
  619. //checking date
  620. }
  621. }
  622. }
  623. // save the states
  624. Session::write('is_courseAdmin', $is_courseAdmin);
  625. Session::write('is_courseMember', $is_courseMember);
  626. Session::write('is_courseTutor', $is_courseTutor);
  627. Session::write('is_courseCoach', $is_courseCoach);
  628. Session::write('is_allowed_in_course', $is_allowed_in_course);
  629. Session::write('is_sessionAdmin', $is_sessionAdmin);
  630. } else { // continue with the previous values
  631. if (isset($_SESSION ['_courseUser'])) {
  632. $_courseUser = $_SESSION ['_courseUser'];
  633. }
  634. $is_courseAdmin = $_SESSION ['is_courseAdmin'];
  635. $is_courseTutor = $_SESSION ['is_courseTutor'];
  636. $is_courseCoach = $_SESSION ['is_courseCoach'];
  637. $is_courseMember = $_SESSION ['is_courseMember'];
  638. $is_allowed_in_course = $_SESSION ['is_allowed_in_course'];
  639. }
  640. }
  641. /**
  642. *
  643. * @global int $_cid
  644. * @global array $_course
  645. * @global int $_gid
  646. *
  647. * @param int $group_id
  648. * @param bool $reset
  649. */
  650. static function init_group($group_id, $reset)
  651. {
  652. global $_cid;
  653. global $_course;
  654. global $_gid;
  655. if ($reset) { // session data refresh requested
  656. if ($group_id && $_cid && !empty($_course['real_id'])) { // have keys to search data
  657. $group_table = Database::get_course_table(TABLE_GROUP);
  658. $sql = "SELECT * FROM $group_table WHERE c_id = " . $_course['real_id'] . " AND id = '$group_id'";
  659. $result = Database::query($sql);
  660. if (Database::num_rows($result) > 0) { // This group has recorded status related to this course
  661. $gpData = Database::fetch_array($result);
  662. $_gid = $gpData ['id'];
  663. Session::write('_gid', $_gid);
  664. } else {
  665. Session::erase('_gid');
  666. }
  667. } elseif (isset($_SESSION['_gid']) or isset($_gid)) { // Keys missing => not anymore in the group - course relation
  668. Session::erase('_gid');
  669. }
  670. } elseif (isset($_SESSION['_gid'])) { // continue with the previous values
  671. $_gid = $_SESSION ['_gid'];
  672. } else { //if no previous value, assign caracteristic undefined value
  673. $_gid = -1;
  674. }
  675. //set variable according to student_view_enabled choices
  676. if (api_get_setting('student_view_enabled') == "true") {
  677. if (isset($_GET['isStudentView'])) {
  678. if ($_GET['isStudentView'] == 'true') {
  679. if (isset($_SESSION['studentview'])) {
  680. if (!empty($_SESSION['studentview'])) {
  681. // switching to studentview
  682. $_SESSION['studentview'] = 'studentview';
  683. }
  684. }
  685. } elseif ($_GET['isStudentView'] == 'false') {
  686. if (isset($_SESSION['studentview'])) {
  687. if (!empty($_SESSION['studentview'])) {
  688. // switching to teacherview
  689. $_SESSION['studentview'] = 'teacherview';
  690. }
  691. }
  692. }
  693. } elseif (!empty($_SESSION['studentview'])) {
  694. //all is fine, no change to that, obviously
  695. } elseif (empty($_SESSION['studentview'])) {
  696. // We are in teacherview here
  697. $_SESSION['studentview'] = 'teacherview';
  698. }
  699. }
  700. }
  701. /**
  702. * Returns true if user exists in the platform when asking the password
  703. *
  704. * @param string $username (email or username)
  705. * @return boolean
  706. */
  707. public static function get_user_accounts_by_username($username)
  708. {
  709. if (strpos($username,'@')){
  710. $username = api_strtolower($username);
  711. $email = true;
  712. } else {
  713. $username = api_strtolower($username);
  714. $email = false;
  715. }
  716. $condition = '';
  717. if ($email) {
  718. $condition = "LOWER(email) = '".Database::escape_string($username)."' ";
  719. } else {
  720. $condition = "LOWER(username) = '".Database::escape_string($username)."'";
  721. }
  722. $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
  723. $query = "SELECT user_id AS uid, lastname AS lastName, firstname AS firstName, username AS loginName, password, email,
  724. status AS status, official_code, phone, picture_uri, creator_id
  725. FROM $tbl_user
  726. WHERE ( $condition AND active = 1) ";
  727. $result = Database::query($query);
  728. $num_rows = Database::num_rows($result);
  729. if ($result && $num_rows > 0) {
  730. return Database::store_result($result);
  731. }
  732. return false;
  733. }
  734. }