local.inc.php 50 KB

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