login.lib.php 38 KB

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