local.inc.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. *
  5. * SCRIPT PURPOSE
  6. *
  7. * This script initializes and manages Chamilo session information. It
  8. * keeps available session information up to date.
  9. *
  10. * You can request a course id. It will check if the course Id requested is the
  11. * same as the current one. If it isn't it will update session information from
  12. * the database. You can also force the course reset if you want ($cidReset).
  13. *
  14. * All the course information is stored in the $_course array.
  15. *
  16. * You can request a group id. The script will check if the group id requested is the
  17. * same as the current one. If it isn't it will update session information from
  18. * the database. You can also force the course reset if you want ($gidReset).
  19. *
  20. * The course id is stored in $_cid session variable.
  21. * The group id is stored in $_gid session variable.
  22. *
  23. * @package chamilo.include
  24. */
  25. //require_once api_get_path(LIBRARY_PATH).'conditionallogin.lib.php'; moved to autologin
  26. // verified if exists the username and password in session current
  27. use \ChamiloSession as Session;
  28. //Conditional login
  29. if (isset($_SESSION['conditional_login']['uid']) && $_SESSION['conditional_login']['can_login']=== true) {
  30. $uData = UserManager::get_user_info_by_id($_SESSION['conditional_login']['uid']);
  31. ConditionalLogin::check_conditions($uData);
  32. $_user['user_id'] = $_SESSION['conditional_login']['uid'];
  33. $_user['status'] = $uData['status'];
  34. Session::write('_user', $_user);
  35. Session::erase('conditional_login');
  36. $uidReset=true;
  37. event_login();
  38. }
  39. // parameters passed via GET
  40. $logout = isset($_GET["logout"]) ? $_GET["logout"] : '';
  41. $gidReq = isset($_GET["gidReq"]) ? Database::escape_string($_GET["gidReq"]) : null;
  42. //this fixes some problems with generic functionalities like
  43. //My Agenda & What's New icons linking to courses
  44. // $cidReq can be set in the index.php file of a course-area
  45. $cidReq = isset($cidReq) ? Database::escape_string($cidReq) : '';
  46. // $cidReq can be set in URL-parameter
  47. $cidReq = isset($_GET["cidReq"]) ? Database::escape_string($_GET["cidReq"]) : $cidReq;
  48. $cidReset = isset($cidReset) ? Database::escape_string($cidReset) : '';
  49. // $cidReset can be set in URL-parameter
  50. $cidReset = (isset($_GET['cidReq']) && ((isset($_SESSION['_cid']) && $_GET['cidReq']!=$_SESSION['_cid']) || (!isset($_SESSION['_cid'])))) ? Database::escape_string($_GET["cidReq"]) : $cidReset;
  51. // $cDir is a special url param sent by courses/.htaccess
  52. $cDir = (!empty($_GET['cDir']) ? $_GET['cDir'] : null);
  53. $gidReset = isset($gidReset) ? $gidReset : '';
  54. // $gidReset can be set in URL-parameter
  55. // parameters passed via POST
  56. $login = isset($_POST["login"]) ? $_POST["login"] : '';
  57. // register if the user is just logging in, in order to redirect him
  58. $logging_in = false;
  59. /* MAIN CODE */
  60. if (!empty($_SESSION['_user']['user_id']) && !($login || $logout)) {
  61. // uid is in session => login already done, continue with this value
  62. $_user['user_id'] = $_SESSION['_user']['user_id'];
  63. //Check if we have to reset user data
  64. //This param can be used to reload user data if user has been logged by external script
  65. if (isset($_SESSION['_user']['uidReset']) && $_SESSION['_user']['uidReset']) {
  66. $uidReset = true;
  67. }
  68. } else {
  69. if (isset($_user['user_id'])) {
  70. unset($_user['user_id']);
  71. }
  72. //Platform legal terms and conditions
  73. if (api_get_setting('allow_terms_conditions') == 'true') {
  74. if (isset($_POST['login']) && isset($_POST['password']) && isset($_SESSION['term_and_condition']['user_id'])) {
  75. $user_id = $_SESSION['term_and_condition']['user_id']; // user id
  76. // Update the terms & conditions
  77. $legal_type = null;
  78. //verify type of terms and conditions
  79. if (isset($_POST['legal_info'])) {
  80. $info_legal = explode(':', $_POST['legal_info']);
  81. $legal_type = LegalManager::get_type_of_terms_and_conditions($info_legal[0], $info_legal[1]);
  82. }
  83. //is necessary verify check
  84. if ($legal_type == 1) {
  85. if ((isset($_POST['legal_accept']) && $_POST['legal_accept']=='1')) {
  86. $legal_option = true;
  87. } else {
  88. $legal_option = false;
  89. }
  90. }
  91. //no is check option
  92. if ($legal_type == 0) {
  93. $legal_option=true;
  94. }
  95. if (isset($_POST['legal_accept_type']) && $legal_option===true) {
  96. $cond_array = explode(':',$_POST['legal_accept_type']);
  97. if (!empty($cond_array[0]) && !empty($cond_array[1])){
  98. $time = time();
  99. $condition_to_save = intval($cond_array[0]).':'.intval($cond_array[1]).':'.$time;
  100. UserManager::update_extra_field_value($user_id,'legal_accept',$condition_to_save);
  101. }
  102. }
  103. }
  104. }
  105. //IF cas is activated and user isn't logged in
  106. if (api_get_setting('cas_activate') == 'true') {
  107. $cas_activated = true;
  108. } else {
  109. $cas_activated = false;
  110. }
  111. $cas_login=false;
  112. if ($cas_activated AND !isset($_user['user_id']) and !isset($_POST['login']) && !$logout) {
  113. require_once api_get_path(SYS_PATH).'main/auth/cas/authcas.php';
  114. $cas_login = cas_is_authenticated();
  115. }
  116. if ((isset($_POST['login']) AND isset($_POST['password']) ) OR ($cas_login)) {
  117. // $login && $password are given to log in
  118. if ( $cas_login && empty($_POST['login']) ) {
  119. $login = $cas_login;
  120. } else {
  121. $login = $_POST['login'];
  122. $password = $_POST['password'];
  123. }
  124. //Lookup the user in the main database
  125. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  126. $sql = "SELECT user_id, username, password, auth_source, active, expiration_date, status FROM $user_table
  127. WHERE username = '".Database::escape_string($login)."'";
  128. $result = Database::query($sql);
  129. if (Database::num_rows($result) > 0) {
  130. $uData = Database::fetch_array($result);
  131. if ($uData['auth_source'] == PLATFORM_AUTH_SOURCE || $uData['auth_source'] == CAS_AUTH_SOURCE) {
  132. //The authentification of this user is managed by Chamilo itself
  133. $password = api_get_encrypted_password(trim(stripslashes($password)));
  134. // Check the user's password
  135. if ( ($password == $uData['password'] OR $cas_login) AND (trim($login) == $uData['username'])) {
  136. $update_type = UserManager::get_extra_user_data_by_field($uData['user_id'], 'update_type');
  137. $update_type= $update_type['update_type'];
  138. if (!empty($extAuthSource[$update_type]['updateUser']) && file_exists($extAuthSource[$update_type]['updateUser'])) {
  139. include_once $extAuthSource[$update_type]['updateUser'];
  140. }
  141. // Check if the account is active (not locked)
  142. if ($uData['active'] == '1') {
  143. // Check if the expiration date has not been reached
  144. if ($uData['expiration_date'] > date('Y-m-d H:i:s') OR $uData['expiration_date'] == '0000-00-00 00:00:00') {
  145. global $_configuration;
  146. if (isset($_configuration['multiple_access_urls']) && $_configuration['multiple_access_urls']) {
  147. //Check if user is an admin
  148. $my_user_is_admin = UserManager::is_admin($uData['user_id']);
  149. // This user is subscribed in these sites => $my_url_list
  150. $my_url_list = api_get_access_url_from_user($uData['user_id']);
  151. //Check the access_url configuration setting if the user is registered in the access_url_rel_user table
  152. //Getting the current access_url_id of the platform
  153. $current_access_url_id = api_get_current_access_url_id();
  154. if ($my_user_is_admin === false) {
  155. if (is_array($my_url_list) && count($my_url_list)>0 ) {
  156. // the user have the permissions to enter at this site
  157. if (in_array($current_access_url_id, $my_url_list)) {
  158. ConditionalLogin::check_conditions($uData);
  159. $_user['user_id'] = $uData['user_id'];
  160. $_user['status'] = $uData['status'];
  161. Session::write('_user',$_user);
  162. event_login();
  163. $logging_in = true;
  164. } else {
  165. $loginFailed = true;
  166. Session::erase('_uid');
  167. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=access_url_inactive');
  168. exit;
  169. }
  170. } else {
  171. $loginFailed = true;
  172. Session::erase('_uid');
  173. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=access_url_inactive');
  174. exit;
  175. }
  176. } else { //Only admins of the "main" (first) Chamilo portal can login wherever they want
  177. if (in_array(1, $my_url_list)) { //Check if this admin have the access_url_id = 1 which means the principal
  178. ConditionalLogin::check_conditions($uData);
  179. $_user['user_id'] = $uData['user_id'];
  180. $_user['status'] = $uData['status'];
  181. Session::write('_user',$_user);
  182. event_login();
  183. } else {
  184. //This means a secondary admin wants to login so we check as he's a normal user
  185. if (in_array($current_access_url_id, $my_url_list)) {
  186. $_user['user_id'] = $uData['user_id'];
  187. $_user['status'] = $uData['status'];
  188. Session::write('_user',$_user);
  189. event_login();
  190. } else {
  191. $loginFailed = true;
  192. Session::erase('_uid');
  193. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=access_url_inactive');
  194. exit;
  195. }
  196. }
  197. }
  198. } else {
  199. //error_log('Loggedin');
  200. ConditionalLogin::check_conditions($uData);
  201. $_user['user_id'] = $uData['user_id'];
  202. $_user['status'] = $uData['status'];
  203. Session::write('_user',$_user);
  204. event_login();
  205. $logging_in = true;
  206. }
  207. } else {
  208. $loginFailed = true;
  209. Session::erase('_uid');
  210. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=account_expired');
  211. exit;
  212. }
  213. } else {
  214. $loginFailed = true;
  215. Session::erase('_uid');
  216. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=account_inactive');
  217. exit;
  218. }
  219. } else {
  220. // login failed: username or password incorrect
  221. $loginFailed = true;
  222. Session::erase('_uid');
  223. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=user_password_incorrect');
  224. exit;
  225. }
  226. if (isset($uData['creator_id']) && $_user['user_id'] != $uData['creator_id']) {
  227. //first login for a not self registred
  228. //e.g. registered by a teacher
  229. //do nothing (code may be added later)
  230. }
  231. } elseif (!empty($extAuthSource[$uData['auth_source']]['login']) && file_exists($extAuthSource[$uData['auth_source']]['login'])) {
  232. /*
  233. * Process external authentication
  234. * on the basis of the given login name
  235. */
  236. $loginFailed = true; // Default initialisation. It could
  237. // change after the external authentication
  238. $key = $uData['auth_source']; //'ldap','shibboleth'...
  239. /* >>>>>>>> External authentication modules <<<<<<<<< */
  240. // see configuration.php to define these
  241. include_once($extAuthSource[$key]['login']);
  242. /* >>>>>>>> External authentication modules <<<<<<<<< */
  243. } else { // no standard Chamilo login - try external authentification
  244. //huh... nothing to do... we shouldn't get here
  245. error_log('Chamilo Authentication file '. $extAuthSource[$uData['auth_source']]['login']. ' could not be found - this might prevent your system from doing the corresponding authentication process',0);
  246. }
  247. } else {
  248. // login failed, Database::num_rows($result) <= 0
  249. $loginFailed = true; // Default initialisation. It could
  250. // change after the external authentication
  251. /*
  252. * In this section:
  253. * there is no entry for the $login user in the Chamilo
  254. * database. This also means there is no auth_source for the user.
  255. * We let all external procedures attempt to add him/her
  256. * to the system.
  257. *
  258. * Process external login on the basis
  259. * of the authentication source list
  260. * provided by the configuration settings.
  261. * If the login succeeds, for going further,
  262. * Chamilo needs the $_user['user_id'] variable to be
  263. * set and registered in the session. It's the
  264. * responsability of the external login script
  265. * to provide this $_user['user_id'].
  266. */
  267. if (isset($extAuthSource) && is_array($extAuthSource)) {
  268. foreach($extAuthSource as $thisAuthSource) {
  269. if (!empty($thisAuthSource['newUser']) && file_exists($thisAuthSource['newUser'])) {
  270. include_once($thisAuthSource['newUser']);
  271. } else {
  272. error_log('Chamilo Authentication file '. $thisAuthSource['newUser']. ' could not be found - this might prevent your system from using the authentication process in the user creation process',0);
  273. }
  274. }
  275. } //end if is_array($extAuthSource)
  276. if ($loginFailed) { //If we are here username given is wrong
  277. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=user_password_incorrect');
  278. }
  279. } //end else login failed
  280. } elseif (api_get_setting('sso_authentication') === 'true' && !in_array('webservices', explode('/', $_SERVER['REQUEST_URI']))) {
  281. /**
  282. * TODO:
  283. * - Work on a better validation for webservices paths. Current is very poor and exit
  284. */
  285. $subsso = api_get_setting('sso_authentication_subclass');
  286. if (!empty($subsso)) {
  287. require_once api_get_path(SYS_CODE_PATH).'auth/sso/sso.'.$subsso.'.class.php';
  288. $subsso = 'sso'.$subsso;
  289. $osso = new $subsso(); //load the subclass
  290. } else {
  291. $osso = new sso();
  292. }
  293. if (isset($_SESSION['_user']['user_id'])) {
  294. if ($logout) {
  295. // Make custom redirect after logout
  296. online_logout($_SESSION['_user']['user_id'], false);
  297. $osso->logout(); //redirects and exits
  298. }
  299. } elseif(!$logout) {
  300. // Handle cookie comming from Master Server
  301. if (!isset($_GET['sso_referer']) && !isset($_GET['loginFailed']) && isset($_GET['sso_cookie'])) {
  302. // Redirect to master server
  303. $osso->ask_master();
  304. } elseif (isset($_GET['sso_cookie'])) {
  305. // Here we are going to check the origin of
  306. // what the call says should be used for
  307. // authentication, and ensure we know it
  308. $matches_domain = false;
  309. if (isset($_GET['sso_referer'])) {
  310. $protocol = api_get_setting('sso_authentication_protocol');
  311. // sso_authentication_domain can list
  312. // several, comma-separated, domains
  313. $master_urls = split(',',api_get_setting('sso_authentication_domain'));
  314. if (!empty($master_urls)) {
  315. $master_auth_uri = api_get_setting('sso_authentication_auth_uri');
  316. foreach ($master_urls as $mu) {
  317. if (empty($mu)) { continue; }
  318. // for each URL, check until we find *one* that matches the $_GET['sso_referer'], then skip the rest
  319. if ($protocol.trim($mu).$master_auth_uri === $_GET['sso_referer']) {
  320. $matches_domain = true;
  321. break;
  322. }
  323. }
  324. } else {
  325. error_log('Your sso_authentication_master param is empty. Check the platform configuration, security section. It can be a list of comma-separated domains');
  326. }
  327. }
  328. if ($matches_domain) {
  329. //make all the process of checking
  330. //if the user exists (delegated to the sso class)
  331. $osso->check_user();
  332. } else {
  333. error_log('Check the sso_referer URL in your script, it doesn\'t match any of the possibilities');
  334. //Request comes from unknown source
  335. $loginFailed = true;
  336. Session::erase('_uid');
  337. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=unrecognize_sso_origin');
  338. exit;
  339. }
  340. }
  341. }//end logout ... else ... login
  342. } elseif (api_get_setting('openid_authentication') == 'true') {
  343. if (!empty($_POST['openid_url'])) {
  344. include api_get_path(SYS_CODE_PATH).'auth/openid/login.php';
  345. openid_begin(trim($_POST['openid_url']), api_get_path(WEB_PATH).'index.php');
  346. //this last function should trigger a redirect, so we can die here safely
  347. die('Openid login redirection should be in progress');
  348. } elseif (!empty($_GET['openid_identity'])) {
  349. //it's usual for PHP to replace '.' (dot) by '_' (underscore) in URL parameters
  350. include(api_get_path(SYS_CODE_PATH).'auth/openid/login.php');
  351. $res = openid_complete($_GET);
  352. if ($res['status'] == 'success') {
  353. $id1 = Database::escape_string($res['openid.identity']);
  354. //have another id with or without the final '/'
  355. $id2 = (substr($id1,-1,1)=='/'?substr($id1,0,-1):$id1.'/');
  356. //lookup the user in the main database
  357. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  358. $sql = "SELECT user_id, username, password, auth_source, active, expiration_date
  359. FROM $user_table
  360. WHERE openid = '$id1'
  361. OR openid = '$id2' ";
  362. $result = Database::query($sql);
  363. if ($result !== false) {
  364. if (Database::num_rows($result)>0) {
  365. //$row = Database::fetch_array($res);
  366. $uData = Database::fetch_array($result);
  367. if ($uData['auth_source'] == PLATFORM_AUTH_SOURCE) {
  368. //the authentification of this user is managed by Chamilo itself
  369. // check if the account is active (not locked)
  370. if ($uData['active']=='1') {
  371. // check if the expiration date has not been reached
  372. if ($uData['expiration_date']>date('Y-m-d H:i:s') OR $uData['expiration_date']=='0000-00-00 00:00:00') {
  373. $_user['user_id'] = $uData['user_id'];
  374. $_user['status'] = $uData['status'];
  375. Session::write('_user',$_user);
  376. event_login();
  377. } else {
  378. $loginFailed = true;
  379. Session::erase('_uid');
  380. header('Location: index.php?loginFailed=1&error=account_expired');
  381. exit;
  382. }
  383. } else {
  384. $loginFailed = true;
  385. Session::erase('_uid');
  386. header('Location: index.php?loginFailed=1&error=account_inactive');
  387. exit;
  388. }
  389. if (isset($uData['creator_id']) && $_user['user_id'] != $uData['creator_id']) {
  390. //first login for a not self registred
  391. //e.g. registered by a teacher
  392. //do nothing (code may be added later)
  393. }
  394. }
  395. } else {
  396. //Redirect to the subscription form
  397. header('Location: '.api_get_path(WEB_CODE_PATH).'auth/inscription.php?username='.$res['openid.sreg.nickname'].'&email='.$res['openid.sreg.email'].'&openid='.$res['openid.identity'].'&openid_msg=idnotfound');
  398. //$loginFailed = true;
  399. }
  400. } else {
  401. $loginFailed = true;
  402. }
  403. } else {
  404. $loginFailed = true;
  405. }
  406. }
  407. } elseif (KeyAuth::is_enabled()) {
  408. $success = KeyAuth::instance()->login();
  409. if($success) {
  410. $use_anonymous = false;
  411. }
  412. }
  413. // else {} => continue as anonymous user
  414. $uidReset = true;
  415. // $cidReset = true;
  416. // $gidReset = true;
  417. } // end else
  418. //Now check for anonymous user mode
  419. if (isset($use_anonymous) && $use_anonymous) {
  420. //if anonymous mode is set, then try to set the current user as anonymous
  421. //if he doesn't have a login yet
  422. api_set_anonymous();
  423. } else {
  424. //if anonymous mode is not set, then check if this user is anonymous. If it
  425. //is, clean it from being anonymous (make him a nobody :-))
  426. api_clear_anonymous();
  427. }
  428. // if there is a cDir parameter in the URL (coming from courses/.htaccess redirection)
  429. if (!empty($cDir)) {
  430. $c = CourseManager::get_course_id_from_path($cDir);
  431. if ($c) { $cidReq = $c; }
  432. }
  433. // if the requested course is different from the course in session
  434. if (!empty($cidReq) && (!isset($_SESSION['_cid']) or (isset($_SESSION['_cid']) && $cidReq != $_SESSION['_cid']))) {
  435. $cidReset = true;
  436. $gidReset = true; // As groups depend from courses, group id is reset
  437. }
  438. /* USER INIT */
  439. if (isset($uidReset) && $uidReset) { // session data refresh requested
  440. unset($_SESSION['_user']['uidReset']);
  441. $is_platformAdmin = false;
  442. $is_allowedCreateCourse = false;
  443. if (isset($_user['user_id']) && $_user['user_id'] && ! api_is_anonymous()) {
  444. // a uid is given (log in succeeded)
  445. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  446. $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
  447. $track_e_login = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  448. $sql = "SELECT user.*, a.user_id is_admin, login.login_date
  449. FROM $user_table
  450. LEFT JOIN $admin_table a
  451. ON user.user_id = a.user_id
  452. LEFT JOIN $track_e_login login
  453. ON user.user_id = login.login_user_id
  454. WHERE user.user_id = '".$_user['user_id']."'
  455. ORDER BY login.login_date DESC LIMIT 1";
  456. $result = Database::query($sql);
  457. if (Database::num_rows($result) > 0) {
  458. // Extracting the user data
  459. $uData = Database::fetch_array($result);
  460. $_user = _api_format_user($uData, false);
  461. $_user['lastLogin'] = api_strtotime($uData['login_date'], 'UTC');
  462. $is_platformAdmin = (bool) (! is_null( $uData['is_admin']));
  463. $is_allowedCreateCourse = (bool) (($uData ['status'] == COURSEMANAGER) or (api_get_setting('drhCourseManagerRights') and $uData['status'] == DRH));
  464. ConditionalLogin::check_conditions($uData);
  465. Session::write('_user', $_user);
  466. UserManager::update_extra_field_value($_user['user_id'], 'already_logged_in', 'true');
  467. Session::write('is_platformAdmin',$is_platformAdmin);
  468. Session::write('is_allowedCreateCourse',$is_allowedCreateCourse);
  469. } else {
  470. header('location:'.api_get_path(WEB_PATH));
  471. //exit("WARNING UNDEFINED UID !! ");
  472. }
  473. } else { // no uid => logout or Anonymous
  474. Session::erase('_user');
  475. Session::erase('_uid');
  476. }
  477. Session::write('is_platformAdmin',$is_platformAdmin);
  478. Session::write('is_allowedCreateCourse',$is_allowedCreateCourse);
  479. } else { // continue with the previous values
  480. $_user = $_SESSION['_user'];
  481. $is_platformAdmin = isset($_SESSION['is_platformAdmin']) ? $_SESSION['is_platformAdmin'] : false;
  482. $is_allowedCreateCourse = isset($_SESSION['is_allowedCreateCourse']) ? $_SESSION['is_allowedCreateCourse'] : false;
  483. }
  484. /* COURSE INIT */
  485. if (isset($cidReset) && $cidReset) {
  486. // Course session data refresh requested or empty data
  487. if ($cidReq) {
  488. $_course = api_get_course_info($cidReq);
  489. if (!empty($_course)) {
  490. //@TODO real_cid should be cid, for working with numeric course id
  491. $_real_cid = $_course['real_id'];
  492. $_cid = $_course['code'];
  493. Session::write('_real_cid', $_real_cid);
  494. Session::write('_cid', $_cid);
  495. Session::write('_course', $_course);
  496. // if a session id has been given in url, we store the session
  497. // Database Table Definitions
  498. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  499. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  500. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  501. if (!empty($_GET['id_session'])) {
  502. $_SESSION['id_session'] = intval($_GET['id_session']);
  503. $sql = 'SELECT name FROM '.$tbl_session . ' WHERE id="'.intval($_SESSION['id_session']) . '"';
  504. $rs = Database::query($sql);
  505. list($_SESSION['session_name']) = Database::fetch_array($rs);
  506. } else {
  507. Session::erase('session_name');
  508. Session::erase('id_session');
  509. }
  510. if (isset($_REQUEST['gidReq'])) {
  511. $_SESSION['_gid'] = intval($_REQUEST['gidReq']);
  512. } else {
  513. Session::erase('_gid');
  514. }
  515. if (!isset($_SESSION['login_as'])) {
  516. //Course login
  517. if (isset($_user['user_id'])) {
  518. event_course_login($_course['code'], $_user['user_id'], api_get_session_id());
  519. }
  520. }
  521. } else {
  522. //exit("WARNING UNDEFINED CID !! ");
  523. header('location:'.api_get_path(WEB_PATH));
  524. }
  525. } else {
  526. Session::erase('_cid');
  527. Session::erase('_real_cid');
  528. Session::erase('_course');
  529. if (!empty($_SESSION)) {
  530. foreach($_SESSION as $key => $session_item) {
  531. if (strpos($key,'lp_autolunch_') === false) {
  532. continue;
  533. } else {
  534. if (isset($_SESSION[$key])) {
  535. Session::erase($key);
  536. }
  537. }
  538. }
  539. }
  540. //Deleting session info
  541. if (api_get_session_id()) {
  542. Session::erase('id_session');
  543. Session::erase('session_name');
  544. }
  545. if (api_get_group_id()) {
  546. Session::erase('_gid');
  547. }
  548. }
  549. } else {
  550. // Continue with the previous values
  551. if (empty($_SESSION['_course']) && !empty($_SESSION['_cid'])) {
  552. //Just in case $_course is empty we try to load if the c_id still exists
  553. $_course = api_get_course_info($_SESSION['_cid']);
  554. if (!empty($_course)) {
  555. $_real_cid = $_course['real_id'];
  556. $_cid = $_course['code'];
  557. Session::write('_real_cid', $_real_cid);
  558. Session::write('_cid', $_cid);
  559. Session::write('_course', $_course);
  560. }
  561. }
  562. if (empty($_SESSION['_course']) OR empty($_SESSION['_cid'])) { //no previous values...
  563. $_cid = -1; //set default values that will be caracteristic of being unset
  564. $_course = -1;
  565. } else {
  566. $_cid = $_SESSION['_cid' ];
  567. $_course = $_SESSION['_course'];
  568. // these lines are usefull for tracking. Indeed we can have lost the id_session and not the cid.
  569. // Moreover, if we want to track a course with another session it can be usefull
  570. if (!empty($_GET['id_session'])) {
  571. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  572. $sql = 'SELECT name FROM '.$tbl_session . ' WHERE id="'.intval($_SESSION['id_session']). '"';
  573. $rs = Database::query($sql);
  574. list($_SESSION['session_name']) = Database::fetch_array($rs);
  575. $_SESSION['id_session'] = intval($_GET['id_session']);
  576. }
  577. if (isset($_REQUEST['gidReq'])) {
  578. $_SESSION['_gid'] = intval($_REQUEST['gidReq']);
  579. $group_table = Database::get_course_table(TABLE_GROUP);
  580. $sql = "SELECT id FROM $group_table WHERE c_id = ".$_course['real_id']." AND id = '$gidReq'";
  581. $result = Database::query($sql);
  582. if (Database::num_rows($result) > 0) {
  583. // This group has recorded status related to this course
  584. $group_info = Database::fetch_array($result);
  585. $_gid = $group_info['id'];
  586. Session::write('_gid', $_gid);
  587. }
  588. }
  589. if (!isset($_SESSION['login_as'])) {
  590. $save_course_access = true;
  591. //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
  592. //Disables the updates in the TRACK_E_COURSE_ACCESS table
  593. if (isset($_dont_save_user_course_access) && $_dont_save_user_course_access == true) {
  594. $save_course_access = false;
  595. }
  596. if ($save_course_access) {
  597. $course_tracking_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  598. /*
  599. * When $_configuration['session_lifetime'] is too big 100 hours (in order to let users take exercises with no problems)
  600. * the function Tracking::get_time_spent_on_the_course() returns big values (200h) due the condition:
  601. * login_course_date > now() - INTERVAL $session_lifetime SECOND
  602. *
  603. */
  604. /*
  605. if (isset($_configuration['session_lifetime'])) {
  606. $session_lifetime = $_configuration['session_lifetime'];
  607. } else {
  608. $session_lifetime = 3600; // 1 hour
  609. }*/
  610. $session_lifetime = 3600; // 1 hour
  611. $course_code = $_course['sysCode'];
  612. $time = api_get_datetime();
  613. if (isset($_user['user_id']) && !empty($_user['user_id'])) {
  614. //We select the last record for the current course in the course tracking table
  615. //But only if the login date is < than now + max_life_time
  616. $sql = "SELECT course_access_id FROM $course_tracking_table
  617. WHERE user_id = ".intval($_user ['user_id'])." AND
  618. course_code = '$course_code' AND
  619. session_id = ".api_get_session_id()." AND
  620. login_course_date > now() - INTERVAL $session_lifetime SECOND
  621. ORDER BY login_course_date DESC LIMIT 0,1";
  622. $result = Database::query($sql);
  623. if (Database::num_rows($result) > 0) {
  624. $i_course_access_id = Database::result($result,0,0);
  625. //We update the course tracking table
  626. $sql = "UPDATE $course_tracking_table SET logout_course_date = '$time', counter = counter+1
  627. WHERE course_access_id = ".intval($i_course_access_id)." AND session_id = ".api_get_session_id();
  628. //error_log($sql);
  629. Database::query($sql);
  630. } else {
  631. $sql="INSERT INTO $course_tracking_table (course_code, user_id, login_course_date, logout_course_date, counter, session_id)" .
  632. "VALUES('".$course_code."', '".$_user['user_id']."', '$time', '$time', '1','".api_get_session_id()."')";
  633. //error_log($sql);
  634. Database::query($sql);
  635. }
  636. }
  637. }
  638. }
  639. }
  640. }
  641. /* COURSE / USER REL. INIT */
  642. $session_id = api_get_session_id();
  643. $user_id = isset($_user['user_id']) ? $_user['user_id'] : null;
  644. //Course permissions
  645. $is_courseAdmin = false; //course teacher
  646. $is_courseTutor = false; //course teacher - some rights
  647. $is_courseMember = false; //course student
  648. $is_courseCoach = false; //course coach
  649. //Course - User permissions
  650. $is_sessionAdmin = false;
  651. if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset)) {
  652. if (isset($_cid) && $_cid) {
  653. $my_user_id = isset($user_id) ? intval($user_id) : 0;
  654. $variable = 'accept_legal_'.$my_user_id.'_'.$_course['real_id'].'_'.$session_id;
  655. $user_pass_open_course = false;
  656. if (api_check_user_access_to_legal($_course['visibility']) && Session::read($variable)) {
  657. $user_pass_open_course = true;
  658. }
  659. //Checking if the user filled the course legal agreement
  660. if ($_course['activate_legal'] == 1 && !api_is_platform_admin()) {
  661. $user_is_subscribed = CourseManager::is_user_accepted_legal($user_id, $_course['id'], $session_id) || $user_pass_open_course;
  662. if (!$user_is_subscribed) {
  663. $url = api_get_path(WEB_CODE_PATH).'course_info/legal.php?course_code='.$_course['code'].'&session_id='.$session_id;
  664. header('Location: '.$url);
  665. exit;
  666. }
  667. }
  668. }
  669. if (isset($user_id) && $user_id && isset($_cid) && $_cid) {
  670. //Check if user is subscribed in a course
  671. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  672. $sql = "SELECT * FROM $course_user_table
  673. WHERE user_id = '".$user_id."' AND relation_type <> ".COURSE_RELATION_TYPE_RRHH."
  674. AND course_code = '$cidReq'";
  675. $result = Database::query($sql);
  676. $cuData = null;
  677. if (Database::num_rows($result) > 0) { // this user have a recorded state for this course
  678. $cuData = Database::fetch_array($result, 'ASSOC');
  679. $is_courseAdmin = (bool) ($cuData['status'] == 1 );
  680. $is_courseTutor = (bool) ($cuData['tutor_id' ] == 1 );
  681. $is_courseMember = true;
  682. $_courseUser['role'] = $cuData['role'];
  683. Session::write('_courseUser',$_courseUser);
  684. }
  685. //We are in a session course? Check session permissions
  686. if (!empty($session_id)) {
  687. //I'm not the teacher of the course
  688. if ($is_courseAdmin == false) {
  689. // this user has no status related to this course
  690. // The user is subscribed in a session? The user is a Session coach a Session admin ?
  691. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  692. $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
  693. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  694. //Session coach, session admin, course coach admin
  695. $sql = "SELECT session.id_coach, session_admin_id, session_rcru.id_user
  696. FROM $tbl_session session, $tbl_session_course_user session_rcru
  697. WHERE session_rcru.id_session = session.id AND
  698. session_rcru.course_code = '$_cid' AND
  699. session_rcru.id_user = '$user_id' AND
  700. session_rcru.id_session = $session_id AND
  701. session_rcru.status = 2
  702. ";
  703. $result = Database::query($sql);
  704. $row = Database::store_result($result);
  705. //I'm a session admin?
  706. if (isset($row) && isset($row[0]) && $row[0]['session_admin_id'] == $user_id) {
  707. $_courseUser['role'] = 'Professor';
  708. $is_courseMember = false;
  709. $is_courseTutor = false;
  710. $is_courseAdmin = false;
  711. $is_courseCoach = false;
  712. $is_sessionAdmin = true;
  713. } else {
  714. //Im a coach or a student?
  715. $sql = "SELECT cu.id_user, cu.status FROM $tbl_session_course_user cu
  716. WHERE course_code = '$_cid' AND
  717. cu.id_user = '".$user_id."' AND
  718. cu.id_session = '".$session_id."'
  719. LIMIT 1";
  720. $result = Database::query($sql);
  721. if (Database::num_rows($result)) {
  722. $row = Database::fetch_array($result, 'ASSOC');
  723. $session_course_status = $row['status'];
  724. switch ($session_course_status) {
  725. case '2': // coach - teacher
  726. $_courseUser['role'] = 'Professor';
  727. $is_courseMember = true;
  728. $is_courseTutor = true;
  729. $is_courseCoach = true;
  730. $is_sessionAdmin = false;
  731. if (api_get_setting('extend_rights_for_coach') == 'true') {
  732. $is_courseAdmin = true;
  733. } else {
  734. $is_courseAdmin = false;
  735. }
  736. Session::write('_courseUser', $_courseUser);
  737. break;
  738. case '0': //Student
  739. $_courseUser['role'] = '';
  740. $is_courseMember = true;
  741. $is_courseTutor = false;
  742. $is_courseAdmin = false;
  743. $is_courseCoach = false;
  744. $is_sessionAdmin = false;
  745. Session::write('_courseUser', $_courseUser);
  746. break;
  747. default:
  748. //unregister user
  749. $_courseUser['role'] = '';
  750. $is_courseMember = false;
  751. $is_courseTutor = false;
  752. $is_courseAdmin = false;
  753. $is_sessionAdmin = false;
  754. $is_courseCoach = false;
  755. Session::erase('_courseUser');
  756. break;
  757. }
  758. } else {
  759. //unregister user
  760. $is_courseMember = false;
  761. $is_courseTutor = false;
  762. $is_courseAdmin = false;
  763. $is_sessionAdmin = false;
  764. $is_courseCoach = false;
  765. Session::erase('_courseUser');
  766. }
  767. }
  768. }
  769. //If I'm the admin platform i'm a teacher of the course
  770. if ($is_platformAdmin) {
  771. $is_courseAdmin = true;
  772. }
  773. }
  774. } else { // keys missing => not anymore in the course - user relation
  775. // course
  776. $is_courseMember = false;
  777. $is_courseAdmin = false;
  778. $is_courseTutor = false;
  779. $is_courseCoach = false;
  780. $is_sessionAdmin = false;
  781. Session::erase('_courseUser');
  782. }
  783. //Checking the course access
  784. $is_allowed_in_course = false;
  785. if (isset($_course)) {
  786. switch ($_course['visibility']) {
  787. case COURSE_VISIBILITY_OPEN_WORLD: //3
  788. $is_allowed_in_course = true;
  789. break;
  790. case COURSE_VISIBILITY_OPEN_PLATFORM : //2
  791. if (isset($user_id) && !api_is_anonymous($user_id)) {
  792. $is_allowed_in_course = true;
  793. }
  794. break;
  795. case COURSE_VISIBILITY_REGISTERED: //1
  796. if ($is_platformAdmin || $is_courseMember) {
  797. $is_allowed_in_course = true;
  798. }
  799. break;
  800. case COURSE_VISIBILITY_CLOSED: //0
  801. if ($is_platformAdmin || $is_courseAdmin) {
  802. $is_allowed_in_course = true;
  803. }
  804. break;
  805. }
  806. }
  807. if (!$is_platformAdmin) {
  808. if (!$is_courseMember && isset($_course['registration_code']) && !empty($_course['registration_code'])) {
  809. $is_courseMember = false;
  810. $is_courseAdmin = false;
  811. $is_courseTutor = false;
  812. $is_courseCoach = false;
  813. $is_sessionAdmin = false;
  814. $is_allowed_in_course = false;
  815. }
  816. }
  817. // check the session visibility
  818. if ($is_allowed_in_course == true) {
  819. //if I'm in a session
  820. if ($session_id != 0) {
  821. if (!$is_platformAdmin) {
  822. // admin is not affected to the invisible session mode
  823. $session_visibility = api_get_session_visibility($session_id);
  824. switch ($session_visibility) {
  825. case SESSION_INVISIBLE:
  826. $is_allowed_in_course = false;
  827. break;
  828. }
  829. //checking date
  830. }
  831. }
  832. }
  833. // save the states
  834. Session::write('is_courseAdmin', $is_courseAdmin);
  835. Session::write('is_courseMember', $is_courseMember);
  836. Session::write('is_courseTutor', $is_courseTutor);
  837. Session::write('is_courseCoach', $is_courseCoach);
  838. Session::write('is_allowed_in_course', $is_allowed_in_course);
  839. Session::write('is_sessionAdmin', $is_sessionAdmin);
  840. } else { // continue with the previous values
  841. if (isset($_SESSION['_courseUser'])) {
  842. $_courseUser = $_SESSION ['_courseUser'];
  843. }
  844. $is_courseAdmin = isset($_SESSION ['is_courseAdmin']) ? $_SESSION ['is_courseAdmin'] : false;
  845. $is_courseTutor = isset($_SESSION ['is_courseTutor']) ? $_SESSION ['is_courseTutor'] : false;
  846. $is_courseCoach = isset($_SESSION ['is_courseCoach']) ? $_SESSION ['is_courseCoach'] : false;
  847. $is_courseMember = isset($_SESSION ['is_courseMember']) ? $_SESSION ['is_courseMember'] : false;
  848. $is_allowed_in_course = isset($_SESSION ['is_allowed_in_course']) ? $_SESSION ['is_allowed_in_course'] : false;
  849. }
  850. //set variable according to student_view_enabled choices
  851. if (api_get_setting('student_view_enabled') == "true") {
  852. if (isset($_GET['isStudentView'])) {
  853. if ($_GET['isStudentView'] == 'true') {
  854. if (isset($_SESSION['studentview'])) {
  855. if (!empty($_SESSION['studentview'])) {
  856. // switching to studentview
  857. $_SESSION['studentview'] = 'studentview';
  858. }
  859. }
  860. } elseif ($_GET['isStudentView'] == 'false') {
  861. if (isset($_SESSION['studentview'])) {
  862. if (!empty($_SESSION['studentview'])) {
  863. // switching to teacherview
  864. $_SESSION['studentview'] = 'teacherview';
  865. }
  866. }
  867. }
  868. } elseif (!empty($_SESSION['studentview'])) {
  869. //all is fine, no change to that, obviously
  870. } elseif (empty($_SESSION['studentview'])) {
  871. // We are in teacherview here
  872. $_SESSION['studentview'] = 'teacherview';
  873. }
  874. }
  875. if (isset($_cid)) {
  876. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  877. $time = api_get_utc_datetime();
  878. $sql="UPDATE $tbl_course SET last_visit= '$time' WHERE code='$_cid'";
  879. Database::query($sql);
  880. }
  881. Redirect::session_request_uri($logging_in, $user_id);