local.inc.php 59 KB

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