local.inc.php 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. *
  5. * SCRIPT PURPOSE
  6. *
  7. * This script initializes and manages Chamilo session information. It
  8. * keeps available session information up to date.
  9. *
  10. * You can request a course id. It will check if the course Id requested is the
  11. * same as the current one. If it isn't it will update session information from
  12. * the database. You can also force the course reset if you want ($cidReset).
  13. *
  14. * All the course information is stored in the $_course array.
  15. *
  16. * You can request a group id. The script will check if the group id requested is the
  17. * same as the current one. If it isn't it will update session information from
  18. * the database. You can also force the course reset if you want ($gidReset).
  19. *
  20. * The course id is stored in $_cid session variable.
  21. * The group id is stored in $_gid session variable.
  22. *
  23. *
  24. * VARIABLES AFFECTING THE SCRIPT BEHAVIOR
  25. *
  26. * string $login
  27. * string $password
  28. * boolean $logout
  29. *
  30. * string $cidReq : course id requested
  31. * boolean $cidReset : ask for a course Reset, if no $cidReq is provided in the
  32. * same time, all course informations is removed from the
  33. * current session
  34. *
  35. * int $gidReq : group Id requested
  36. * boolean $gidReset : ask for a group Reset, if no $gidReq is provided in the
  37. * same time, all group informations is removed from the
  38. * current session
  39. *
  40. *
  41. * VARIABLES SET AND RETURNED BY THE SCRIPT
  42. *
  43. * All the variables below are set and returned by this script.
  44. *
  45. * USER VARIABLES
  46. *
  47. * string $_user ['firstName' ]
  48. * string $_user ['lastName' ]
  49. * string $_user ['mail' ]
  50. * string $_user ['lastLogin' ]
  51. * string $_user ['official_code']
  52. * string $_user ['picture_uri' ]
  53. * string $_user['user_id']
  54. *
  55. * boolean $is_platformAdmin
  56. * boolean $is_allowedCreateCourse
  57. *
  58. * COURSE VARIABLES
  59. * see the function get_course_info_with_category
  60. * boolean $is_courseMember
  61. * boolean $is_courseTutor
  62. * boolean $is_courseAdmin
  63. *
  64. *
  65. * GROUP VARIABLES
  66. *
  67. * int $_gid (the group id)
  68. *
  69. *
  70. * IMPORTANT ADVICE FOR DEVELOPERS
  71. *
  72. * We strongly encourage developers to use a connection layer at the top of
  73. * their scripts rather than use these variables, as they are, inside the core
  74. * of their scripts. It will make code maintenance much easier.
  75. *
  76. * Many if the functions you need you can already find in the
  77. * main_api.lib.php
  78. *
  79. * We encourage you to use functions to access these global "kernel" variables.
  80. * You can add them to e.g. the main API library.
  81. *
  82. *
  83. * SCRIPT STRUCTURE
  84. *
  85. * 1. The script determines if there is an authentication attempt. This part
  86. * only chek if the login name and password are valid. Afterwards, it set the
  87. * $_user['user_id'] (user id) and the $uidReset flag. Other user informations are retrieved
  88. * later. It's also in this section that optional external authentication
  89. * devices step in.
  90. *
  91. * 2. The script determines what other session informations have to be set or
  92. * reset, setting correctly $cidReset (for course) and $gidReset (for group).
  93. *
  94. * 3. If needed, the script retrieves the other user informations (first name,
  95. * last name, ...) and stores them in session.
  96. *
  97. * 4. If needed, the script retrieves the course information and stores them
  98. * in session
  99. *
  100. * 5. The script initializes the user permission status and permission for the
  101. * course level
  102. *
  103. * 6. If needed, the script retrieves group informations an store them in
  104. * session.
  105. *
  106. * 7. The script initializes the user status and permission for the group level.
  107. *
  108. * @package chamilo.include
  109. */
  110. // Verified if exists the username and password in session current
  111. use ChamiloSession as Session;
  112. // Facebook connexion, if activated
  113. if (api_is_facebook_auth_activated() && !api_get_user_id()) {
  114. require_once api_get_path(SYS_PATH).'main/auth/external_login/facebook.inc.php';
  115. if (isset($facebook_config['appId']) && isset($facebook_config['secret'])) {
  116. facebookConnect();
  117. }
  118. }
  119. // Conditional login
  120. if (isset($_SESSION['conditional_login']['uid']) && $_SESSION['conditional_login']['can_login'] === true) {
  121. $uData = api_get_user_info($_SESSION['conditional_login']['uid']);
  122. ConditionalLogin::check_conditions($uData);
  123. $_user['user_id'] = $_SESSION['conditional_login']['uid'];
  124. $_user['status'] = $uData['status'];
  125. Session::write('_user', $_user);
  126. Session::erase('conditional_login');
  127. $uidReset=true;
  128. Event::event_login($_user['user_id']);
  129. }
  130. // parameters passed via GET
  131. $logout = isset($_GET["logout"]) ? $_GET["logout"] : '';
  132. $gidReq = isset($_GET["gidReq"]) ? intval($_GET["gidReq"]) : '';
  133. //this fixes some problems with generic functionalities like
  134. //My Agenda & What's New icons linking to courses
  135. // $cidReq can be set in the index.php file of a course-area
  136. $cidReq = isset($cidReq) ? Database::escape_string($cidReq) : '';
  137. // $cidReq can be set in URL-parameter
  138. $cidReq = isset($_GET["cidReq"]) ? Database::escape_string($_GET["cidReq"]) : $cidReq;
  139. $cidReset = isset($cidReset) ? Database::escape_string($cidReset) : '';
  140. // $cidReset can be set in URL-parameter
  141. $cidReset = (
  142. isset($_GET['cidReq']) && ((isset($_SESSION['_cid'])
  143. && $_GET['cidReq']!=$_SESSION['_cid']) || (!isset($_SESSION['_cid'])))
  144. ) ? Database::escape_string($_GET["cidReq"]) : $cidReset;
  145. // $cDir is a special url param sent by courses/.htaccess
  146. $cDir = (!empty($_GET['cDir']) ? $_GET['cDir'] : null);
  147. $gidReset = isset($gidReset) ? $gidReset : '';
  148. // $gidReset can be set in URL-parameter
  149. // parameters passed via POST
  150. $login = isset($_POST["login"]) ? $_POST["login"] : '';
  151. // register if the user is just logging in, in order to redirect him
  152. $logging_in = false;
  153. /* MAIN CODE */
  154. if (!empty($_SESSION['_user']['user_id']) && !($login || $logout)) {
  155. // uid is in session => login already done, continue with this value
  156. $_user['user_id'] = $_SESSION['_user']['user_id'];
  157. //Check if we have to reset user data
  158. //This param can be used to reload user data if user has been logged by external script
  159. if (isset($_SESSION['_user']['uidReset']) && $_SESSION['_user']['uidReset']) {
  160. $uidReset = true;
  161. }
  162. } else {
  163. if (isset($_user['user_id'])) {
  164. unset($_user['user_id']);
  165. }
  166. // Platform legal terms and conditions
  167. if (api_get_setting('allow_terms_conditions') == 'true') {
  168. if (isset($_POST['login']) && isset($_POST['password']) &&
  169. isset($_SESSION['term_and_condition']['user_id'])
  170. ) {
  171. // user id
  172. $user_id = $_SESSION['term_and_condition']['user_id'];
  173. // Update the terms & conditions
  174. $legal_type = null;
  175. //verify type of terms and conditions
  176. if (isset($_POST['legal_info'])) {
  177. $info_legal = explode(':', $_POST['legal_info']);
  178. $legal_type = LegalManager::get_type_of_terms_and_conditions(
  179. $info_legal[0],
  180. $info_legal[1]
  181. );
  182. }
  183. //is necessary verify check
  184. if ($legal_type == 1) {
  185. if ((isset($_POST['legal_accept']) && $_POST['legal_accept']=='1')) {
  186. $legal_option = true;
  187. } else {
  188. $legal_option = false;
  189. }
  190. }
  191. //no is check option
  192. if ($legal_type == 0) {
  193. $legal_option=true;
  194. }
  195. if (isset($_POST['legal_accept_type']) && $legal_option === true) {
  196. $cond_array = explode(':', $_POST['legal_accept_type']);
  197. if (!empty($cond_array[0]) && !empty($cond_array[1])) {
  198. $time = time();
  199. $condition_to_save = intval($cond_array[0]).':'.intval($cond_array[1]).':'.$time;
  200. UserManager::update_extra_field_value(
  201. $user_id,
  202. 'legal_accept',
  203. $condition_to_save
  204. );
  205. }
  206. }
  207. }
  208. }
  209. //IF cas is activated and user isn't logged in
  210. if (api_get_setting('cas_activate') == 'true') {
  211. $cas_activated = true;
  212. } else {
  213. $cas_activated = false;
  214. }
  215. $cas_login = false;
  216. if ($cas_activated && !isset($_user['user_id']) && !isset($_POST['login']) && !$logout) {
  217. require_once(api_get_path(SYS_PATH).'main/auth/cas/authcas.php');
  218. $cas_login = cas_is_authenticated();
  219. }
  220. if ((isset($_POST['login']) && isset($_POST['password'])) || ($cas_login)) {
  221. // $login && $password are given to log in
  222. if ($cas_login && empty($_POST['login'])) {
  223. $login = $cas_login;
  224. } else {
  225. $login = $_POST['login'];
  226. $password = $_POST['password'];
  227. }
  228. $userManager = UserManager::getManager();
  229. $userRepository = UserManager::getRepository();
  230. // Lookup the user in the main database
  231. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  232. $sql = "SELECT user_id, username, password, auth_source, active, expiration_date, status
  233. FROM $user_table
  234. WHERE username = '".Database::escape_string($login)."'";
  235. $result = Database::query($sql);
  236. $captchaValidated = true;
  237. $captcha = api_get_setting('allow_captcha');
  238. $allowCaptcha = $captcha == 'true';
  239. if (Database::num_rows($result) > 0) {
  240. $uData = Database::fetch_array($result, 'ASSOC');
  241. if ($allowCaptcha) {
  242. // Checking captcha
  243. if (isset($_POST['captcha'])) {
  244. // Check captcha
  245. $captchaText = $_POST['captcha'];
  246. /** @var Text_CAPTCHA $obj */
  247. $obj = isset($_SESSION['userportal.lib']) ? $_SESSION['userportal.lib'] : null;
  248. if ($obj) {
  249. $obj->getPhrase();
  250. if ($obj->getPhrase() != $captchaText) {
  251. $captchaValidated = false;
  252. } else {
  253. $captchaValidated = true;
  254. }
  255. }
  256. if (isset($_SESSION['captcha_question'])) {
  257. $captcha_question = $_SESSION['captcha_question'];
  258. $captcha_question->destroy();
  259. }
  260. }
  261. // Redirect to login page
  262. if ($captchaValidated == false) {
  263. $loginFailed = true;
  264. Session::erase('_uid');
  265. Session::write('loginFailed', '1');
  266. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=wrong_captcha');
  267. exit;
  268. }
  269. // Check if account is blocked by captcha user extra field see function api_block_account_captcha()
  270. $blockedUntilDate = api_get_user_blocked_by_captcha($login);
  271. if (isset($blockedUntilDate) && !empty($blockedUntilDate)) {
  272. if (time() > api_strtotime($blockedUntilDate, 'UTC')) {
  273. api_clean_account_captcha($login);
  274. } else {
  275. $loginFailed = true;
  276. Session::erase('_uid');
  277. Session::write('loginFailed', '1');
  278. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=blocked_by_captcha');
  279. exit;
  280. }
  281. }
  282. }
  283. if ($uData['auth_source'] == PLATFORM_AUTH_SOURCE ||
  284. $uData['auth_source'] == CAS_AUTH_SOURCE
  285. ) {
  286. $validPassword = false;
  287. $user = $userManager->findUserByUsername($login);
  288. if ($user) {
  289. $validPassword = UserManager::isPasswordValid(
  290. $password,
  291. $user
  292. );
  293. }
  294. // The authentication of this user is managed by Chamilo itself
  295. //$password = api_get_encrypted_password(trim(stripslashes($password)));
  296. // Check the user's password
  297. if (($validPassword || $cas_login) &&
  298. (trim($login) == $uData['username'])
  299. ) {
  300. $update_type = UserManager::get_extra_user_data_by_field(
  301. $uData['user_id'],
  302. 'update_type'
  303. );
  304. $update_type = $update_type['update_type'];
  305. if (!empty($extAuthSource[$update_type]['updateUser'])
  306. && file_exists($extAuthSource[$update_type]['updateUser'])
  307. ) {
  308. include_once $extAuthSource[$update_type]['updateUser'];
  309. }
  310. // Check if the account is active (not locked)
  311. if ($uData['active'] == '1') {
  312. // Check if the expiration date has not been reached
  313. if ($uData['expiration_date'] > date('Y-m-d H:i:s')
  314. || empty($uData['expiration_date'])
  315. ) {
  316. global $_configuration;
  317. if (api_is_multiple_url_enabled()) {
  318. // Check if user is an admin
  319. $my_user_is_admin = UserManager::is_admin($uData['user_id']);
  320. // This user is subscribed in these sites => $my_url_list
  321. $my_url_list = api_get_access_url_from_user($uData['user_id']);
  322. //Check the access_url configuration setting if
  323. // the user is registered in the access_url_rel_user table
  324. //Getting the current access_url_id of the platform
  325. $current_access_url_id = api_get_current_access_url_id();
  326. if ($my_user_is_admin === false) {
  327. // the user have the permissions to enter at this site
  328. if (is_array($my_url_list) &&
  329. in_array($current_access_url_id, $my_url_list)
  330. ) {
  331. ConditionalLogin::check_conditions($uData);
  332. $_user['user_id'] = $uData['user_id'];
  333. $_user['status'] = $uData['status'];
  334. Session::write('_user', $_user);
  335. Event::event_login($_user['user_id']);
  336. $logging_in = true;
  337. } else {
  338. $loginFailed = true;
  339. Session::erase('_uid');
  340. Session::write('loginFailed', '1');
  341. // Fix cas redirection loop
  342. // https://support.chamilo.org/issues/6124
  343. $location = api_get_path(WEB_PATH)
  344. .'index.php?loginFailed=1&error=access_url_inactive';
  345. if ($cas_login) {
  346. cas_logout(null, $location);
  347. } else {
  348. header('Location: '.$location);
  349. }
  350. exit;
  351. }
  352. } else {
  353. //Only admins of the "main" (first) Chamilo portal can login wherever they want
  354. if (in_array(1, $my_url_list)) {
  355. //Check if this admin have the access_url_id = 1 which means the principal
  356. ConditionalLogin::check_conditions($uData);
  357. $_user['user_id'] = $uData['user_id'];
  358. $_user['status'] = $uData['status'];
  359. Session::write('_user', $_user);
  360. Event::event_login($_user['user_id']);
  361. $logging_in = true;
  362. } else {
  363. //This means a secondary admin wants to login so we check as he's a normal user
  364. if (in_array($current_access_url_id, $my_url_list)) {
  365. $_user['user_id'] = $uData['user_id'];
  366. $_user['status'] = $uData['status'];
  367. Session::write('_user', $_user);
  368. Event::event_login($_user['user_id']);
  369. $logging_in = true;
  370. } else {
  371. $loginFailed = true;
  372. Session::erase('_uid');
  373. Session::write('loginFailed', '1');
  374. header(
  375. 'Location: '.api_get_path(WEB_PATH)
  376. .'index.php?loginFailed=1&error=access_url_inactive'
  377. );
  378. exit;
  379. }
  380. }
  381. }
  382. } else {
  383. ConditionalLogin::check_conditions($uData);
  384. $_user['user_id'] = $uData['user_id'];
  385. $_user['status'] = $uData['status'];
  386. Session::write('_user', $_user);
  387. Event::event_login($uData['user_id']);
  388. $logging_in = true;
  389. }
  390. } else {
  391. $loginFailed = true;
  392. Session::erase('_uid');
  393. Session::write('loginFailed', '1');
  394. header(
  395. 'Location: '.api_get_path(WEB_PATH)
  396. .'index.php?loginFailed=1&error=account_expired'
  397. );
  398. exit;
  399. }
  400. } else {
  401. $loginFailed = true;
  402. Session::erase('_uid');
  403. Session::write('loginFailed', '1');
  404. header(
  405. 'Location: '.api_get_path(WEB_PATH)
  406. .'index.php?loginFailed=1&error=account_inactive'
  407. );
  408. exit;
  409. }
  410. } else {
  411. // login failed: username or password incorrect
  412. $loginFailed = true;
  413. Session::erase('_uid');
  414. Session::write('loginFailed', '1');
  415. if ($allowCaptcha) {
  416. if (isset($_SESSION['loginFailedCount'])) {
  417. $_SESSION['loginFailedCount']++;
  418. } else {
  419. $_SESSION['loginFailedCount'] = 1;
  420. }
  421. $numberMistakesToBlockAccount = api_get_setting('captcha_number_mistakes_to_block_account');
  422. if (isset($_SESSION['loginFailedCount'])) {
  423. if ($_SESSION['loginFailedCount'] >= $numberMistakesToBlockAccount) {
  424. api_block_account_captcha($login);
  425. }
  426. }
  427. }
  428. header(
  429. 'Location: '.api_get_path(WEB_PATH)
  430. .'index.php?loginFailed=1&error=user_password_incorrect'
  431. );
  432. exit;
  433. }
  434. if (isset($uData['creator_id']) && $_user['user_id'] != $uData['creator_id']) {
  435. //first login for a not self registred
  436. //e.g. registered by a teacher
  437. //do nothing (code may be added later)
  438. }
  439. } elseif (!empty($extAuthSource[$uData['auth_source']]['login'])
  440. && file_exists($extAuthSource[$uData['auth_source']]['login'])
  441. ) {
  442. /*
  443. * Process external authentication
  444. * on the basis of the given login name
  445. */
  446. $loginFailed = true; // Default initialisation. It could
  447. // change after the external authentication
  448. $key = $uData['auth_source']; //'ldap','shibboleth'...
  449. /* >>>>>>>> External authentication modules <<<<<<<<< */
  450. // see configuration.php to define these
  451. include_once($extAuthSource[$key]['login']);
  452. /* >>>>>>>> External authentication modules <<<<<<<<< */
  453. } else { // no standard Chamilo login - try external authentification
  454. //huh... nothing to do... we shouldn't get here
  455. error_log(
  456. 'Chamilo Authentication file defined in'.
  457. ' $extAuthSource could not be found - this might prevent'.
  458. ' your system from doing the corresponding authentication'.
  459. ' process',
  460. 0
  461. );
  462. }
  463. } else {
  464. // login failed, Database::num_rows($result) <= 0
  465. $loginFailed = true; // Default initialisation. It could
  466. // change after the external authentication
  467. /*
  468. * In this section:
  469. * there is no entry for the $login user in the Chamilo
  470. * database. This also means there is no auth_source for the user.
  471. * We let all external procedures attempt to add him/her
  472. * to the system.
  473. *
  474. * Process external login on the basis
  475. * of the authentication source list
  476. * provided by the configuration settings.
  477. * If the login succeeds, for going further,
  478. * Chamilo needs the $_user['user_id'] variable to be
  479. * set and registered in the session. It's the
  480. * responsability of the external login script
  481. * to provide this $_user['user_id'].
  482. */
  483. if (isset($extAuthSource) && is_array($extAuthSource)) {
  484. foreach ($extAuthSource as $thisAuthSource) {
  485. if (!empty($thisAuthSource['newUser']) && file_exists($thisAuthSource['newUser'])) {
  486. include_once($thisAuthSource['newUser']);
  487. } else {
  488. error_log(
  489. 'Chamilo Authentication file '. $thisAuthSource['newUser'].
  490. ' could not be found - this might prevent your system from using'.
  491. ' the authentication process in the user creation process',
  492. 0
  493. );
  494. }
  495. }
  496. } //end if is_array($extAuthSource)
  497. if ($loginFailed) { //If we are here username given is wrong
  498. Session::write('loginFailed', '1');
  499. header(
  500. 'Location: '.api_get_path(WEB_PATH)
  501. .'index.php?loginFailed=1&error=user_password_incorrect'
  502. );
  503. exit;
  504. }
  505. } //end else login failed
  506. } elseif (api_get_setting('sso_authentication') === 'true'
  507. && !in_array('webservices', explode('/', $_SERVER['REQUEST_URI']))
  508. ) {
  509. /**
  510. * TODO:
  511. * - Work on a better validation for webservices paths. Current is very poor and exit
  512. */
  513. $subsso = api_get_setting('sso_authentication_subclass');
  514. if (!empty($subsso)) {
  515. require_once api_get_path(SYS_CODE_PATH).'auth/sso/sso.'.$subsso.'.class.php';
  516. $subsso = 'sso'.$subsso;
  517. $osso = new $subsso(); //load the subclass
  518. } else {
  519. $osso = new sso();
  520. }
  521. if (isset($_SESSION['_user']['user_id'])) {
  522. if ($logout) {
  523. // Make custom redirect after logout
  524. online_logout($_SESSION['_user']['user_id'], false);
  525. $osso->logout(); //redirects and exits
  526. }
  527. } elseif (!$logout) {
  528. // Handle cookie from Master Server
  529. $forceSsoRedirect = api_get_setting('sso_force_redirect');
  530. if ($forceSsoRedirect === 'true') {
  531. // all users to be redirected unless they are connected (removed req on sso_cookie)
  532. $redirectToMasterConditions = !isset($_GET['sso_referer']) && !isset($_GET['loginFailed']);
  533. } else {
  534. // Users to still see the homepage without connecting
  535. $redirectToMasterConditions = !isset($_GET['sso_referer']) && !isset($_GET['loginFailed']) && isset($_GET['sso_cookie']);
  536. }
  537. if ($redirectToMasterConditions) {
  538. // Redirect to master server
  539. $osso->ask_master();
  540. } elseif (isset($_GET['sso_cookie'])) {
  541. // Here we are going to check the origin of
  542. // what the call says should be used for
  543. // authentication, and ensure we know it
  544. $matches_domain = false;
  545. if (isset($_GET['sso_referer'])) {
  546. $protocol = api_get_setting('sso_authentication_protocol');
  547. // sso_authentication_domain can list
  548. // several, comma-separated, domains
  549. $master_urls = preg_split('/,/', api_get_setting('sso_authentication_domain'));
  550. if (!empty($master_urls)) {
  551. $master_auth_uri = api_get_setting('sso_authentication_auth_uri');
  552. foreach ($master_urls as $mu) {
  553. if (empty($mu)) {
  554. continue;
  555. }
  556. // For each URL, check until we find *one* that matches the $_GET['sso_referer'],
  557. // then skip other possibilities
  558. // Do NOT compare the whole referer, as this might cause confusing errors with friendly urls,
  559. // like in Drupal /?q=user& vs /user?
  560. $referrer = substr($_GET['sso_referer'], 0, strrpos($_GET['sso_referer'], '/'));
  561. if ($protocol.trim($mu) === $referrer) {
  562. $matches_domain = true;
  563. break;
  564. }
  565. }
  566. } else {
  567. error_log(
  568. 'Your sso_authentication_master param is empty. '.
  569. 'Check the platform configuration, security section. '.
  570. 'It can be a list of comma-separated domains'
  571. );
  572. }
  573. }
  574. if ($matches_domain) {
  575. //make all the process of checking
  576. //if the user exists (delegated to the sso class)
  577. $osso->check_user();
  578. } else {
  579. error_log('Check the sso_referer URL in your script, it doesn\'t match any of the possibilities');
  580. //Request comes from unknown source
  581. $loginFailed = true;
  582. Session::erase('_uid');
  583. Session::write('loginFailed', '1');
  584. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=unrecognize_sso_origin');
  585. exit;
  586. }
  587. }
  588. //end logout ... else ... login
  589. } elseif ($logout) {
  590. //if there was an attempted logout without a previous login, log
  591. // this anonymous user out as well but avoid redirect
  592. online_logout(null, false);
  593. $osso->logout(); //redirects and exits
  594. }
  595. } elseif (api_get_setting('openid_authentication')=='true') {
  596. if (!empty($_POST['openid_url'])) {
  597. include api_get_path(SYS_CODE_PATH).'auth/openid/login.php';
  598. openid_begin(trim($_POST['openid_url']), api_get_path(WEB_PATH).'index.php');
  599. //this last function should trigger a redirect, so we can die here safely
  600. die('Openid login redirection should be in progress');
  601. } elseif (!empty($_GET['openid_identity'])) {
  602. //it's usual for PHP to replace '.' (dot) by '_' (underscore) in URL parameters
  603. include(api_get_path(SYS_CODE_PATH).'auth/openid/login.php');
  604. $res = openid_complete($_GET);
  605. if ($res['status'] == 'success') {
  606. $id1 = Database::escape_string($res['openid.identity']);
  607. //have another id with or without the final '/'
  608. $id2 = (substr($id1, -1, 1)=='/'?substr($id1, 0, -1):$id1.'/');
  609. //lookup the user in the main database
  610. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  611. $sql = "SELECT user_id, username, password, auth_source, active, expiration_date
  612. FROM $user_table
  613. WHERE openid = '$id1'
  614. OR openid = '$id2' ";
  615. $result = Database::query($sql);
  616. if ($result !== false) {
  617. if (Database::num_rows($result)>0) {
  618. $uData = Database::fetch_array($result);
  619. if ($uData['auth_source'] == PLATFORM_AUTH_SOURCE) {
  620. //the authentification of this user is managed by Chamilo itself
  621. // check if the account is active (not locked)
  622. if ($uData['active']=='1') {
  623. // check if the expiration date has not been reached
  624. if ($uData['expiration_date'] > date('Y-m-d H:i:s')
  625. || empty($uData['expiration_date'])
  626. ) {
  627. $_user['user_id'] = $uData['user_id'];
  628. $_user['status'] = $uData['status'];
  629. Session::write('_user', $_user);
  630. Event::event_login($_user['user_id']);
  631. } else {
  632. $loginFailed = true;
  633. Session::erase('_uid');
  634. Session::write('loginFailed', '1');
  635. header('Location: index.php?loginFailed=1&error=account_expired');
  636. exit;
  637. }
  638. } else {
  639. $loginFailed = true;
  640. Session::erase('_uid');
  641. Session::write('loginFailed', '1');
  642. header('Location: index.php?loginFailed=1&error=account_inactive');
  643. exit;
  644. }
  645. if (isset($uData['creator_id']) && $_user['user_id'] != $uData['creator_id']) {
  646. //first login for a not self registred
  647. //e.g. registered by a teacher
  648. //do nothing (code may be added later)
  649. }
  650. }
  651. } else {
  652. //Redirect to the subscription form
  653. header(
  654. 'Location: '.api_get_path(WEB_CODE_PATH)
  655. .'auth/inscription.php?username='.$res['openid.sreg.nickname']
  656. .'&email='.$res['openid.sreg.email']
  657. .'&openid='.$res['openid.identity']
  658. .'&openid_msg=idnotfound'
  659. );
  660. Session::write('loginFailed', '1');
  661. exit;
  662. //$loginFailed = true;
  663. }
  664. } else {
  665. $loginFailed = true;
  666. }
  667. } else {
  668. $loginFailed = true;
  669. }
  670. }
  671. } elseif (KeyAuth::is_enabled()) {
  672. $success = KeyAuth::instance()->login();
  673. if ($success) {
  674. $use_anonymous = false;
  675. }
  676. }
  677. $uidReset = true;
  678. // $cidReset = true;
  679. // $gidReset = true;
  680. } // end else
  681. // Now check for anonymous user mode
  682. if (isset($use_anonymous) && $use_anonymous) {
  683. //if anonymous mode is set, then try to set the current user as anonymous
  684. //if he doesn't have a login yet
  685. api_set_anonymous();
  686. } else {
  687. //if anonymous mode is not set, then check if this user is anonymous. If it
  688. //is, clean it from being anonymous (make him a nobody :-))
  689. api_clear_anonymous();
  690. }
  691. // if there is a cDir parameter in the URL (coming from courses/.htaccess redirection)
  692. if (!empty($cDir)) {
  693. $c = CourseManager::get_course_id_from_path($cDir);
  694. if ($c) {
  695. $cidReq = $c;
  696. }
  697. }
  698. // if the requested course is different from the course in session
  699. if (!empty($cidReq) && (!isset($_SESSION['_cid']) ||
  700. (isset($_SESSION['_cid']) && $cidReq != $_SESSION['_cid']))
  701. ) {
  702. $cidReset = true;
  703. $gidReset = true; // As groups depend from courses, group id is reset
  704. }
  705. /* USER INIT */
  706. if (isset($uidReset) && $uidReset) {
  707. // session data refresh requested
  708. unset($_SESSION['_user']['uidReset']);
  709. $is_platformAdmin = false;
  710. $is_allowedCreateCourse = false;
  711. if (isset($_user['user_id']) && $_user['user_id'] && !api_is_anonymous()) {
  712. //if (isset($_user['user_id']) && $_user['user_id']) {
  713. // a uid is given (log in succeeded)
  714. $_SESSION['loginFailed'] = false;
  715. unset($_SESSION['loginFailedCount']);
  716. unset($_SESSION['loginToBlock']);
  717. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  718. $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
  719. $track_e_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  720. $sql = "SELECT user.*, a.user_id is_admin, login.login_date
  721. FROM $user_table
  722. LEFT JOIN $admin_table a
  723. ON user.user_id = a.user_id
  724. LEFT JOIN $track_e_login login
  725. ON user.user_id = login.login_user_id
  726. WHERE user.user_id = '".$_user['user_id']."'
  727. ORDER BY login.login_date DESC LIMIT 1";
  728. $result = Database::query($sql);
  729. if (Database::num_rows($result) > 0) {
  730. // Extracting the user data
  731. $uData = Database::fetch_array($result);
  732. $_user = _api_format_user($uData, false);
  733. $_user['lastLogin'] = api_strtotime($uData['login_date'], 'UTC');
  734. $is_platformAdmin = (bool) (! is_null($uData['is_admin']));
  735. $is_allowedCreateCourse = (bool) (($uData ['status'] == COURSEMANAGER) || (api_get_setting('drhCourseManagerRights') && $uData['status'] == DRH));
  736. ConditionalLogin::check_conditions($uData);
  737. Session::write('_user', $_user);
  738. UserManager::update_extra_field_value($_user['user_id'], 'already_logged_in', 'true');
  739. Session::write('is_platformAdmin', $is_platformAdmin);
  740. Session::write('is_allowedCreateCourse', $is_allowedCreateCourse);
  741. } else {
  742. header('location:'.api_get_path(WEB_PATH));
  743. //exit("WARNING UNDEFINED UID !! ");
  744. }
  745. } else {
  746. if (!api_is_anonymous()) {
  747. // no uid => logout or Anonymous
  748. Session::erase('_user');
  749. Session::erase('_uid');
  750. }
  751. }
  752. Session::write('is_platformAdmin', $is_platformAdmin);
  753. Session::write('is_allowedCreateCourse', $is_allowedCreateCourse);
  754. } else { // continue with the previous values
  755. $_user = $_SESSION['_user'];
  756. $is_platformAdmin = isset($_SESSION['is_platformAdmin']) ? $_SESSION['is_platformAdmin'] : false;
  757. $is_allowedCreateCourse = isset($_SESSION['is_allowedCreateCourse']) ? $_SESSION['is_allowedCreateCourse'] : false;
  758. }
  759. /* COURSE INIT */
  760. if (isset($cidReset) && $cidReset) {
  761. // Course session data refresh requested or empty data
  762. if ($cidReq) {
  763. $_course = api_get_course_info($cidReq);
  764. if (!empty($_course)) {
  765. //@TODO real_cid should be cid, for working with numeric course id
  766. $_real_cid = $_course['real_id'];
  767. $_cid = $_course['code'];
  768. Session::write('_real_cid', $_real_cid);
  769. Session::write('_cid', $_cid);
  770. Session::write('_course', $_course);
  771. // if a session id has been given in url, we store the session
  772. // Database Table Definitions
  773. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  774. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  775. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  776. if (!empty($_GET['id_session'])) {
  777. $sql = 'SELECT name FROM '.$tbl_session . '
  778. WHERE id="'.intval($_GET['id_session']) . '"';
  779. $rs = Database::query($sql);
  780. if (Database::num_rows($rs)) {
  781. list($_SESSION['session_name']) = Database::fetch_array(
  782. $rs
  783. );
  784. $_SESSION['id_session'] = intval($_GET['id_session']);
  785. } else {
  786. api_not_allowed(true);
  787. }
  788. } else {
  789. Session::erase('session_name');
  790. Session::erase('id_session');
  791. }
  792. if (!empty($_GET['gidReq'])) {
  793. $_SESSION['_gid'] = intval($_GET['gidReq']);
  794. } else {
  795. Session::erase('_gid');
  796. }
  797. if (!isset($_SESSION['login_as'])) {
  798. //Course login
  799. if (isset($_user['user_id'])) {
  800. Event::event_course_login(
  801. api_get_course_int_id(),
  802. api_get_user_id(),
  803. api_get_session_id()
  804. );
  805. }
  806. }
  807. } else {
  808. //exit("WARNING UNDEFINED CID !! ");
  809. header('location:'.api_get_path(WEB_PATH));
  810. }
  811. } else {
  812. Session::erase('_cid');
  813. Session::erase('_real_cid');
  814. Session::erase('_course');
  815. if (!empty($_SESSION)) {
  816. foreach ($_SESSION as $key => $session_item) {
  817. if (strpos($key, 'lp_autolaunch_') === false) {
  818. continue;
  819. } else {
  820. if (isset($_SESSION[$key])) {
  821. Session::erase($key);
  822. }
  823. }
  824. }
  825. }
  826. // Deleting session info.
  827. if (api_get_session_id()) {
  828. Session::erase('id_session');
  829. Session::erase('session_name');
  830. }
  831. if (api_get_group_id()) {
  832. Session::erase('_gid');
  833. }
  834. }
  835. } else {
  836. // Continue with the previous values
  837. if (empty($_SESSION['_course']) && !empty($_SESSION['_cid'])) {
  838. //Just in case $_course is empty we try to load if the c_id still exists
  839. $_course = api_get_course_info($_SESSION['_cid']);
  840. if (!empty($_course)) {
  841. $_real_cid = $_course['real_id'];
  842. $_cid = $_course['code'];
  843. Session::write('_real_cid', $_real_cid);
  844. Session::write('_cid', $_cid);
  845. Session::write('_course', $_course);
  846. }
  847. }
  848. if (empty($_SESSION['_course']) or empty($_SESSION['_cid'])) { //no previous values...
  849. $_cid = -1; // Set default values
  850. $_course = -1;
  851. } else {
  852. $_cid = $_SESSION['_cid'];
  853. $_course = $_SESSION['_course'];
  854. // these lines are useful for tracking. Indeed we can have lost the id_session and not the cid.
  855. // Moreover, if we want to track a course with another session it can be usefull
  856. if (!empty($_GET['id_session']) && is_numeric($_GET['id_session'])) {
  857. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  858. $sql = 'SELECT name FROM '.$tbl_session . ' WHERE id="'.intval($_GET['id_session']). '"';
  859. $rs = Database::query($sql);
  860. if (Database::num_rows($rs)) {
  861. list($_SESSION['session_name']) = Database::fetch_array($rs);
  862. $_SESSION['id_session'] = intval($_GET['id_session']);
  863. } else {
  864. api_not_allowed(true);
  865. }
  866. }
  867. if (!empty($_REQUEST['gidReq'])) {
  868. $_SESSION['_gid'] = intval($_REQUEST['gidReq']);
  869. $group_table = Database::get_course_table(TABLE_GROUP);
  870. $sql = "SELECT * FROM $group_table
  871. WHERE c_id = ".$_course['real_id']." AND id = '$gidReq'";
  872. $result = Database::query($sql);
  873. if (Database::num_rows($result) > 0) { // This group has recorded status related to this course
  874. $gpData = Database::fetch_array($result);
  875. $_gid = $gpData ['id'];
  876. Session::write('_gid', $_gid);
  877. }
  878. }
  879. if (!isset($_SESSION['login_as'])) {
  880. $save_course_access = true;
  881. //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
  882. //Disables the updates in the TRACK_E_COURSE_ACCESS table
  883. if (isset($_dont_save_user_course_access) && $_dont_save_user_course_access == true) {
  884. $save_course_access = false;
  885. }
  886. if ($save_course_access) {
  887. $course_tracking_table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  888. /*
  889. * When $_configuration['session_lifetime'] is too big 100 hours (in order to let users take exercises with no problems)
  890. * the function Tracking::get_time_spent_on_the_course() returns big values (200h) due the condition:
  891. * login_course_date > now() - INTERVAL $session_lifetime SECOND
  892. *
  893. */
  894. /*
  895. if (isset($_configuration['session_lifetime'])) {
  896. $session_lifetime = $_configuration['session_lifetime'];
  897. } else {
  898. $session_lifetime = 3600; // 1 hour
  899. }*/
  900. $session_lifetime = 3600; // 1 hour
  901. $course_code = $_course['sysCode'];
  902. $time = api_get_utc_datetime();
  903. if (isset($_user['user_id']) && !empty($_user['user_id'])) {
  904. //We select the last record for the current course in the course tracking table
  905. //But only if the login date is < than now + max_life_time
  906. $sql = "SELECT course_access_id
  907. FROM $course_tracking_table
  908. WHERE
  909. user_id = ".intval($_user['user_id'])." AND
  910. c_id = ".$_course['real_id']." AND
  911. session_id = ".api_get_session_id()." AND
  912. login_course_date > '$time' - INTERVAL $session_lifetime SECOND
  913. ORDER BY login_course_date DESC LIMIT 0,1";
  914. $result = Database::query($sql);
  915. if (Database::num_rows($result) > 0) {
  916. $i_course_access_id = Database::result($result, 0, 0);
  917. //We update the course tracking table
  918. $sql = "UPDATE $course_tracking_table SET logout_course_date = '$time', counter = counter+1
  919. WHERE course_access_id = ".intval($i_course_access_id)." AND session_id = ".api_get_session_id();
  920. Database::query($sql);
  921. } else {
  922. $sql="INSERT INTO $course_tracking_table (c_id, user_id, login_course_date, logout_course_date, counter, session_id)" .
  923. "VALUES('".$_course['real_id']."', '".$_user['user_id']."', '$time', '$time', '1','".api_get_session_id()."')";
  924. Database::query($sql);
  925. }
  926. }
  927. }
  928. }
  929. }
  930. }
  931. /* COURSE / USER REL. INIT */
  932. $session_id = api_get_session_id();
  933. $user_id = isset($_user['user_id']) ? $_user['user_id'] : null;
  934. //Course permissions
  935. //if this code is uncommented in some platforms the is_courseAdmin is not correctly saved see BT#5789
  936. /*$is_courseAdmin = false; //course teacher
  937. $is_courseTutor = false; //course teacher - some rights
  938. $is_courseMember = false; //course student
  939. $is_courseCoach = false; //course coach
  940. */
  941. //Course - User permissions
  942. $is_sessionAdmin = false;
  943. $is_courseCoach = false; //course coach
  944. $is_courseAdmin = false;
  945. $is_courseTutor = false;
  946. $is_courseMember = false;
  947. if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset)) {
  948. if (isset($_cid) && $_cid) {
  949. $my_user_id = isset($user_id) ? intval($user_id) : 0;
  950. $variable = 'accept_legal_'.$my_user_id.'_'.$_course['real_id'].'_'.$session_id;
  951. $user_pass_open_course = false;
  952. if (api_check_user_access_to_legal($_course['visibility']) && Session::read($variable)) {
  953. $user_pass_open_course = true;
  954. }
  955. //Checking if the user filled the course legal agreement
  956. if ($_course['activate_legal'] == 1 && !api_is_platform_admin() && !api_is_anonymous()) {
  957. $user_is_subscribed = CourseManager::is_user_accepted_legal($user_id, $_course['id'], $session_id) || $user_pass_open_course;
  958. if (!$user_is_subscribed) {
  959. $url = api_get_path(WEB_CODE_PATH).'course_info/legal.php?course_code='.$_course['code'].'&session_id='.$session_id;
  960. header('Location: '.$url);
  961. exit;
  962. }
  963. }
  964. }
  965. if (isset($user_id) && $user_id && isset($_real_cid) && $_real_cid) {
  966. //Check if user is subscribed in a course
  967. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  968. $sql = "SELECT * FROM $course_user_table
  969. WHERE
  970. user_id = '".$user_id."' AND
  971. relation_type <> ".COURSE_RELATION_TYPE_RRHH." AND
  972. c_id = '$_real_cid'";
  973. $result = Database::query($sql);
  974. $cuData = null;
  975. if (Database::num_rows($result) > 0) { // this user have a recorded state for this course
  976. $cuData = Database::fetch_array($result, 'ASSOC');
  977. $is_courseAdmin = (bool)($cuData['status'] == 1);
  978. $is_courseTutor = (bool)($cuData['is_tutor'] == 1);
  979. $is_courseMember = true;
  980. }
  981. // We are in a session course? Check session permissions
  982. if (!empty($session_id)) {
  983. // I'm not the teacher of the course
  984. if ($is_courseAdmin == false) {
  985. // This user has no status related to this course
  986. // The user is subscribed in a session? The user is a Session coach a Session admin ?
  987. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  988. $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
  989. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  990. // Session coach, session admin or course coach admin
  991. $sql = "SELECT session.id_coach, session_admin_id, session_rcru.user_id
  992. FROM $tbl_session session, $tbl_session_course_user session_rcru
  993. WHERE
  994. session_rcru.session_id = session.id AND
  995. session_rcru.c_id = '$_real_cid' AND
  996. session_rcru.user_id = '$user_id' AND
  997. session_rcru.session_id = $session_id AND
  998. session_rcru.status = 2
  999. ";
  1000. $result = Database::query($sql);
  1001. $row = Database::store_result($result);
  1002. // Am I a session admin?
  1003. if (isset($row) && isset($row[0]) && $row[0]['session_admin_id'] == $user_id) {
  1004. $is_courseMember = false;
  1005. $is_courseTutor = false;
  1006. $is_courseAdmin = false;
  1007. $is_courseCoach = false;
  1008. $is_sessionAdmin = true;
  1009. } else {
  1010. // Am I a session coach for this session?
  1011. $sql = "SELECT session.id, session.id_coach FROM $tbl_session session
  1012. INNER JOIN $tbl_session_course sc
  1013. ON sc.session_id = session.id
  1014. WHERE session.id = $session_id
  1015. AND session.id_coach = $user_id
  1016. AND sc.c_id = '$_real_cid'";
  1017. $result = Database::query($sql);
  1018. if (Database::num_rows($result)) {
  1019. $is_courseMember = true;
  1020. $is_courseTutor = false;
  1021. $is_courseCoach = true;
  1022. $is_sessionAdmin = false;
  1023. } else {
  1024. // Am I a course coach or a student?
  1025. $sql = "SELECT cu.user_id, cu.status
  1026. FROM $tbl_session_course_user cu
  1027. WHERE
  1028. c_id = '$_real_cid' AND
  1029. cu.user_id = '".$user_id."' AND
  1030. cu.session_id = '".$session_id."'
  1031. LIMIT 1";
  1032. $result = Database::query($sql);
  1033. if (Database::num_rows($result)) {
  1034. $row = Database::fetch_array($result, 'ASSOC');
  1035. $session_course_status = $row['status'];
  1036. switch ($session_course_status) {
  1037. case '2': // coach - teacher
  1038. $is_courseMember = true;
  1039. $is_courseTutor = true;
  1040. $is_courseCoach = true;
  1041. $is_sessionAdmin = false;
  1042. if (api_get_setting('extend_rights_for_coach') == 'true') {
  1043. $is_courseAdmin = true;
  1044. } else {
  1045. $is_courseAdmin = false;
  1046. }
  1047. break;
  1048. case '0': //Student
  1049. $is_courseMember = true;
  1050. $is_courseTutor = false;
  1051. $is_courseAdmin = false;
  1052. $is_courseCoach = false;
  1053. $is_sessionAdmin = false;
  1054. break;
  1055. default:
  1056. //unregister user
  1057. $is_courseMember = false;
  1058. $is_courseTutor = false;
  1059. $is_courseAdmin = false;
  1060. $is_sessionAdmin = false;
  1061. $is_courseCoach = false;
  1062. break;
  1063. }
  1064. } else {
  1065. // Unregister user
  1066. $is_courseMember = false;
  1067. $is_courseTutor = false;
  1068. $is_courseAdmin = false;
  1069. $is_sessionAdmin = false;
  1070. $is_courseCoach = false;
  1071. }
  1072. }
  1073. }
  1074. // Drh can enter to a course as an student see BT#6770
  1075. if (api_drh_can_access_all_session_content()) {
  1076. $sessionInfo = SessionManager::getSessionFollowedByDrh($user_id, $session_id);
  1077. if (!empty($sessionInfo) && !empty($sessionInfo['course_list'])) {
  1078. if (isset($sessionInfo['course_list'][$_course['real_id']])) {
  1079. $is_courseMember = true;
  1080. $is_courseTutor = false;
  1081. $is_courseCoach = false;
  1082. $is_sessionAdmin = false;
  1083. }
  1084. }
  1085. }
  1086. }
  1087. //If I'm the admin platform i'm a teacher of the course
  1088. if ($is_platformAdmin) {
  1089. $is_courseAdmin = true;
  1090. }
  1091. }
  1092. } else { // keys missing => not anymore in the course - user relation
  1093. // course
  1094. $is_courseMember = false;
  1095. $is_courseAdmin = false;
  1096. $is_courseTutor = false;
  1097. $is_courseCoach = false;
  1098. $is_sessionAdmin = false;
  1099. }
  1100. // Checking the course access
  1101. $is_allowed_in_course = false;
  1102. if (isset($_course) && isset($_course['visibility'])) {
  1103. switch ($_course['visibility']) {
  1104. case COURSE_VISIBILITY_OPEN_WORLD: //3
  1105. $is_allowed_in_course = true;
  1106. break;
  1107. case COURSE_VISIBILITY_OPEN_PLATFORM: //2
  1108. if (isset($user_id) && !api_is_anonymous($user_id)) {
  1109. $is_allowed_in_course = true;
  1110. }
  1111. break;
  1112. case COURSE_VISIBILITY_REGISTERED: //1
  1113. if ($is_platformAdmin || $is_courseMember) {
  1114. $is_allowed_in_course = true;
  1115. }
  1116. break;
  1117. case COURSE_VISIBILITY_CLOSED: //0
  1118. if ($is_platformAdmin || $is_courseAdmin) {
  1119. $is_allowed_in_course = true;
  1120. }
  1121. break;
  1122. case COURSE_VISIBILITY_HIDDEN: //4
  1123. if ($is_platformAdmin) {
  1124. $is_allowed_in_course = true;
  1125. }
  1126. }
  1127. }
  1128. if (!$is_platformAdmin) {
  1129. if (!$is_courseMember &&
  1130. isset($_course['registration_code']) &&
  1131. !empty($_course['registration_code']) &&
  1132. !Session::read('course_password_'.$_course['real_id'], false)
  1133. ) {
  1134. // if we are here we try to access to a course requiring password
  1135. if ($is_allowed_in_course) {
  1136. // the course visibility allows to access the course
  1137. // with a password
  1138. $url = api_get_path(WEB_CODE_PATH).'auth/set_temp_password.php?course_id='.$_course['real_id'].'&session_id='.$session_id;
  1139. header('Location: '.$url);
  1140. exit;
  1141. } else {
  1142. $is_courseMember = false;
  1143. $is_courseAdmin = false;
  1144. $is_courseTutor = false;
  1145. $is_courseCoach = false;
  1146. $is_sessionAdmin = false;
  1147. $is_allowed_in_course = false;
  1148. }
  1149. }
  1150. } // check the session visibility
  1151. if ($is_allowed_in_course == true) {
  1152. //if I'm in a session
  1153. if ($session_id != 0) {
  1154. if (!$is_platformAdmin) {
  1155. // admin is not affected to the invisible session mode
  1156. $session_visibility = api_get_session_visibility($session_id);
  1157. switch ($session_visibility) {
  1158. case SESSION_INVISIBLE:
  1159. $is_allowed_in_course = false;
  1160. break;
  1161. }
  1162. //checking date
  1163. }
  1164. }
  1165. }
  1166. // save the states
  1167. if (isset($is_courseAdmin)) {
  1168. Session::write('is_courseAdmin', $is_courseAdmin);
  1169. }
  1170. if (isset($is_courseMember)) {
  1171. Session::write('is_courseMember', $is_courseMember);
  1172. }
  1173. if (isset($is_courseTutor)) {
  1174. Session::write('is_courseTutor', $is_courseTutor);
  1175. }
  1176. Session::write('is_courseCoach', $is_courseCoach);
  1177. Session::write('is_allowed_in_course', $is_allowed_in_course);
  1178. Session::write('is_sessionAdmin', $is_sessionAdmin);
  1179. } else {
  1180. // Continue with the previous values
  1181. $is_courseAdmin = isset($_SESSION['is_courseAdmin']) ? $_SESSION['is_courseAdmin'] : false;
  1182. $is_courseTutor = isset($_SESSION['is_courseTutor']) ? $_SESSION['is_courseTutor'] : false;
  1183. $is_courseCoach = isset($_SESSION['is_courseCoach']) ? $_SESSION['is_courseCoach'] : false;
  1184. $is_courseMember = isset($_SESSION['is_courseMember']) ? $_SESSION['is_courseMember'] : false;
  1185. $is_allowed_in_course = isset($_SESSION ['is_allowed_in_course']) ? $_SESSION ['is_allowed_in_course'] : false;
  1186. }
  1187. //set variable according to student_view_enabled choices
  1188. if (api_get_setting('student_view_enabled') == "true") {
  1189. if (isset($_GET['isStudentView'])) {
  1190. if ($_GET['isStudentView'] == 'true') {
  1191. if (isset($_SESSION['studentview'])) {
  1192. if (!empty($_SESSION['studentview'])) {
  1193. // switching to studentview
  1194. $_SESSION['studentview'] = 'studentview';
  1195. }
  1196. }
  1197. } elseif ($_GET['isStudentView'] == 'false') {
  1198. if (isset($_SESSION['studentview'])) {
  1199. if (!empty($_SESSION['studentview'])) {
  1200. // switching to teacherview
  1201. $_SESSION['studentview'] = 'teacherview';
  1202. }
  1203. }
  1204. }
  1205. } elseif (!empty($_SESSION['studentview'])) {
  1206. //all is fine, no change to that, obviously
  1207. } elseif (empty($_SESSION['studentview'])) {
  1208. // We are in teacherview here
  1209. $_SESSION['studentview'] = 'teacherview';
  1210. }
  1211. }
  1212. if (isset($_cid)) {
  1213. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  1214. $time = api_get_utc_datetime();
  1215. $sql = "UPDATE $tbl_course SET last_visit = '$time' WHERE code='$_cid'";
  1216. Database::query($sql);
  1217. }
  1218. // direct login to course
  1219. if ((isset($cas_login) && $cas_login && exist_firstpage_parameter()) ||
  1220. ($logging_in && exist_firstpage_parameter())
  1221. ) {
  1222. $redirectCourseDir = api_get_firstpage_parameter();
  1223. api_delete_firstpage_parameter(); // delete the cookie
  1224. if (!isset($_SESSION['request_uri'])) {
  1225. if (CourseManager::get_course_id_from_path($redirectCourseDir)) {
  1226. $_SESSION['noredirection'] = false;
  1227. $_SESSION['request_uri'] = api_get_path(WEB_COURSE_PATH) . $redirectCourseDir;
  1228. }
  1229. }
  1230. } elseif (api_user_is_login() && exist_firstpage_parameter()) {
  1231. $redirectCourseDir = api_get_firstpage_parameter();
  1232. api_delete_firstpage_parameter(); // delete the cookie
  1233. if (CourseManager::get_course_id_from_path($redirectCourseDir)) {
  1234. $_SESSION['noredirection'] = false;
  1235. $_SESSION['request_uri'] = api_get_path(WEB_COURSE_PATH) . $redirectCourseDir;
  1236. }
  1237. }
  1238. Redirect::session_request_uri($logging_in, $user_id);