local.inc.php 66 KB

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