login.lib.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  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. //
  292. //
  293. // // If request_uri is setted we have to go further to have course permissions
  294. // if (empty($_SESSION['request_uri']) || !isset($_SESSION['request_uri'])) {
  295. // if (isset($_SESSION['noredirection'])) {
  296. // //If we just want to reset info without redirecting user
  297. // unset($_SESSION['noredirection']);
  298. // } else {
  299. // LoginRedirection::redirect();
  300. // }
  301. // }
  302. } else {
  303. header('location:' . api_get_path(WEB_PATH));
  304. //exit("WARNING UNDEFINED UID !! ");
  305. }
  306. } else { // no uid => logout or Anonymous
  307. Session::erase('_user');
  308. Session::erase('_uid');
  309. }
  310. Session::write('is_platformAdmin', $is_platformAdmin);
  311. Session::write('is_allowedCreateCourse', $is_allowedCreateCourse);
  312. } else { // continue with the previous values
  313. $_user = $_SESSION['_user'];
  314. $is_platformAdmin = $_SESSION['is_platformAdmin'];
  315. $is_allowedCreateCourse = $_SESSION['is_allowedCreateCourse'];
  316. }
  317. }
  318. /**
  319. *
  320. * @global bool $is_platformAdmin
  321. * @global bool $is_allowedCreateCourse
  322. * @global object $_user
  323. * @global int $_cid
  324. * @global array $_course
  325. * @global type $_real_cid
  326. * @global type $_courseUser
  327. * @global type $is_courseAdmin
  328. * @global type $is_courseTutor
  329. * @global type $is_courseCoach
  330. * @global type $is_courseMember
  331. * @global type $is_sessionAdmin
  332. * @global type $is_allowed_in_course
  333. *
  334. * @param type $course_id
  335. * @param type $reset
  336. */
  337. static function init_course($course_id, $reset)
  338. {
  339. global $_configuration;
  340. global $is_platformAdmin;
  341. global $is_allowedCreateCourse;
  342. global $_user;
  343. global $_cid;
  344. global $_course;
  345. global $_real_cid;
  346. global $is_courseAdmin; //course teacher
  347. global $is_courseTutor; //course teacher - some rights
  348. global $is_courseCoach; //course coach
  349. global $is_courseMember; //course student
  350. global $is_sessionAdmin;
  351. global $is_allowed_in_course;
  352. if ($reset) {
  353. // Course session data refresh requested or empty data
  354. if ($course_id) {
  355. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  356. $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  357. $sql = "SELECT course.*, course_category.code faCode, course_category.name faName
  358. FROM $course_table
  359. LEFT JOIN $course_cat_table
  360. ON course.category_code = course_category.code
  361. WHERE course.code = '$course_id'";
  362. $result = Database::query($sql);
  363. if (Database::num_rows($result) > 0) {
  364. $course_data = Database::fetch_array($result);
  365. //@TODO real_cid should be cid, for working with numeric course id
  366. $_real_cid = $course_data['id'];
  367. $_cid = $course_data['code'];
  368. $_course = array();
  369. $_course['real_id'] = $course_data['id'];
  370. $_course['id'] = $course_data['code']; //auto-assigned integer
  371. $_course['code'] = $course_data['code'];
  372. $_course['name'] = $course_data['title'];
  373. $_course['title'] = $course_data['title'];
  374. $_course['official_code'] = $course_data['visual_code']; // use in echo
  375. $_course['sysCode'] = $course_data['code']; // use as key in db
  376. $_course['path'] = $course_data['directory']; // use as key in path
  377. $_course['dbName'] = $course_data['db_name']; // use as key in db list
  378. $_course['db_name'] = $course_data['db_name']; // not needed in Chamilo 1.9
  379. $_course['titular'] = $course_data['tutor_name']; // this should be deprecated and use the table course_rel_user
  380. $_course['language'] = $course_data['course_language'];
  381. $_course['extLink']['url'] = $course_data['department_url'];
  382. $_course['extLink']['name'] = $course_data['department_name'];
  383. $_course['categoryCode'] = $course_data['faCode'];
  384. $_course['categoryName'] = $course_data['faName'];
  385. $_course['visibility'] = $course_data['visibility'];
  386. $_course['subscribe_allowed'] = $course_data['subscribe'];
  387. $_course['unsubscribe'] = $course_data['unsubscribe'];
  388. $_course['activate_legal'] = $course_data['activate_legal'];
  389. $_course['show_score'] = $course_data['show_score']; //used in the work tool
  390. Session::write('_cid', $_cid);
  391. Session::write('_course', $_course);
  392. //@TODO real_cid should be cid, for working with numeric course id
  393. Session::write('_real_cid', $_real_cid);
  394. // if a session id has been given in url, we store the session
  395. // Database Table Definitions
  396. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  397. if (!empty($_GET['id_session'])) {
  398. $_SESSION['id_session'] = intval($_GET['id_session']);
  399. $sql = 'SELECT name FROM ' . $tbl_session . ' WHERE id="' . intval($_SESSION['id_session']) . '"';
  400. $rs = Database::query($sql);
  401. list($_SESSION['session_name']) = Database::fetch_array($rs);
  402. } else {
  403. Session::erase('session_name');
  404. Session::erase('id_session');
  405. }
  406. if (!isset($_SESSION['login_as'])) {
  407. //Course login
  408. if (isset($_user['user_id'])) {
  409. Event::event_course_login(api_get_course_int_id(), $_user['user_id'], api_get_session_id());
  410. }
  411. }
  412. } else {
  413. //exit("WARNING UNDEFINED CID !! ");
  414. header('location:' . api_get_path(WEB_PATH));
  415. }
  416. } else {
  417. Session::erase('_cid');
  418. Session::erase('_real_cid');
  419. Session::erase('_course');
  420. if (!empty($_SESSION)) {
  421. foreach ($_SESSION as $key => $session_item) {
  422. if (strpos($key, 'lp_autolaunch_') === false) {
  423. continue;
  424. } else {
  425. if (isset($_SESSION[$key])) {
  426. Session::erase($key);
  427. }
  428. }
  429. }
  430. }
  431. //Deleting session info
  432. if (api_get_session_id()) {
  433. Session::erase('id_session');
  434. Session::erase('session_name');
  435. }
  436. }
  437. } else {
  438. // Continue with the previous values
  439. if (empty($_SESSION['_course']) OR empty($_SESSION['_cid'])) { //no previous values...
  440. $_cid = -1; //set default values that will be caracteristic of being unset
  441. $_course = -1;
  442. } else {
  443. $_cid = $_SESSION['_cid'];
  444. $_course = $_SESSION['_course'];
  445. // these lines are usefull for tracking. Indeed we can have lost the id_session and not the cid.
  446. // Moreover, if we want to track a course with another session it can be usefull
  447. if (!empty($_GET['id_session'])) {
  448. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  449. $sql = 'SELECT name FROM ' . $tbl_session . ' WHERE id="' . intval($_SESSION['id_session']) . '"';
  450. $rs = Database::query($sql);
  451. list($_SESSION['session_name']) = Database::fetch_array($rs);
  452. $_SESSION['id_session'] = intval($_GET['id_session']);
  453. }
  454. if (!isset($_SESSION['login_as'])) {
  455. $save_course_access = true;
  456. //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
  457. //Disables the updates in the TRACK_E_COURSE_ACCESS table
  458. if (isset($_dont_save_user_course_access) && $_dont_save_user_course_access == true) {
  459. $save_course_access = false;
  460. }
  461. if ($save_course_access) {
  462. $course_tracking_table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  463. /*
  464. * When $_configuration['session_lifetime'] is too big 100 hours (in order to let users take exercises with no problems)
  465. * the function Tracking::get_time_spent_on_the_course() returns big values (200h) due the condition:
  466. * login_course_date > now() - INTERVAL $session_lifetime SECOND
  467. *
  468. */
  469. /*
  470. if (isset($_configuration['session_lifetime'])) {
  471. $session_lifetime = $_configuration['session_lifetime'];
  472. } else {
  473. $session_lifetime = 3600; // 1 hour
  474. } */
  475. $session_lifetime = 3600; // 1 hour
  476. $course_code = $_course['sysCode'];
  477. $time = api_get_utc_datetime();
  478. if (isset($_user['user_id']) && !empty($_user['user_id'])) {
  479. //We select the last record for the current course in the course tracking table
  480. //But only if the login date is < than now + max_life_time
  481. $sql = "SELECT course_access_id FROM $course_tracking_table
  482. WHERE
  483. user_id = " . intval($_user ['user_id']) . " AND
  484. c_id = '".api_get_course_int_id()."' AND
  485. session_id = " . api_get_session_id() . " AND
  486. login_course_date > now() - INTERVAL $session_lifetime SECOND
  487. ORDER BY login_course_date DESC LIMIT 0,1";
  488. $result = Database::query($sql);
  489. if (Database::num_rows($result) > 0) {
  490. $i_course_access_id = Database::result($result, 0, 0);
  491. //We update the course tracking table
  492. $sql = "UPDATE $course_tracking_table SET logout_course_date = '$time', counter = counter+1
  493. WHERE course_access_id = " . intval($i_course_access_id) . " AND session_id = " . api_get_session_id();
  494. Database::query($sql);
  495. } else {
  496. $sql = "INSERT INTO $course_tracking_table (c_id, user_id, login_course_date, logout_course_date, counter, session_id)" .
  497. "VALUES('" . api_get_course_int_id() . "', '" . $_user['user_id'] . "', '$time', '$time', '1','" . api_get_session_id() . "')";
  498. Database::query($sql);
  499. }
  500. }
  501. }
  502. }
  503. }
  504. }
  505. /* COURSE / USER REL. INIT */
  506. $session_id = api_get_session_id();
  507. $user_id = isset($_user['user_id']) ? $_user['user_id'] : null;
  508. //Course permissions
  509. $is_courseAdmin = false; //course teacher
  510. $is_courseTutor = false; //course teacher - some rights
  511. $is_courseMember = false; //course student
  512. //Course - User permissions
  513. $is_sessionAdmin = false;
  514. if ($reset) {
  515. if (isset($user_id) && $user_id && isset($_cid) && $_cid) {
  516. //Check if user is subscribed in a course
  517. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  518. $sql = "SELECT * FROM $course_user_table
  519. WHERE
  520. user_id = '" . $user_id . "' AND
  521. relation_type <> " . COURSE_RELATION_TYPE_RRHH . " AND
  522. course_code = '$course_id'";
  523. $result = Database::query($sql);
  524. $cuData = null;
  525. if (Database::num_rows($result) > 0) {
  526. // this user have a recorded state for this course
  527. $cuData = Database::fetch_array($result, 'ASSOC');
  528. $is_courseAdmin = (bool) $cuData['status'] == 1;
  529. $is_courseTutor = (bool) $cuData['is_tutor'] == 1;
  530. $is_courseMember = true;
  531. // Checking if the user filled the course legal agreement
  532. if ($_course['activate_legal'] == 1 && !api_is_platform_admin()) {
  533. $user_is_subscribed = CourseManager::is_user_accepted_legal(
  534. $user_id,
  535. $_course['id'],
  536. $session_id
  537. );
  538. if (!$user_is_subscribed) {
  539. $url = api_get_path(WEB_CODE_PATH) . 'course_info/legal.php?course_code=' . $_course['code'] . '&session_id=' . $session_id;
  540. header('Location: ' . $url);
  541. exit;
  542. }
  543. }
  544. }
  545. //We are in a session course? Check session permissions
  546. if (!empty($session_id)) {
  547. //I'm not the teacher of the course
  548. if ($is_courseAdmin == false) {
  549. // this user has no status related to this course
  550. // The user is subscribed in a session? The user is a Session coach a Session admin ?
  551. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  552. $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
  553. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  554. //Session coach, session admin, course coach admin
  555. $sql = "SELECT session.id_coach, session_admin_id, session_rcru.user_id
  556. FROM $tbl_session session, $tbl_session_course_user session_rcru
  557. WHERE
  558. session_rcru.session_id = session.id AND
  559. session_rcru.c_id = '$_real_cid' AND
  560. session_rcru.user_id = '$user_id' AND
  561. session_rcru.session_id = $session_id AND
  562. session_rcru.status = 2";
  563. $result = Database::query($sql);
  564. $row = Database::store_result($result);
  565. //I'm a session admin?
  566. if (isset($row) && isset($row[0]) && $row[0]['session_admin_id'] == $user_id) {
  567. $is_courseMember = false;
  568. $is_courseTutor = false;
  569. $is_courseAdmin = false;
  570. $is_courseCoach = false;
  571. $is_sessionAdmin = true;
  572. } else {
  573. //Im a coach or a student?
  574. $sql = "SELECT user_id, status
  575. FROM " . $tbl_session_course_user . "
  576. WHERE
  577. c_id = '$_cid' AND
  578. user_id = '" . $user_id . "' AND
  579. session_id = '" . $session_id . "'
  580. LIMIT 1";
  581. $result = Database::query($sql);
  582. if (Database::num_rows($result)) {
  583. $row = Database::fetch_array($result, 'ASSOC');
  584. $session_course_status = $row['status'];
  585. switch ($session_course_status) {
  586. case '2': // coach - teacher
  587. $is_courseMember = true;
  588. $is_courseTutor = true;
  589. $is_courseCoach = true;
  590. $is_sessionAdmin = false;
  591. if (api_get_setting('extend_rights_for_coach') == 'true') {
  592. $is_courseAdmin = true;
  593. } else {
  594. $is_courseAdmin = false;
  595. }
  596. break;
  597. case '0': //student
  598. $is_courseMember = true;
  599. $is_courseTutor = false;
  600. $is_courseAdmin = false;
  601. $is_sessionAdmin = false;
  602. break;
  603. default:
  604. //unregister user
  605. $is_courseMember = false;
  606. $is_courseTutor = false;
  607. $is_courseAdmin = false;
  608. $is_sessionAdmin = false;
  609. break;
  610. }
  611. } else {
  612. //unregister user
  613. $is_courseMember = false;
  614. $is_courseTutor = false;
  615. $is_courseAdmin = false;
  616. $is_sessionAdmin = false;
  617. }
  618. }
  619. }
  620. //If I'm the admin platform i'm a teacher of the course
  621. if ($is_platformAdmin) {
  622. $is_courseAdmin = true;
  623. }
  624. }
  625. } else { // keys missing => not anymore in the course - user relation
  626. // course
  627. $is_courseMember = false;
  628. $is_courseAdmin = false;
  629. $is_courseTutor = false;
  630. $is_courseCoach = false;
  631. $is_sessionAdmin = false;
  632. }
  633. //Checking the course access
  634. $is_allowed_in_course = false;
  635. if (isset($_course)) {
  636. switch ($_course['visibility']) {
  637. case COURSE_VISIBILITY_OPEN_WORLD: //3
  638. $is_allowed_in_course = true;
  639. break;
  640. case COURSE_VISIBILITY_OPEN_PLATFORM : //2
  641. if (isset($user_id) && !api_is_anonymous($user_id)) {
  642. $is_allowed_in_course = true;
  643. }
  644. break;
  645. case COURSE_VISIBILITY_REGISTERED: //1
  646. if ($is_platformAdmin || $is_courseMember) {
  647. $is_allowed_in_course = true;
  648. }
  649. break;
  650. case COURSE_VISIBILITY_CLOSED: //0
  651. if ($is_platformAdmin || $is_courseAdmin) {
  652. $is_allowed_in_course = true;
  653. }
  654. break;
  655. case COURSE_VISIBILITY_HIDDEN: //4
  656. if ($is_platformAdmin) {
  657. $is_allowed_in_course = true;
  658. }
  659. break;
  660. }
  661. }
  662. // check the session visibility
  663. if ($is_allowed_in_course == true) {
  664. //if I'm in a session
  665. if ($session_id != 0) {
  666. if (!$is_platformAdmin) {
  667. // admin and session coach are *not* affected to the invisible session mode
  668. // the coach is not affected because he can log in some days after the end date of a session
  669. $session_visibility = api_get_session_visibility($session_id);
  670. switch ($session_visibility) {
  671. case SESSION_INVISIBLE:
  672. $is_allowed_in_course = false;
  673. break;
  674. }
  675. //checking date
  676. }
  677. }
  678. }
  679. // save the states
  680. Session::write('is_courseAdmin', $is_courseAdmin);
  681. Session::write('is_courseMember', $is_courseMember);
  682. Session::write('is_courseTutor', $is_courseTutor);
  683. Session::write('is_courseCoach', $is_courseCoach);
  684. Session::write('is_allowed_in_course', $is_allowed_in_course);
  685. Session::write('is_sessionAdmin', $is_sessionAdmin);
  686. } else {
  687. // continue with the previous values
  688. $is_courseAdmin = $_SESSION['is_courseAdmin'];
  689. $is_courseTutor = $_SESSION['is_courseTutor'];
  690. $is_courseCoach = $_SESSION['is_courseCoach'];
  691. $is_courseMember = $_SESSION['is_courseMember'];
  692. $is_allowed_in_course = $_SESSION['is_allowed_in_course'];
  693. }
  694. }
  695. /**
  696. *
  697. * @global int $_cid
  698. * @global array $_course
  699. * @global int $_gid
  700. *
  701. * @param int $group_id
  702. * @param bool $reset
  703. */
  704. static function init_group($group_id, $reset)
  705. {
  706. global $_cid;
  707. global $_course;
  708. global $_gid;
  709. if ($reset) { // session data refresh requested
  710. if ($group_id && $_cid && !empty($_course['real_id'])) { // have keys to search data
  711. $group_table = Database::get_course_table(TABLE_GROUP);
  712. $sql = "SELECT * FROM $group_table WHERE c_id = " . $_course['real_id'] . " AND id = '$group_id'";
  713. $result = Database::query($sql);
  714. if (Database::num_rows($result) > 0) { // This group has recorded status related to this course
  715. $gpData = Database::fetch_array($result);
  716. $_gid = $gpData ['id'];
  717. Session::write('_gid', $_gid);
  718. } else {
  719. Session::erase('_gid');
  720. }
  721. } elseif (isset($_SESSION['_gid']) or isset($_gid)) { // Keys missing => not anymore in the group - course relation
  722. Session::erase('_gid');
  723. }
  724. } elseif (isset($_SESSION['_gid'])) { // continue with the previous values
  725. $_gid = $_SESSION ['_gid'];
  726. } else { //if no previous value, assign caracteristic undefined value
  727. $_gid = -1;
  728. }
  729. //set variable according to student_view_enabled choices
  730. if (api_get_setting('student_view_enabled') == "true") {
  731. if (isset($_GET['isStudentView'])) {
  732. if ($_GET['isStudentView'] == 'true') {
  733. if (isset($_SESSION['studentview'])) {
  734. if (!empty($_SESSION['studentview'])) {
  735. // switching to studentview
  736. $_SESSION['studentview'] = 'studentview';
  737. }
  738. }
  739. } elseif ($_GET['isStudentView'] == 'false') {
  740. if (isset($_SESSION['studentview'])) {
  741. if (!empty($_SESSION['studentview'])) {
  742. // switching to teacherview
  743. $_SESSION['studentview'] = 'teacherview';
  744. }
  745. }
  746. }
  747. } elseif (!empty($_SESSION['studentview'])) {
  748. //all is fine, no change to that, obviously
  749. } elseif (empty($_SESSION['studentview'])) {
  750. // We are in teacherview here
  751. $_SESSION['studentview'] = 'teacherview';
  752. }
  753. }
  754. }
  755. /**
  756. * Returns true if user exists in the platform when asking the password
  757. *
  758. * @param string $username (email or username)
  759. * @return array|boolean
  760. */
  761. public static function get_user_accounts_by_username($username)
  762. {
  763. if (strpos($username,'@')){
  764. $username = api_strtolower($username);
  765. $email = true;
  766. } else {
  767. $username = api_strtolower($username);
  768. $email = false;
  769. }
  770. if ($email) {
  771. $condition = "LOWER(email) = '".Database::escape_string($username)."' ";
  772. } else {
  773. $condition = "LOWER(username) = '".Database::escape_string($username)."'";
  774. }
  775. $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
  776. $query = "SELECT user_id AS uid, lastname AS lastName, firstname AS firstName, username AS loginName, password, email,
  777. status AS status, official_code, phone, picture_uri, creator_id
  778. FROM $tbl_user
  779. WHERE ( $condition AND active = 1) ";
  780. $result = Database::query($query);
  781. $num_rows = Database::num_rows($result);
  782. if ($result && $num_rows > 0) {
  783. return Database::store_result($result);
  784. }
  785. return false;
  786. }
  787. }