local.inc.php 57 KB

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