local.inc.php 60 KB

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