local.inc.php 66 KB

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