local.inc.php 60 KB

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