local.inc.php 49 KB

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