local.inc.php 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527
  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)
  441. .'index.php?loginFailed=1&error=user_password_incorrect'
  442. );
  443. exit;
  444. }
  445. if (isset($uData['creator_id']) && $_user['user_id'] != $uData['creator_id']) {
  446. //first login for a not self registred
  447. //e.g. registered by a teacher
  448. //do nothing (code may be added later)
  449. }
  450. } elseif (!empty($extAuthSource[$uData['auth_source']]['login'])
  451. && file_exists($extAuthSource[$uData['auth_source']]['login'])
  452. ) {
  453. /*
  454. * Process external authentication
  455. * on the basis of the given login name
  456. */
  457. $loginFailed = true; // Default initialisation. It could
  458. // change after the external authentication
  459. $key = $uData['auth_source']; //'ldap','shibboleth'...
  460. // Check if organisationemail email exist for this user and replace the current login with
  461. $extraFieldValue = new ExtraFieldValue('user');
  462. $newLogin = $extraFieldValue->get_values_by_handler_and_field_variable(
  463. $uData['user_id'],
  464. 'organisationemail'
  465. );
  466. if (!empty($newLogin) && isset($newLogin['value'])) {
  467. $login = $newLogin['value'];
  468. }
  469. /* >>>>>>>> External authentication modules <<<<<<<<< */
  470. // see configuration.php to define these
  471. include_once($extAuthSource[$key]['login']);
  472. /* >>>>>>>> External authentication modules <<<<<<<<< */
  473. } else { // no standard Chamilo login - try external authentification
  474. //huh... nothing to do... we shouldn't get here
  475. error_log(
  476. 'Chamilo Authentication file defined in'.
  477. ' $extAuthSource could not be found - this might prevent'.
  478. ' your system from doing the corresponding authentication'.
  479. ' process',
  480. 0
  481. );
  482. }
  483. } else {
  484. $extraFieldValue = new ExtraFieldValue('user');
  485. $uData = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
  486. 'organisationemail',
  487. $login
  488. );
  489. if (!empty($uData)) {
  490. $uData = api_get_user_info($uData['item_id']);
  491. if (!empty($extAuthSource[$uData['auth_source']]['login'])
  492. && file_exists($extAuthSource[$uData['auth_source']]['login'])
  493. ) {
  494. /*
  495. * Process external authentication
  496. * on the basis of the given login name
  497. */
  498. $loginFailed = true; // Default initialisation. It could
  499. // change after the external authentication
  500. $key = $uData['auth_source']; //'ldap','shibboleth'...
  501. /* >>>>>>>> External authentication modules <<<<<<<<< */
  502. // see configuration.php to define these
  503. include_once($extAuthSource[$key]['login']);
  504. }
  505. } else {
  506. // change after the external authentication
  507. // login failed, Database::num_rows($result) <= 0
  508. $loginFailed = true; // Default initialisation. It could
  509. }
  510. // login failed, Database::num_rows($result) <= 0
  511. $loginFailed = true; // Default initialisation. It could
  512. // change after the external authentication
  513. /*
  514. * In this section:
  515. * there is no entry for the $login user in the Chamilo
  516. * database. This also means there is no auth_source for the user.
  517. * We let all external procedures attempt to add him/her
  518. * to the system.
  519. *
  520. * Process external login on the basis
  521. * of the authentication source list
  522. * provided by the configuration settings.
  523. * If the login succeeds, for going further,
  524. * Chamilo needs the $_user['user_id'] variable to be
  525. * set and registered in the session. It's the
  526. * responsability of the external login script
  527. * to provide this $_user['user_id'].
  528. */
  529. if (isset($extAuthSource) && is_array($extAuthSource)) {
  530. foreach ($extAuthSource as $thisAuthSource) {
  531. if (!empty($thisAuthSource['login']) && file_exists($thisAuthSource['login'])) {
  532. include_once($thisAuthSource['login']);
  533. }
  534. if (isset($thisAuthSource['newUser']) && file_exists($thisAuthSource['newUser'])) {
  535. include_once($thisAuthSource['newUser']);
  536. } else {
  537. error_log(
  538. 'Chamilo Authentication external file'.
  539. ' could not be found - this might prevent your system from using'.
  540. ' the authentication process in the user creation process',
  541. 0
  542. );
  543. }
  544. }
  545. } //end if is_array($extAuthSource)
  546. $checkUserInfo = Session::read('_user');
  547. if ($loginFailed && empty($checkUserInfo)) {
  548. //If we are here username given is wrong
  549. Session::write('loginFailed', '1');
  550. header(
  551. 'Location: '.api_get_path(WEB_PATH)
  552. .'index.php?loginFailed=1&error=user_password_incorrect'
  553. );
  554. exit;
  555. }
  556. } //end else login failed
  557. } elseif (api_get_setting('sso_authentication') === 'true'
  558. && !in_array('webservices', explode('/', $_SERVER['REQUEST_URI']))
  559. ) {
  560. /**
  561. * TODO:
  562. * - Work on a better validation for webservices paths. Current is very poor and exit
  563. */
  564. $subsso = api_get_setting('sso_authentication_subclass');
  565. if (!empty($subsso)) {
  566. require_once api_get_path(SYS_CODE_PATH).'auth/sso/sso.'.$subsso.'.class.php';
  567. $subsso = 'sso'.$subsso;
  568. $osso = new $subsso(); //load the subclass
  569. } else {
  570. $osso = new sso();
  571. }
  572. if (isset($_SESSION['_user']['user_id'])) {
  573. if ($logout) {
  574. // Make custom redirect after logout
  575. online_logout($_SESSION['_user']['user_id'], false);
  576. $osso->logout(); //redirects and exits
  577. }
  578. } elseif (!$logout) {
  579. // Handle cookie from Master Server
  580. $forceSsoRedirect = api_get_setting('sso_force_redirect');
  581. if ($forceSsoRedirect === 'true') {
  582. // all users to be redirected unless they are connected (removed req on sso_cookie)
  583. $redirectToMasterConditions = !isset($_GET['sso_referer']) && !isset($_GET['loginFailed']);
  584. } else {
  585. // Users to still see the homepage without connecting
  586. $redirectToMasterConditions = !isset($_GET['sso_referer']) && !isset($_GET['loginFailed']) && isset($_GET['sso_cookie']);
  587. }
  588. if ($redirectToMasterConditions) {
  589. // Redirect to master server
  590. $osso->ask_master();
  591. } elseif (isset($_GET['sso_cookie'])) {
  592. // Here we are going to check the origin of
  593. // what the call says should be used for
  594. // authentication, and ensure we know it
  595. $matches_domain = false;
  596. if (isset($_GET['sso_referer'])) {
  597. $protocol = api_get_setting('sso_authentication_protocol');
  598. // sso_authentication_domain can list
  599. // several, comma-separated, domains
  600. $master_urls = preg_split('/,/', api_get_setting('sso_authentication_domain'));
  601. if (!empty($master_urls)) {
  602. $master_auth_uri = api_get_setting('sso_authentication_auth_uri');
  603. foreach ($master_urls as $mu) {
  604. if (empty($mu)) {
  605. continue;
  606. }
  607. // For each URL, check until we find *one* that matches the $_GET['sso_referer'],
  608. // then skip other possibilities
  609. // Do NOT compare the whole referer, as this might cause confusing errors with friendly urls,
  610. // like in Drupal /?q=user& vs /user?
  611. $referrer = substr($_GET['sso_referer'], 0, strrpos($_GET['sso_referer'], '/'));
  612. if ($protocol.trim($mu) === $referrer) {
  613. $matches_domain = true;
  614. break;
  615. }
  616. }
  617. } else {
  618. error_log(
  619. 'Your sso_authentication_master param is empty. '.
  620. 'Check the platform configuration, security section. '.
  621. 'It can be a list of comma-separated domains'
  622. );
  623. }
  624. }
  625. if ($matches_domain) {
  626. //make all the process of checking
  627. //if the user exists (delegated to the sso class)
  628. $osso->check_user();
  629. } else {
  630. error_log('Check the sso_referer URL in your script, it doesn\'t match any of the possibilities');
  631. //Request comes from unknown source
  632. $loginFailed = true;
  633. Session::erase('_uid');
  634. Session::write('loginFailed', '1');
  635. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=unrecognize_sso_origin');
  636. exit;
  637. }
  638. }
  639. //end logout ... else ... login
  640. } elseif ($logout) {
  641. //if there was an attempted logout without a previous login, log
  642. // this anonymous user out as well but avoid redirect
  643. online_logout(null, false);
  644. $osso->logout(); //redirects and exits
  645. }
  646. } elseif (api_get_setting('openid_authentication') == 'true') {
  647. if (!empty($_POST['openid_url'])) {
  648. include api_get_path(SYS_CODE_PATH).'auth/openid/login.php';
  649. openid_begin(trim($_POST['openid_url']), api_get_path(WEB_PATH).'index.php');
  650. //this last function should trigger a redirect, so we can die here safely
  651. die('Openid login redirection should be in progress');
  652. } elseif (!empty($_GET['openid_identity'])) {
  653. //it's usual for PHP to replace '.' (dot) by '_' (underscore) in URL parameters
  654. include(api_get_path(SYS_CODE_PATH).'auth/openid/login.php');
  655. $res = openid_complete($_GET);
  656. if ($res['status'] == 'success') {
  657. $id1 = Database::escape_string($res['openid.identity']);
  658. //have another id with or without the final '/'
  659. $id2 = (substr($id1, -1, 1) == '/' ? substr($id1, 0, -1) : $id1.'/');
  660. //lookup the user in the main database
  661. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  662. $sql = "SELECT user_id, username, password, auth_source, active, expiration_date
  663. FROM $user_table
  664. WHERE openid = '$id1'
  665. OR openid = '$id2' ";
  666. $result = Database::query($sql);
  667. if ($result !== false) {
  668. if (Database::num_rows($result) > 0) {
  669. $uData = Database::fetch_array($result);
  670. if ($uData['auth_source'] == PLATFORM_AUTH_SOURCE) {
  671. //the authentification of this user is managed by Chamilo itself
  672. // check if the account is active (not locked)
  673. if ($uData['active'] == '1') {
  674. // check if the expiration date has not been reached
  675. if ($uData['expiration_date'] > date('Y-m-d H:i:s')
  676. || empty($uData['expiration_date'])
  677. ) {
  678. $_user['user_id'] = $uData['user_id'];
  679. $_user['status'] = $uData['status'];
  680. Session::write('_user', $_user);
  681. Event::event_login($_user['user_id']);
  682. } else {
  683. $loginFailed = true;
  684. Session::erase('_uid');
  685. Session::write('loginFailed', '1');
  686. header('Location: index.php?loginFailed=1&error=account_expired');
  687. exit;
  688. }
  689. } else {
  690. $loginFailed = true;
  691. Session::erase('_uid');
  692. Session::write('loginFailed', '1');
  693. header('Location: index.php?loginFailed=1&error=account_inactive');
  694. exit;
  695. }
  696. if (isset($uData['creator_id']) && $_user['user_id'] != $uData['creator_id']) {
  697. //first login for a not self registred
  698. //e.g. registered by a teacher
  699. //do nothing (code may be added later)
  700. }
  701. }
  702. } else {
  703. // Redirect to the subscription form
  704. header(
  705. 'Location: '.api_get_path(WEB_CODE_PATH)
  706. .'auth/inscription.php?username='.$res['openid.sreg.nickname']
  707. .'&email='.$res['openid.sreg.email']
  708. .'&openid='.$res['openid.identity']
  709. .'&openid_msg=idnotfound'
  710. );
  711. Session::write('loginFailed', '1');
  712. exit;
  713. //$loginFailed = true;
  714. }
  715. } else {
  716. $loginFailed = true;
  717. }
  718. } else {
  719. $loginFailed = true;
  720. }
  721. }
  722. } elseif (KeyAuth::is_enabled()) {
  723. $success = KeyAuth::instance()->login();
  724. if ($success) {
  725. $use_anonymous = false;
  726. }
  727. }
  728. $uidReset = true;
  729. // $cidReset = true;
  730. // $gidReset = true;
  731. } // end else
  732. // Now check for anonymous user mode
  733. if (isset($use_anonymous) && $use_anonymous) {
  734. //if anonymous mode is set, then try to set the current user as anonymous
  735. //if he doesn't have a login yet
  736. api_set_anonymous();
  737. } else {
  738. //if anonymous mode is not set, then check if this user is anonymous. If it
  739. //is, clean it from being anonymous (make him a nobody :-))
  740. api_clear_anonymous();
  741. }
  742. // if the requested course is different from the course in session
  743. if (!empty($cidReq) && (!isset($_SESSION['_cid']) ||
  744. (isset($_SESSION['_cid']) && $cidReq != $_SESSION['_cid']))
  745. ) {
  746. $cidReset = true;
  747. $gidReset = true; // As groups depend from courses, group id is reset
  748. }
  749. /* USER INIT */
  750. if (isset($uidReset) && $uidReset) {
  751. // session data refresh requested
  752. unset($_SESSION['_user']['uidReset']);
  753. $is_platformAdmin = false;
  754. $is_allowedCreateCourse = false;
  755. if (isset($_user['user_id']) && $_user['user_id'] && !api_is_anonymous()) {
  756. // a uid is given (log in succeeded)
  757. $_SESSION['loginFailed'] = false;
  758. unset($_SESSION['loginFailedCount']);
  759. unset($_SESSION['loginToBlock']);
  760. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  761. $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
  762. $track_e_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  763. $sql = "SELECT user.*, a.user_id is_admin, login.login_date
  764. FROM $user_table
  765. LEFT JOIN $admin_table a
  766. ON user.user_id = a.user_id
  767. LEFT JOIN $track_e_login login
  768. ON user.user_id = login.login_user_id
  769. WHERE user.user_id = '".$_user['user_id']."'
  770. ORDER BY login.login_date DESC LIMIT 1";
  771. $result = Database::query($sql);
  772. if (Database::num_rows($result) > 0) {
  773. // Extracting the user data
  774. $uData = Database::fetch_array($result);
  775. $_user = _api_format_user($uData, false);
  776. $is_platformAdmin = (bool) (!is_null($uData['is_admin']));
  777. $is_allowedCreateCourse = (bool) (($uData ['status'] == COURSEMANAGER) || (api_get_setting('drhCourseManagerRights') && $uData['status'] == DRH));
  778. ConditionalLogin::check_conditions($uData);
  779. Session::write('_user', $_user);
  780. UserManager::update_extra_field_value($_user['user_id'], 'already_logged_in', 'true');
  781. Session::write('is_platformAdmin', $is_platformAdmin);
  782. Session::write('is_allowedCreateCourse', $is_allowedCreateCourse);
  783. } else {
  784. header('location:'.api_get_path(WEB_PATH));
  785. //exit("WARNING UNDEFINED UID !! ");
  786. }
  787. } else {
  788. if (!api_is_anonymous()) {
  789. // no uid => logout or Anonymous
  790. Session::erase('_user');
  791. Session::erase('_uid');
  792. }
  793. }
  794. Session::write('is_platformAdmin', $is_platformAdmin);
  795. Session::write('is_allowedCreateCourse', $is_allowedCreateCourse);
  796. } else { // continue with the previous values
  797. $_user = $_SESSION['_user'];
  798. $is_platformAdmin = isset($_SESSION['is_platformAdmin']) ? $_SESSION['is_platformAdmin'] : false;
  799. $is_allowedCreateCourse = isset($_SESSION['is_allowedCreateCourse']) ? $_SESSION['is_allowedCreateCourse'] : false;
  800. }
  801. if (!isset($_SESSION['login_as'])) {
  802. $save_course_access = true;
  803. $_course = Session::read('_course');
  804. if ($_course && isset($_course['real_id'])) {
  805. // 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
  806. // Disables the updates in the TRACK_E_COURSE_ACCESS table
  807. if (isset($_dont_save_user_course_access) && $_dont_save_user_course_access == true) {
  808. $save_course_access = false;
  809. }
  810. if ($save_course_access) {
  811. $course_tracking_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  812. /*
  813. * When $_configuration['session_lifetime'] is too big 100 hours (in order to let users take exercises with no problems)
  814. * the function Tracking::get_time_spent_on_the_course() returns big values (200h) due the condition:
  815. * login_course_date > now() - INTERVAL $session_lifetime SECOND
  816. *
  817. */
  818. /*
  819. if (isset($_configuration['session_lifetime'])) {
  820. $session_lifetime = $_configuration['session_lifetime'];
  821. } else {
  822. $session_lifetime = 3600; // 1 hour
  823. }*/
  824. $session_lifetime = 3600; // 1 hour
  825. $time = api_get_utc_datetime();
  826. if (isset($_user['user_id']) && !empty($_user['user_id'])) {
  827. //We select the last record for the current course in the course tracking table
  828. //But only if the login date is < than now + max_life_time
  829. $sql = "SELECT course_access_id
  830. FROM $course_tracking_table
  831. WHERE
  832. user_id = ".intval($_user['user_id'])." AND
  833. c_id = ".$_course['real_id']." AND
  834. session_id = ".api_get_session_id()." AND
  835. login_course_date > '$time' - INTERVAL $session_lifetime SECOND
  836. ORDER BY login_course_date DESC LIMIT 0,1";
  837. $result = Database::query($sql);
  838. if (Database::num_rows($result) > 0) {
  839. $i_course_access_id = Database::result($result, 0, 0);
  840. // We update the course tracking table
  841. $sql = "UPDATE $course_tracking_table
  842. SET logout_course_date = '$time', counter = counter+1
  843. WHERE
  844. course_access_id = ".intval($i_course_access_id)." AND
  845. session_id = ".api_get_session_id();
  846. Database::query($sql);
  847. } else {
  848. $ip = api_get_real_ip();
  849. $sql = "INSERT INTO $course_tracking_table (c_id, user_ip, user_id, login_course_date, logout_course_date, counter, session_id)
  850. VALUES('".$_course['real_id']."', '".$ip."', '".$_user['user_id']."', '$time', '$time', '1','".api_get_session_id()."')";
  851. Database::query($sql);
  852. }
  853. }
  854. }
  855. }
  856. }
  857. /* COURSE INIT */
  858. if (isset($cidReset) && $cidReset) {
  859. // Course session data refresh requested or empty data
  860. if ($cidReq) {
  861. $_course = api_get_course_info($cidReq);
  862. if (!empty($_course)) {
  863. //@TODO real_cid should be cid, for working with numeric course id
  864. $_real_cid = $_course['real_id'];
  865. $_cid = $_course['code'];
  866. Session::write('_real_cid', $_real_cid);
  867. Session::write('_cid', $_cid);
  868. Session::write('_course', $_course);
  869. // if a session id has been given in url, we store the session
  870. // Database Table Definitions
  871. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  872. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  873. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  874. if (!empty($_GET['id_session'])) {
  875. $sql = 'SELECT name FROM '.$tbl_session.'
  876. WHERE id="'.intval($_GET['id_session']).'"';
  877. $rs = Database::query($sql);
  878. if (Database::num_rows($rs)) {
  879. list($_SESSION['session_name']) = Database::fetch_array($rs);
  880. $_SESSION['id_session'] = intval($_GET['id_session']);
  881. } else {
  882. api_not_allowed(true);
  883. }
  884. } else {
  885. Session::erase('session_name');
  886. Session::erase('id_session');
  887. }
  888. if (!empty($_GET['gidReq'])) {
  889. $_SESSION['_gid'] = intval($_GET['gidReq']);
  890. } else {
  891. Session::erase('_gid');
  892. }
  893. if (!isset($_SESSION['login_as'])) {
  894. //Course login
  895. if (isset($_user['user_id'])) {
  896. Event::event_course_login(
  897. api_get_course_int_id(),
  898. api_get_user_id(),
  899. api_get_session_id()
  900. );
  901. }
  902. }
  903. } else {
  904. //exit("WARNING UNDEFINED CID !! ");
  905. header('location:'.api_get_path(WEB_PATH));
  906. }
  907. } else {
  908. Session::erase('_cid');
  909. Session::erase('_real_cid');
  910. Session::erase('_course');
  911. if (!empty($_SESSION)) {
  912. foreach ($_SESSION as $key => $session_item) {
  913. if (strpos($key, 'lp_autolaunch_') === false) {
  914. continue;
  915. } else {
  916. if (isset($_SESSION[$key])) {
  917. Session::erase($key);
  918. }
  919. }
  920. }
  921. }
  922. // Deleting session info.
  923. if (api_get_session_id()) {
  924. Session::erase('id_session');
  925. Session::erase('session_name');
  926. }
  927. if (api_get_group_id()) {
  928. Session::erase('_gid');
  929. }
  930. }
  931. } else {
  932. // Continue with the previous values
  933. if (empty($_SESSION['_course']) && !empty($_SESSION['_cid'])) {
  934. //Just in case $_course is empty we try to load if the c_id still exists
  935. $_course = api_get_course_info($_SESSION['_cid']);
  936. if (!empty($_course)) {
  937. $_real_cid = $_course['real_id'];
  938. $_cid = $_course['code'];
  939. Session::write('_real_cid', $_real_cid);
  940. Session::write('_cid', $_cid);
  941. Session::write('_course', $_course);
  942. }
  943. }
  944. if (empty($_SESSION['_course']) or empty($_SESSION['_cid'])) { //no previous values...
  945. $_cid = -1; // Set default values
  946. $_course = -1;
  947. } else {
  948. $_cid = $_SESSION['_cid'];
  949. $_course = $_SESSION['_course'];
  950. // these lines are useful for tracking. Indeed we can have lost the id_session and not the cid.
  951. // Moreover, if we want to track a course with another session it can be usefull
  952. if (!empty($_GET['id_session']) && is_numeric($_GET['id_session'])) {
  953. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  954. $sql = 'SELECT name FROM '.$tbl_session.' WHERE id="'.intval($_GET['id_session']).'"';
  955. $rs = Database::query($sql);
  956. if (Database::num_rows($rs)) {
  957. list($_SESSION['session_name']) = Database::fetch_array($rs);
  958. $_SESSION['id_session'] = intval($_GET['id_session']);
  959. } else {
  960. api_not_allowed(true);
  961. }
  962. }
  963. if (!empty($_REQUEST['gidReq'])) {
  964. $_SESSION['_gid'] = intval($_REQUEST['gidReq']);
  965. $group_table = Database::get_course_table(TABLE_GROUP);
  966. $sql = "SELECT * FROM $group_table
  967. WHERE c_id = ".$_course['real_id']." AND id = '$gidReq'";
  968. $result = Database::query($sql);
  969. if (Database::num_rows($result) > 0) { // This group has recorded status related to this course
  970. $gpData = Database::fetch_array($result);
  971. $_gid = $gpData ['id'];
  972. Session::write('_gid', $_gid);
  973. }
  974. }
  975. }
  976. }
  977. /* COURSE / USER REL. INIT */
  978. $session_id = api_get_session_id();
  979. $user_id = isset($_user['user_id']) ? $_user['user_id'] : null;
  980. //Course permissions
  981. //if this code is uncommented in some platforms the is_courseAdmin is not correctly saved see BT#5789
  982. /*$is_courseAdmin = false; //course teacher
  983. $is_courseTutor = false; //course teacher - some rights
  984. $is_courseMember = false; //course student
  985. $is_courseCoach = false; //course coach
  986. */
  987. // Course - User permissions
  988. $is_sessionAdmin = false;
  989. $is_courseCoach = false; //course coach
  990. $is_courseAdmin = false;
  991. $is_courseTutor = false;
  992. $is_courseMember = false;
  993. if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset)) {
  994. if (isset($_cid) && $_cid) {
  995. $my_user_id = isset($user_id) ? intval($user_id) : 0;
  996. $variable = 'accept_legal_'.$my_user_id.'_'.$_course['real_id'].'_'.$session_id;
  997. $user_pass_open_course = false;
  998. if (api_check_user_access_to_legal($_course['visibility']) && Session::read($variable)) {
  999. $user_pass_open_course = true;
  1000. }
  1001. // Checking if the user filled the course legal agreement
  1002. if ($_course['activate_legal'] == 1 && !api_is_platform_admin() && !api_is_anonymous()) {
  1003. $user_is_subscribed = CourseManager::is_user_accepted_legal(
  1004. $user_id,
  1005. $_course['id'],
  1006. $session_id
  1007. ) || $user_pass_open_course;
  1008. if (!$user_is_subscribed) {
  1009. $url = api_get_path(WEB_CODE_PATH).'course_info/legal.php?course_code='.$_course['code'].'&session_id='.$session_id;
  1010. header('Location: '.$url);
  1011. exit;
  1012. }
  1013. }
  1014. // Platform legal terms and conditions
  1015. if (api_get_setting('allow_terms_conditions') === 'true' &&
  1016. api_get_setting('load_term_conditions_section') === 'course'
  1017. ) {
  1018. $termAndConditionStatus = api_check_term_condition($user_id);
  1019. // @todo not sure why we need the login password and update_term_status
  1020. if ($termAndConditionStatus === false) {
  1021. Session::write('term_and_condition', array('user_id' => $user_id));
  1022. } else {
  1023. Session::erase('term_and_condition');
  1024. }
  1025. $termsAndCondition = Session::read('term_and_condition');
  1026. if (isset($termsAndCondition['user_id'])) {
  1027. // user id
  1028. $user_id = $termsAndCondition['user_id'];
  1029. // Update the terms & conditions
  1030. $legal_type = null;
  1031. // Verify type of terms and conditions
  1032. if (isset($_POST['legal_info'])) {
  1033. $info_legal = explode(':', $_POST['legal_info']);
  1034. $legal_type = LegalManager::get_type_of_terms_and_conditions(
  1035. $info_legal[0],
  1036. $info_legal[1]
  1037. );
  1038. }
  1039. // is necessary verify check
  1040. if ($legal_type === 1) {
  1041. if (isset($_POST['legal_accept']) && $_POST['legal_accept'] == '1') {
  1042. $legal_option = true;
  1043. } else {
  1044. $legal_option = false;
  1045. }
  1046. }
  1047. // no is check option
  1048. if ($legal_type == 0) {
  1049. $legal_option = true;
  1050. }
  1051. if (isset($_POST['legal_accept_type']) && $legal_option === true) {
  1052. $cond_array = explode(':', $_POST['legal_accept_type']);
  1053. if (!empty($cond_array[0]) && !empty($cond_array[1])) {
  1054. $time = time();
  1055. $condition_to_save = intval($cond_array[0]).':'.intval($cond_array[1]).':'.$time;
  1056. UserManager::update_extra_field_value(
  1057. $user_id,
  1058. 'legal_accept',
  1059. $condition_to_save
  1060. );
  1061. }
  1062. }
  1063. $url = api_get_path(WEB_CODE_PATH).'auth/inscription.php';
  1064. header("Location:".$url);
  1065. exit;
  1066. }
  1067. }
  1068. }
  1069. if (isset($user_id) && $user_id && isset($_real_cid) && $_real_cid) {
  1070. //Check if user is subscribed in a course
  1071. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1072. $sql = "SELECT * FROM $course_user_table
  1073. WHERE
  1074. user_id = '".$user_id."' AND
  1075. relation_type <> ".COURSE_RELATION_TYPE_RRHH." AND
  1076. c_id = '$_real_cid'";
  1077. $result = Database::query($sql);
  1078. $cuData = null;
  1079. if (Database::num_rows($result) > 0) { // this user have a recorded state for this course
  1080. $cuData = Database::fetch_array($result, 'ASSOC');
  1081. $is_courseAdmin = (bool) ($cuData['status'] == 1);
  1082. $is_courseTutor = (bool) ($cuData['is_tutor'] == 1);
  1083. $is_courseMember = true;
  1084. }
  1085. // We are in a session course? Check session permissions
  1086. if (!empty($session_id)) {
  1087. // I'm not the teacher of the course
  1088. if ($is_courseAdmin == false) {
  1089. // This user has no status related to this course
  1090. // The user is subscribed in a session? The user is a Session coach a Session admin ?
  1091. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1092. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1093. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1094. // Session coach, session admin or course coach admin
  1095. $sql = "SELECT session.id_coach, session_admin_id, session_rcru.user_id
  1096. FROM $tbl_session session, $tbl_session_course_user session_rcru
  1097. WHERE
  1098. session_rcru.session_id = session.id AND
  1099. session_rcru.c_id = '$_real_cid' AND
  1100. session_rcru.user_id = '$user_id' AND
  1101. session_rcru.session_id = $session_id AND
  1102. session_rcru.status = 2
  1103. ";
  1104. $result = Database::query($sql);
  1105. $row = Database::store_result($result);
  1106. // Am I a session admin?
  1107. if (isset($row) && isset($row[0]) && $row[0]['session_admin_id'] == $user_id) {
  1108. $is_courseMember = false;
  1109. $is_courseTutor = false;
  1110. $is_courseAdmin = false;
  1111. $is_courseCoach = false;
  1112. $is_sessionAdmin = true;
  1113. } else {
  1114. // Am I a session coach for this session?
  1115. $sql = "SELECT session.id, session.id_coach FROM $tbl_session session
  1116. INNER JOIN $tbl_session_course sc
  1117. ON sc.session_id = session.id
  1118. WHERE session.id = $session_id
  1119. AND session.id_coach = $user_id
  1120. AND sc.c_id = '$_real_cid'";
  1121. $result = Database::query($sql);
  1122. if (Database::num_rows($result)) {
  1123. $is_courseMember = true;
  1124. $is_courseTutor = false;
  1125. $is_courseCoach = true;
  1126. $is_sessionAdmin = false;
  1127. } else {
  1128. // Am I a course coach or a student?
  1129. $sql = "SELECT cu.user_id, cu.status
  1130. FROM $tbl_session_course_user cu
  1131. WHERE
  1132. c_id = '$_real_cid' AND
  1133. cu.user_id = '".$user_id."' AND
  1134. cu.session_id = '".$session_id."'
  1135. LIMIT 1";
  1136. $result = Database::query($sql);
  1137. if (Database::num_rows($result)) {
  1138. $row = Database::fetch_array($result, 'ASSOC');
  1139. $session_course_status = $row['status'];
  1140. switch ($session_course_status) {
  1141. case '2': // coach - teacher
  1142. $is_courseMember = true;
  1143. $is_courseTutor = true;
  1144. $is_courseCoach = true;
  1145. $is_sessionAdmin = false;
  1146. if (api_get_setting('extend_rights_for_coach') == 'true') {
  1147. $is_courseAdmin = true;
  1148. } else {
  1149. $is_courseAdmin = false;
  1150. }
  1151. break;
  1152. case '0': //Student
  1153. $is_courseMember = true;
  1154. $is_courseTutor = false;
  1155. $is_courseAdmin = false;
  1156. $is_courseCoach = false;
  1157. $is_sessionAdmin = false;
  1158. break;
  1159. default:
  1160. //unregister user
  1161. $is_courseMember = false;
  1162. $is_courseTutor = false;
  1163. $is_courseAdmin = false;
  1164. $is_sessionAdmin = false;
  1165. $is_courseCoach = false;
  1166. break;
  1167. }
  1168. } else {
  1169. // Unregister user
  1170. $is_courseMember = false;
  1171. $is_courseTutor = false;
  1172. $is_courseAdmin = false;
  1173. $is_sessionAdmin = false;
  1174. $is_courseCoach = false;
  1175. }
  1176. }
  1177. }
  1178. // Drh can enter to a course as an student see BT#6770
  1179. if (api_drh_can_access_all_session_content()) {
  1180. $sessionInfo = SessionManager::getSessionFollowedByDrh($user_id, $session_id);
  1181. if (!empty($sessionInfo) && !empty($sessionInfo['course_list'])) {
  1182. if (isset($sessionInfo['course_list'][$_course['real_id']])) {
  1183. $is_courseMember = true;
  1184. $is_courseTutor = false;
  1185. $is_courseCoach = false;
  1186. $is_sessionAdmin = false;
  1187. }
  1188. }
  1189. }
  1190. }
  1191. // If I'm the admin platform i'm a teacher of the course
  1192. if ($is_platformAdmin) {
  1193. $is_courseAdmin = true;
  1194. }
  1195. } else {
  1196. // User has not access to the course
  1197. // This will check if the course was added in one of his sessions
  1198. // Then it will be redirected to that course-session
  1199. if ($is_courseMember == false) {
  1200. // Search session
  1201. $courseSession = SessionManager::searchCourseInSessionsFromUser(
  1202. $user_id,
  1203. $_course['real_id']
  1204. );
  1205. if (!empty($courseSession) && isset($courseSession[0])) {
  1206. $courseSessionItem = $courseSession[0];
  1207. if (isset($courseSessionItem['session_id'])) {
  1208. $customSessionId = $courseSessionItem['session_id'];
  1209. $url = $_course['course_public_url'].'?id_session='.$customSessionId;
  1210. Session::erase('_real_cid');
  1211. Session::erase('_cid');
  1212. Session::erase('_course');
  1213. header('Location: '.$url);
  1214. exit;
  1215. }
  1216. }
  1217. }
  1218. }
  1219. } else { // keys missing => not anymore in the course - user relation
  1220. // course
  1221. $is_courseMember = false;
  1222. $is_courseAdmin = false;
  1223. $is_courseTutor = false;
  1224. $is_courseCoach = false;
  1225. $is_sessionAdmin = false;
  1226. }
  1227. // Checking the course access
  1228. $is_allowed_in_course = false;
  1229. if (isset($_course) && isset($_course['visibility'])) {
  1230. switch ($_course['visibility']) {
  1231. case COURSE_VISIBILITY_OPEN_WORLD: //3
  1232. $is_allowed_in_course = true;
  1233. break;
  1234. case COURSE_VISIBILITY_OPEN_PLATFORM: //2
  1235. $userAccess = api_get_configuration_value('block_registered_users_access_to_open_course_contents');
  1236. // If this setting is not set or equals false, allow registered users to access content from any open
  1237. // course
  1238. if ($userAccess == false) {
  1239. if (isset($user_id) && !api_is_anonymous($user_id)) {
  1240. $is_allowed_in_course = true;
  1241. }
  1242. } else {
  1243. // If the setting == true, then only allow users to access the content of an open course if they are
  1244. // directly subscribed to the course (so first check the registration to the course)
  1245. $courseCode = $_course['code'];
  1246. $isUserSubscribedInCourse = CourseManager::is_user_subscribed_in_course(
  1247. $user_id,
  1248. $courseCode,
  1249. $session_id
  1250. );
  1251. if (isset($user_id) && ($is_platformAdmin || $isUserSubscribedInCourse === true) && !api_is_anonymous($user_id)) {
  1252. $is_allowed_in_course = true;
  1253. }
  1254. }
  1255. break;
  1256. case COURSE_VISIBILITY_REGISTERED: //1
  1257. if ($is_platformAdmin || $is_courseMember) {
  1258. $is_allowed_in_course = true;
  1259. }
  1260. break;
  1261. case COURSE_VISIBILITY_CLOSED: //0
  1262. if ($is_platformAdmin || $is_courseAdmin) {
  1263. $is_allowed_in_course = true;
  1264. }
  1265. break;
  1266. case COURSE_VISIBILITY_HIDDEN: //4
  1267. if ($is_platformAdmin) {
  1268. $is_allowed_in_course = true;
  1269. }
  1270. break;
  1271. }
  1272. }
  1273. if (!$is_platformAdmin) {
  1274. if (!$is_courseMember &&
  1275. isset($_course['registration_code']) &&
  1276. !empty($_course['registration_code']) &&
  1277. !Session::read('course_password_'.$_course['real_id'], false)
  1278. ) {
  1279. // if we are here we try to access to a course requiring password
  1280. if ($is_allowed_in_course) {
  1281. // the course visibility allows to access the course
  1282. // with a password
  1283. $url = api_get_path(WEB_CODE_PATH).'auth/set_temp_password.php?course_id='.$_course['real_id'].'&session_id='.$session_id;
  1284. header('Location: '.$url);
  1285. exit;
  1286. } else {
  1287. $is_courseMember = false;
  1288. $is_courseAdmin = false;
  1289. $is_courseTutor = false;
  1290. $is_courseCoach = false;
  1291. $is_sessionAdmin = false;
  1292. $is_allowed_in_course = false;
  1293. }
  1294. }
  1295. } // check the session visibility
  1296. if ($is_allowed_in_course == true) {
  1297. //if I'm in a session
  1298. if ($session_id != 0) {
  1299. if (!$is_platformAdmin) {
  1300. // admin is not affected to the invisible session mode
  1301. $session_visibility = api_get_session_visibility($session_id);
  1302. switch ($session_visibility) {
  1303. case SESSION_INVISIBLE:
  1304. $is_allowed_in_course = false;
  1305. break;
  1306. }
  1307. }
  1308. }
  1309. }
  1310. // save the states
  1311. if (isset($is_courseAdmin)) {
  1312. Session::write('is_courseAdmin', $is_courseAdmin);
  1313. if ($is_courseAdmin) {
  1314. $is_allowed_in_course = true;
  1315. }
  1316. }
  1317. if (isset($is_courseMember)) {
  1318. Session::write('is_courseMember', $is_courseMember);
  1319. }
  1320. if (isset($is_courseTutor)) {
  1321. Session::write('is_courseTutor', $is_courseTutor);
  1322. if ($is_courseTutor) {
  1323. $is_allowed_in_course = true;
  1324. }
  1325. }
  1326. Session::write('is_courseCoach', $is_courseCoach);
  1327. Session::write('is_allowed_in_course', $is_allowed_in_course);
  1328. Session::write('is_sessionAdmin', $is_sessionAdmin);
  1329. } else {
  1330. // Continue with the previous values
  1331. $is_courseAdmin = isset($_SESSION['is_courseAdmin']) ? $_SESSION['is_courseAdmin'] : false;
  1332. $is_courseTutor = isset($_SESSION['is_courseTutor']) ? $_SESSION['is_courseTutor'] : false;
  1333. $is_courseCoach = isset($_SESSION['is_courseCoach']) ? $_SESSION['is_courseCoach'] : false;
  1334. $is_courseMember = isset($_SESSION['is_courseMember']) ? $_SESSION['is_courseMember'] : false;
  1335. $is_allowed_in_course = isset($_SESSION ['is_allowed_in_course']) ? $_SESSION ['is_allowed_in_course'] : false;
  1336. }
  1337. //set variable according to student_view_enabled choices
  1338. if (api_get_setting('student_view_enabled') == "true") {
  1339. if (isset($_GET['isStudentView'])) {
  1340. if ($_GET['isStudentView'] == 'true') {
  1341. if (isset($_SESSION['studentview'])) {
  1342. if (!empty($_SESSION['studentview'])) {
  1343. // switching to studentview
  1344. $_SESSION['studentview'] = 'studentview';
  1345. }
  1346. }
  1347. } elseif ($_GET['isStudentView'] == 'false') {
  1348. if (isset($_SESSION['studentview'])) {
  1349. if (!empty($_SESSION['studentview'])) {
  1350. // switching to teacherview
  1351. $_SESSION['studentview'] = 'teacherview';
  1352. }
  1353. }
  1354. }
  1355. } elseif (!empty($_SESSION['studentview'])) {
  1356. //all is fine, no change to that, obviously
  1357. } elseif (empty($_SESSION['studentview'])) {
  1358. // We are in teacherview here
  1359. $_SESSION['studentview'] = 'teacherview';
  1360. }
  1361. }
  1362. if (isset($_cid)) {
  1363. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  1364. $time = api_get_utc_datetime();
  1365. $sql = "UPDATE $tbl_course SET last_visit = '$time' WHERE code='$_cid'";
  1366. Database::query($sql);
  1367. }
  1368. // direct login to course
  1369. if ((isset($cas_login) && $cas_login && exist_firstpage_parameter()) ||
  1370. ($logging_in && exist_firstpage_parameter())
  1371. ) {
  1372. $redirectCourseDir = api_get_firstpage_parameter();
  1373. api_delete_firstpage_parameter(); // delete the cookie
  1374. if (!isset($_SESSION['request_uri'])) {
  1375. if (CourseManager::get_course_id_from_path($redirectCourseDir)) {
  1376. $_SESSION['noredirection'] = false;
  1377. $_SESSION['request_uri'] = api_get_path(WEB_COURSE_PATH).$redirectCourseDir.'/';
  1378. }
  1379. }
  1380. } elseif (api_user_is_login() && exist_firstpage_parameter()) {
  1381. $redirectCourseDir = api_get_firstpage_parameter();
  1382. api_delete_firstpage_parameter(); // delete the cookie
  1383. if (CourseManager::get_course_id_from_path($redirectCourseDir)) {
  1384. $_SESSION['noredirection'] = false;
  1385. $_SESSION['request_uri'] = api_get_path(WEB_COURSE_PATH).$redirectCourseDir.'/';
  1386. }
  1387. }
  1388. Redirect::session_request_uri($logging_in, $user_id);