local.inc.php 61 KB

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