login.lib.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  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_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  546. //Session coach, session admin, course coach admin
  547. $sql = "SELECT session.id_coach, session_admin_id, session_rcru.user_id
  548. FROM $tbl_session session, $tbl_session_course_user session_rcru
  549. WHERE
  550. session_rcru.session_id = session.id AND
  551. session_rcru.c_id = '$_real_cid' AND
  552. session_rcru.user_id = '$user_id' AND
  553. session_rcru.session_id = $session_id AND
  554. session_rcru.status = 2";
  555. $result = Database::query($sql);
  556. $row = Database::store_result($result);
  557. //I'm a session admin?
  558. if (isset($row) && isset($row[0]) && $row[0]['session_admin_id'] == $user_id) {
  559. $is_courseMember = false;
  560. $is_courseTutor = false;
  561. $is_courseAdmin = false;
  562. $is_courseCoach = false;
  563. $is_sessionAdmin = true;
  564. } else {
  565. //Im a coach or a student?
  566. $sql = "SELECT user_id, status
  567. FROM " . $tbl_session_course_user."
  568. WHERE
  569. c_id = '$_cid' AND
  570. user_id = '".$user_id."' AND
  571. session_id = '" . $session_id."'
  572. LIMIT 1";
  573. $result = Database::query($sql);
  574. if (Database::num_rows($result)) {
  575. $row = Database::fetch_array($result, 'ASSOC');
  576. $session_course_status = $row['status'];
  577. switch ($session_course_status) {
  578. case '2': // coach - teacher
  579. $is_courseMember = true;
  580. $is_courseTutor = true;
  581. $is_courseCoach = true;
  582. $is_sessionAdmin = false;
  583. if (api_get_setting('extend_rights_for_coach') == 'true') {
  584. $is_courseAdmin = true;
  585. } else {
  586. $is_courseAdmin = false;
  587. }
  588. break;
  589. case '0': //student
  590. $is_courseMember = true;
  591. $is_courseTutor = false;
  592. $is_courseAdmin = false;
  593. $is_sessionAdmin = false;
  594. break;
  595. default:
  596. //unregister user
  597. $is_courseMember = false;
  598. $is_courseTutor = false;
  599. $is_courseAdmin = false;
  600. $is_sessionAdmin = false;
  601. break;
  602. }
  603. } else {
  604. //unregister user
  605. $is_courseMember = false;
  606. $is_courseTutor = false;
  607. $is_courseAdmin = false;
  608. $is_sessionAdmin = false;
  609. }
  610. }
  611. }
  612. //If I'm the admin platform i'm a teacher of the course
  613. if ($is_platformAdmin) {
  614. $is_courseAdmin = true;
  615. }
  616. }
  617. } else { // keys missing => not anymore in the course - user relation
  618. // course
  619. $is_courseMember = false;
  620. $is_courseAdmin = false;
  621. $is_courseTutor = false;
  622. $is_courseCoach = false;
  623. $is_sessionAdmin = false;
  624. }
  625. //Checking the course access
  626. $is_allowed_in_course = false;
  627. if (isset($_course)) {
  628. switch ($_course['visibility']) {
  629. case COURSE_VISIBILITY_OPEN_WORLD: //3
  630. $is_allowed_in_course = true;
  631. break;
  632. case COURSE_VISIBILITY_OPEN_PLATFORM : //2
  633. if (isset($user_id) && !api_is_anonymous($user_id)) {
  634. $is_allowed_in_course = true;
  635. }
  636. break;
  637. case COURSE_VISIBILITY_REGISTERED: //1
  638. if ($is_platformAdmin || $is_courseMember) {
  639. $is_allowed_in_course = true;
  640. }
  641. break;
  642. case COURSE_VISIBILITY_CLOSED: //0
  643. if ($is_platformAdmin || $is_courseAdmin) {
  644. $is_allowed_in_course = true;
  645. }
  646. break;
  647. case COURSE_VISIBILITY_HIDDEN: //4
  648. if ($is_platformAdmin) {
  649. $is_allowed_in_course = true;
  650. }
  651. break;
  652. }
  653. }
  654. // check the session visibility
  655. if ($is_allowed_in_course == true) {
  656. //if I'm in a session
  657. if ($session_id != 0) {
  658. if (!$is_platformAdmin) {
  659. // admin and session coach are *not* affected to the invisible session mode
  660. // the coach is not affected because he can log in some days after the end date of a session
  661. $session_visibility = api_get_session_visibility($session_id);
  662. switch ($session_visibility) {
  663. case SESSION_INVISIBLE:
  664. $is_allowed_in_course = false;
  665. break;
  666. }
  667. //checking date
  668. }
  669. }
  670. }
  671. // save the states
  672. Session::write('is_courseAdmin', $is_courseAdmin);
  673. Session::write('is_courseMember', $is_courseMember);
  674. Session::write('is_courseTutor', $is_courseTutor);
  675. Session::write('is_courseCoach', $is_courseCoach);
  676. Session::write('is_allowed_in_course', $is_allowed_in_course);
  677. Session::write('is_sessionAdmin', $is_sessionAdmin);
  678. } else {
  679. // continue with the previous values
  680. $is_courseAdmin = Session::read('is_courseAdmin');
  681. $is_courseTutor = Session::read('is_courseTutor');
  682. $is_courseCoach = Session::read('is_courseCoach');
  683. $is_courseMember = Session::read('is_courseMember');
  684. $is_allowed_in_course = Session::read('is_allowed_in_course');
  685. }
  686. }
  687. /**
  688. *
  689. * @global int $_cid
  690. * @global array $_course
  691. * @global int $_gid
  692. *
  693. * @param int $group_id
  694. * @param bool $reset
  695. */
  696. static function init_group($group_id, $reset)
  697. {
  698. global $_cid;
  699. global $_course;
  700. global $_gid;
  701. if ($reset) { // session data refresh requested
  702. if ($group_id && $_cid && !empty($_course['real_id'])) { // have keys to search data
  703. $group_table = Database::get_course_table(TABLE_GROUP);
  704. $sql = "SELECT * FROM $group_table WHERE c_id = ".$_course['real_id']." AND id = '$group_id'";
  705. $result = Database::query($sql);
  706. if (Database::num_rows($result) > 0) { // This group has recorded status related to this course
  707. $gpData = Database::fetch_array($result);
  708. $_gid = $gpData ['id'];
  709. Session::write('_gid', $_gid);
  710. } else {
  711. Session::erase('_gid');
  712. }
  713. } elseif (isset($_SESSION['_gid']) or isset($_gid)) { // Keys missing => not anymore in the group - course relation
  714. Session::erase('_gid');
  715. }
  716. } elseif (isset($_SESSION['_gid'])) { // continue with the previous values
  717. $_gid = $_SESSION ['_gid'];
  718. } else { //if no previous value, assign caracteristic undefined value
  719. $_gid = -1;
  720. }
  721. //set variable according to student_view_enabled choices
  722. if (api_get_setting('student_view_enabled') == "true") {
  723. if (isset($_GET['isStudentView'])) {
  724. if ($_GET['isStudentView'] == 'true') {
  725. if (isset($_SESSION['studentview'])) {
  726. if (!empty($_SESSION['studentview'])) {
  727. // switching to studentview
  728. $_SESSION['studentview'] = 'studentview';
  729. }
  730. }
  731. } elseif ($_GET['isStudentView'] == 'false') {
  732. if (isset($_SESSION['studentview'])) {
  733. if (!empty($_SESSION['studentview'])) {
  734. // switching to teacherview
  735. $_SESSION['studentview'] = 'teacherview';
  736. }
  737. }
  738. }
  739. //} elseif (!empty($_SESSION['studentview'])) {
  740. //all is fine, no change to that, obviously
  741. } elseif (empty($_SESSION['studentview'])) {
  742. // We are in teacherview here
  743. $_SESSION['studentview'] = 'teacherview';
  744. }
  745. }
  746. }
  747. /**
  748. * Returns true if user exists in the platform when asking the password
  749. *
  750. * @param string $username (email or username)
  751. * @return array|boolean
  752. */
  753. public static function get_user_accounts_by_username($username)
  754. {
  755. if (strpos($username, '@')) {
  756. $username = api_strtolower($username);
  757. $email = true;
  758. } else {
  759. $username = api_strtolower($username);
  760. $email = false;
  761. }
  762. if ($email) {
  763. $condition = "LOWER(email) = '".Database::escape_string($username)."' ";
  764. } else {
  765. $condition = "LOWER(username) = '".Database::escape_string($username)."'";
  766. }
  767. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  768. $query = "SELECT
  769. user_id AS uid,
  770. lastname AS lastName,
  771. firstname AS firstName,
  772. username AS loginName,
  773. password,
  774. email,
  775. status AS status,
  776. official_code,
  777. phone,
  778. picture_uri,
  779. creator_id,
  780. auth_source
  781. FROM $tbl_user
  782. WHERE ( $condition AND active = 1) ";
  783. $result = Database::query($query);
  784. $num_rows = Database::num_rows($result);
  785. if ($result && $num_rows > 0) {
  786. return Database::fetch_assoc($result);
  787. }
  788. return false;
  789. }
  790. }