login.lib.php 38 KB

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