local.inc.php 59 KB

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