local.inc.php 65 KB

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