local.inc.php 45 KB

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