local.inc.php 45 KB

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