local.inc.php 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. *
  5. * SCRIPT PURPOSE
  6. *
  7. * This script initializes and manages Chamilo session information. It
  8. * keeps available session information up to date.
  9. *
  10. * You can request a course id. It will check if the course Id requested is the
  11. * same as the current one. If it isn't it will update session information from
  12. * the database. You can also force the course reset if you want ($cidReset).
  13. *
  14. * All the course information is stored in the $_course array.
  15. *
  16. * You can request a group id. The script will check if the group id requested is the
  17. * same as the current one. If it isn't it will update session information from
  18. * the database. You can also force the course reset if you want ($gidReset).
  19. *
  20. * The course id is stored in $_cid session variable.
  21. * The group id is stored in $_gid session variable.
  22. *
  23. *
  24. * VARIABLES AFFECTING THE SCRIPT BEHAVIOR
  25. *
  26. * string $login
  27. * string $password
  28. * boolean $logout
  29. *
  30. * string $cidReq : course id requested
  31. * boolean $cidReset : ask for a course Reset, if no $cidReq is provided in the
  32. * same time, all course informations is removed from the
  33. * current session
  34. *
  35. * int $gidReq : group Id requested
  36. * boolean $gidReset : ask for a group Reset, if no $gidReq is provided in the
  37. * same time, all group informations is removed from the
  38. * current session
  39. *
  40. *
  41. * VARIABLES SET AND RETURNED BY THE SCRIPT
  42. *
  43. * All the variables below are set and returned by this script.
  44. *
  45. * USER VARIABLES
  46. *
  47. * string $_user ['firstName' ]
  48. * string $_user ['lastName' ]
  49. * string $_user ['mail' ]
  50. * string $_user ['lastLogin' ]
  51. * string $_user ['official_code']
  52. * string $_user ['picture_uri' ]
  53. * string $_user['user_id']
  54. *
  55. * boolean $is_platformAdmin
  56. * boolean $is_allowedCreateCourse
  57. *
  58. * COURSE VARIABLES
  59. * see the function get_course_info_with_category
  60. * boolean $is_courseMember
  61. * boolean $is_courseTutor
  62. * boolean $is_courseAdmin
  63. *
  64. *
  65. * GROUP VARIABLES
  66. *
  67. * int $_gid (the group id)
  68. *
  69. *
  70. * IMPORTANT ADVICE FOR DEVELOPERS
  71. *
  72. * We strongly encourage developers to use a connection layer at the top of
  73. * their scripts rather than use these variables, as they are, inside the core
  74. * of their scripts. It will make code maintenance much easier.
  75. *
  76. * Many if the functions you need you can already find in the
  77. * main_api.lib.php
  78. *
  79. * We encourage you to use functions to access these global "kernel" variables.
  80. * You can add them to e.g. the main API library.
  81. *
  82. *
  83. * SCRIPT STRUCTURE
  84. *
  85. * 1. The script determines if there is an authentication attempt. This part
  86. * only chek if the login name and password are valid. Afterwards, it set the
  87. * $_user['user_id'] (user id) and the $uidReset flag. Other user informations are retrieved
  88. * later. It's also in this section that optional external authentication
  89. * devices step in.
  90. *
  91. * 2. The script determines what other session informations have to be set or
  92. * reset, setting correctly $cidReset (for course) and $gidReset (for group).
  93. *
  94. * 3. If needed, the script retrieves the other user informations (first name,
  95. * last name, ...) and stores them in session.
  96. *
  97. * 4. If needed, the script retrieves the course information and stores them
  98. * in session
  99. *
  100. * 5. The script initializes the user permission status and permission for the
  101. * course level
  102. *
  103. * 6. If needed, the script retrieves group informations an store them in
  104. * session.
  105. *
  106. * 7. The script initializes the user status and permission for the group level.
  107. *
  108. * @package chamilo.include
  109. */
  110. /*
  111. INIT SECTION
  112. variables should be initialised here
  113. */
  114. //require_once api_get_path(LIBRARY_PATH).'conditionallogin.lib.php'; moved to autologin
  115. // verified if exists the username and password in session current
  116. use \ChamiloSession as Session;
  117. //Conditional login
  118. if (isset($_SESSION['conditional_login']['uid']) && $_SESSION['conditional_login']['can_login']=== true){
  119. $uData = UserManager::get_user_info_by_id($_SESSION['conditional_login']['uid']);
  120. ConditionalLogin::check_conditions($uData);
  121. $_user['user_id'] = $_SESSION['conditional_login']['uid'];
  122. $_user['status'] = $uData['status'];
  123. Session::write('_user',$_user);
  124. Session::erase('conditional_login');
  125. $uidReset=true;
  126. event_login();
  127. }
  128. // parameters passed via GET
  129. $logout = isset($_GET["logout"]) ? $_GET["logout"] : '';
  130. $gidReq = isset($_GET["gidReq"]) ? Database::escape_string($_GET["gidReq"]) : '';
  131. //this fixes some problems with generic functionalities like
  132. //My Agenda & What's New icons linking to courses
  133. // $cidReq can be set in the index.php file of a course-area
  134. $cidReq = isset($cidReq) ? Database::escape_string($cidReq) : '';
  135. // $cidReq can be set in URL-parameter
  136. $cidReq = isset($_GET["cidReq"]) ? Database::escape_string($_GET["cidReq"]) : $cidReq;
  137. $cidReset = isset($cidReset) ? Database::escape_string($cidReset) : '';
  138. // $cidReset can be set in URL-parameter
  139. $cidReset = (isset($_GET['cidReq']) && ((isset($_SESSION['_cid']) && $_GET['cidReq']!=$_SESSION['_cid']) || (!isset($_SESSION['_cid'])))) ? Database::escape_string($_GET["cidReq"]) : $cidReset;
  140. // $cDir is a special url param sent by courses/.htaccess
  141. $cDir = (!empty($_GET['cDir']) ? $_GET['cDir'] : null);
  142. $gidReset = isset($gidReset) ? $gidReset : '';
  143. // $gidReset can be set in URL-parameter
  144. // parameters passed via POST
  145. $login = isset($_POST["login"]) ? $_POST["login"] : '';
  146. // 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. $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. $c = CourseManager::get_course_id_from_path($cDir);
  519. if ($c) { $cidReq = $c; }
  520. }
  521. // if the requested course is different from the course in session
  522. if (!empty($cidReq) && (!isset($_SESSION['_cid']) or (isset($_SESSION['_cid']) && $cidReq != $_SESSION['_cid']))) {
  523. $cidReset = true;
  524. $gidReset = true; // As groups depend from courses, group id is reset
  525. }
  526. /* USER INIT */
  527. if (isset($uidReset) && $uidReset) { // session data refresh requested
  528. unset($_SESSION['_user']['uidReset']);
  529. $is_platformAdmin = false;
  530. $is_allowedCreateCourse = false;
  531. if (isset($_user['user_id']) && $_user['user_id'] && ! api_is_anonymous()) {
  532. // a uid is given (log in succeeded)
  533. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  534. $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
  535. $track_e_login = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  536. $sql = "SELECT user.*, a.user_id is_admin, login.login_date
  537. FROM $user_table
  538. LEFT JOIN $admin_table a
  539. ON user.user_id = a.user_id
  540. LEFT JOIN $track_e_login login
  541. ON user.user_id = login.login_user_id
  542. WHERE user.user_id = '".$_user['user_id']."'
  543. ORDER BY login.login_date DESC LIMIT 1";
  544. $result = Database::query($sql);
  545. if (Database::num_rows($result) > 0) {
  546. // Extracting the user data
  547. $uData = Database::fetch_array($result);
  548. $_user = _api_format_user($uData, false);
  549. $_user['lastLogin'] = api_strtotime($uData['login_date'], 'UTC');
  550. $is_platformAdmin = (bool) (! is_null( $uData['is_admin']));
  551. $is_allowedCreateCourse = (bool) (($uData ['status'] == COURSEMANAGER) or (api_get_setting('drhCourseManagerRights') and $uData['status'] == DRH));
  552. ConditionalLogin::check_conditions($uData);
  553. Session::write('_user',$_user);
  554. UserManager::update_extra_field_value($_user['user_id'], 'already_logged_in', 'true');
  555. Session::write('is_platformAdmin', $is_platformAdmin);
  556. Session::write('is_allowedCreateCourse',$is_allowedCreateCourse);
  557. } else {
  558. header('location:'.api_get_path(WEB_PATH));
  559. //exit("WARNING UNDEFINED UID !! ");
  560. }
  561. } else { // no uid => logout or Anonymous
  562. Session::erase('_user');
  563. Session::erase('_uid');
  564. }
  565. Session::write('is_platformAdmin',$is_platformAdmin);
  566. Session::write('is_allowedCreateCourse',$is_allowedCreateCourse);
  567. } else { // continue with the previous values
  568. $_user = $_SESSION['_user'];
  569. $is_platformAdmin = isset($_SESSION['is_platformAdmin']) ? $_SESSION['is_platformAdmin'] : false;
  570. $is_allowedCreateCourse = isset($_SESSION['is_allowedCreateCourse']) ? $_SESSION['is_allowedCreateCourse'] : false;
  571. }
  572. /* COURSE INIT */
  573. if (isset($cidReset) && $cidReset) {
  574. // Course session data refresh requested or empty data
  575. if ($cidReq) {
  576. $_course = api_get_course_info($cidReq);
  577. if (!empty($_course)) {
  578. //@TODO real_cid should be cid, for working with numeric course id
  579. $_real_cid = $_course['real_id'];
  580. $_cid = $_course['code'];
  581. Session::write('_real_cid', $_real_cid);
  582. Session::write('_cid', $_cid);
  583. Session::write('_course', $_course);
  584. // if a session id has been given in url, we store the session
  585. // Database Table Definitions
  586. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  587. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  588. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  589. if (!empty($_GET['id_session'])) {
  590. $_SESSION['id_session'] = intval($_GET['id_session']);
  591. $sql = 'SELECT name FROM '.$tbl_session . ' WHERE id="'.intval($_SESSION['id_session']) . '"';
  592. $rs = Database::query($sql);
  593. list($_SESSION['session_name']) = Database::fetch_array($rs);
  594. } else {
  595. Session::erase('session_name');
  596. Session::erase('id_session');
  597. }
  598. if (!empty($_GET['gidReq'])) {
  599. $_SESSION['_gid'] = intval($_GET['gidReq']);
  600. } else {
  601. Session::erase('_gid');
  602. }
  603. if (!isset($_SESSION['login_as'])) {
  604. //Course login
  605. if (isset($_user['user_id'])) {
  606. event_course_login($_course['code'], $_user['user_id'], api_get_session_id());
  607. }
  608. }
  609. } else {
  610. //exit("WARNING UNDEFINED CID !! ");
  611. header('location:'.api_get_path(WEB_PATH));
  612. }
  613. } else {
  614. Session::erase('_cid');
  615. Session::erase('_real_cid');
  616. Session::erase('_course');
  617. if (!empty($_SESSION)) {
  618. foreach($_SESSION as $key => $session_item) {
  619. if (strpos($key,'lp_autolunch_') === false) {
  620. continue;
  621. } else {
  622. if (isset($_SESSION[$key])) {
  623. Session::erase($key);
  624. }
  625. }
  626. }
  627. }
  628. //Deleting session info
  629. if (api_get_session_id()) {
  630. Session::erase('id_session');
  631. Session::erase('session_name');
  632. }
  633. if (api_get_group_id()) {
  634. Session::erase('_gid');
  635. }
  636. }
  637. } else {
  638. // Continue with the previous values
  639. if (empty($_SESSION['_course']) && !empty($_SESSION['_cid'])) {
  640. //Just in case $_course is empty we try to load if the c_id still exists
  641. $_course = api_get_course_info($_SESSION['_cid']);
  642. if (!empty($_course)) {
  643. $_real_cid = $_course['real_id'];
  644. $_cid = $_course['code'];
  645. Session::write('_real_cid', $_real_cid);
  646. Session::write('_cid', $_cid);
  647. Session::write('_course', $_course);
  648. }
  649. }
  650. if (empty($_SESSION['_course']) OR empty($_SESSION['_cid'])) { //no previous values...
  651. $_cid = -1; //set default values that will be caracteristic of being unset
  652. $_course = -1;
  653. } else {
  654. $_cid = $_SESSION['_cid' ];
  655. $_course = $_SESSION['_course'];
  656. // these lines are usefull for tracking. Indeed we can have lost the id_session and not the cid.
  657. // Moreover, if we want to track a course with another session it can be usefull
  658. if (!empty($_GET['id_session'])) {
  659. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  660. $sql = 'SELECT name FROM '.$tbl_session . ' WHERE id="'.intval($_SESSION['id_session']). '"';
  661. $rs = Database::query($sql);
  662. list($_SESSION['session_name']) = Database::fetch_array($rs);
  663. $_SESSION['id_session'] = intval($_GET['id_session']);
  664. }
  665. if (!empty($_REQUEST['gidReq'])) {
  666. $_SESSION['_gid'] = intval($_REQUEST['gidReq']);
  667. $group_table = Database::get_course_table(TABLE_GROUP);
  668. $sql = "SELECT * FROM $group_table WHERE c_id = ".$_course['real_id']." AND id = '$gidReq'";
  669. $result = Database::query($sql);
  670. if (Database::num_rows($result) > 0) { // This group has recorded status related to this course
  671. $gpData = Database::fetch_array($result);
  672. $_gid = $gpData ['id'];
  673. Session::write('_gid', $_gid);
  674. }
  675. }
  676. if (!isset($_SESSION['login_as'])) {
  677. $save_course_access = true;
  678. //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
  679. //Disables the updates in the TRACK_E_COURSE_ACCESS table
  680. if (isset($_dont_save_user_course_access) && $_dont_save_user_course_access == true) {
  681. $save_course_access = false;
  682. }
  683. if ($save_course_access) {
  684. $course_tracking_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  685. /*
  686. * When $_configuration['session_lifetime'] is too big 100 hours (in order to let users take exercises with no problems)
  687. * the function Tracking::get_time_spent_on_the_course() returns big values (200h) due the condition:
  688. * login_course_date > now() - INTERVAL $session_lifetime SECOND
  689. *
  690. */
  691. /*
  692. if (isset($_configuration['session_lifetime'])) {
  693. $session_lifetime = $_configuration['session_lifetime'];
  694. } else {
  695. $session_lifetime = 3600; // 1 hour
  696. }*/
  697. $session_lifetime = 3600; // 1 hour
  698. $course_code = $_course['sysCode'];
  699. $time = api_get_datetime();
  700. if (isset($_user['user_id']) && !empty($_user['user_id'])) {
  701. //We select the last record for the current course in the course tracking table
  702. //But only if the login date is < than now + max_life_time
  703. $sql = "SELECT course_access_id FROM $course_tracking_table
  704. WHERE user_id = ".intval($_user ['user_id'])." AND
  705. course_code = '$course_code' AND
  706. session_id = ".api_get_session_id()." AND
  707. login_course_date > now() - INTERVAL $session_lifetime SECOND
  708. ORDER BY login_course_date DESC LIMIT 0,1";
  709. $result = Database::query($sql);
  710. if (Database::num_rows($result) > 0) {
  711. $i_course_access_id = Database::result($result,0,0);
  712. //We update the course tracking table
  713. $sql = "UPDATE $course_tracking_table SET logout_course_date = '$time', counter = counter+1
  714. WHERE course_access_id = ".intval($i_course_access_id)." AND session_id = ".api_get_session_id();
  715. //error_log($sql);
  716. Database::query($sql);
  717. } else {
  718. $sql="INSERT INTO $course_tracking_table (course_code, user_id, login_course_date, logout_course_date, counter, session_id)" .
  719. "VALUES('".$course_code."', '".$_user['user_id']."', '$time', '$time', '1','".api_get_session_id()."')";
  720. //error_log($sql);
  721. Database::query($sql);
  722. }
  723. }
  724. }
  725. }
  726. }
  727. }
  728. /* COURSE / USER REL. INIT */
  729. $session_id = api_get_session_id();
  730. $user_id = isset($_user['user_id']) ? $_user['user_id'] : null;
  731. //Course permissions
  732. $is_courseAdmin = false; //course teacher
  733. $is_courseTutor = false; //course teacher - some rights
  734. $is_courseMember = false; //course student
  735. $is_courseCoach = false; //course coach
  736. //Course - User permissions
  737. $is_sessionAdmin = false;
  738. if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset)) {
  739. if (isset($_cid) && $_cid) {
  740. $my_user_id = isset($user_id) ? intval($user_id) : 0;
  741. $variable = 'accept_legal_'.$my_user_id.'_'.$_course['real_id'].'_'.$session_id;
  742. $user_pass_open_course = false;
  743. if (api_check_user_access_to_legal($_course['visibility']) && Session::read($variable)) {
  744. $user_pass_open_course = true;
  745. }
  746. //Checking if the user filled the course legal agreement
  747. if ($_course['activate_legal'] == 1 && !api_is_platform_admin()) {
  748. $user_is_subscribed = CourseManager::is_user_accepted_legal($user_id, $_course['id'], $session_id) || $user_pass_open_course;
  749. if (!$user_is_subscribed) {
  750. $url = api_get_path(WEB_CODE_PATH).'course_info/legal.php?course_code='.$_course['code'].'&session_id='.$session_id;
  751. header('Location: '.$url);
  752. exit;
  753. }
  754. }
  755. }
  756. if (isset($user_id) && $user_id && isset($_cid) && $_cid) {
  757. //Check if user is subscribed in a course
  758. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  759. $sql = "SELECT * FROM $course_user_table
  760. WHERE user_id = '".$user_id."' AND relation_type <> ".COURSE_RELATION_TYPE_RRHH."
  761. AND course_code = '$cidReq'";
  762. $result = Database::query($sql);
  763. $cuData = null;
  764. if (Database::num_rows($result) > 0) { // this user have a recorded state for this course
  765. $cuData = Database::fetch_array($result, 'ASSOC');
  766. $is_courseAdmin = (bool) ($cuData['status'] == 1 );
  767. $is_courseTutor = (bool) ($cuData['tutor_id' ] == 1 );
  768. $is_courseMember = true;
  769. $_courseUser['role'] = $cuData['role'];
  770. Session::write('_courseUser',$_courseUser);
  771. }
  772. //We are in a session course? Check session permissions
  773. if (!empty($session_id)) {
  774. //I'm not the teacher of the course
  775. if ($is_courseAdmin == false) {
  776. // this user has no status related to this course
  777. // The user is subscribed in a session? The user is a Session coach a Session admin ?
  778. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  779. $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
  780. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  781. //Session coach, session admin, course coach admin
  782. $sql = "SELECT session.id_coach, session_admin_id, session_rcru.id_user
  783. FROM $tbl_session session, $tbl_session_course_user session_rcru
  784. WHERE session_rcru.id_session = session.id AND
  785. session_rcru.course_code = '$_cid' AND
  786. session_rcru.id_user = '$user_id' AND
  787. session_rcru.id_session = $session_id AND
  788. session_rcru.status = 2
  789. ";
  790. $result = Database::query($sql);
  791. $row = Database::store_result($result);
  792. //I'm a session admin?
  793. if (isset($row) && isset($row[0]) && $row[0]['session_admin_id'] == $user_id) {
  794. $_courseUser['role'] = 'Professor';
  795. $is_courseMember = false;
  796. $is_courseTutor = false;
  797. $is_courseAdmin = false;
  798. $is_courseCoach = false;
  799. $is_sessionAdmin = true;
  800. } else {
  801. //Im a coach or a student?
  802. $sql = "SELECT cu.id_user, cu.status FROM $tbl_session_course_user cu
  803. WHERE course_code = '$_cid' AND
  804. cu.id_user = '".$user_id."' AND
  805. cu.id_session = '".$session_id."'
  806. LIMIT 1";
  807. $result = Database::query($sql);
  808. if (Database::num_rows($result)) {
  809. $row = Database::fetch_array($result, 'ASSOC');
  810. $session_course_status = $row['status'];
  811. switch ($session_course_status) {
  812. case '2': // coach - teacher
  813. $_courseUser['role'] = 'Professor';
  814. $is_courseMember = true;
  815. $is_courseTutor = true;
  816. $is_courseCoach = true;
  817. $is_sessionAdmin = false;
  818. if (api_get_setting('extend_rights_for_coach') == 'true') {
  819. $is_courseAdmin = true;
  820. } else {
  821. $is_courseAdmin = false;
  822. }
  823. Session::write('_courseUser', $_courseUser);
  824. break;
  825. case '0': //Student
  826. $_courseUser['role'] = '';
  827. $is_courseMember = true;
  828. $is_courseTutor = false;
  829. $is_courseAdmin = false;
  830. $is_courseCoach = false;
  831. $is_sessionAdmin = false;
  832. Session::write('_courseUser', $_courseUser);
  833. break;
  834. default:
  835. //unregister user
  836. $_courseUser['role'] = '';
  837. $is_courseMember = false;
  838. $is_courseTutor = false;
  839. $is_courseAdmin = false;
  840. $is_sessionAdmin = false;
  841. $is_courseCoach = false;
  842. Session::erase('_courseUser');
  843. break;
  844. }
  845. } else {
  846. //unregister user
  847. $is_courseMember = false;
  848. $is_courseTutor = false;
  849. $is_courseAdmin = false;
  850. $is_sessionAdmin = false;
  851. $is_courseCoach = false;
  852. Session::erase('_courseUser');
  853. }
  854. }
  855. }
  856. //If I'm the admin platform i'm a teacher of the course
  857. if ($is_platformAdmin) {
  858. $is_courseAdmin = true;
  859. }
  860. }
  861. } else { // keys missing => not anymore in the course - user relation
  862. // course
  863. $is_courseMember = false;
  864. $is_courseAdmin = false;
  865. $is_courseTutor = false;
  866. $is_courseCoach = false;
  867. $is_sessionAdmin = false;
  868. Session::erase('_courseUser');
  869. }
  870. //Checking the course access
  871. $is_allowed_in_course = false;
  872. if (isset($_course) && isset($_course['visibility'])) {
  873. switch ($_course['visibility']) {
  874. case COURSE_VISIBILITY_OPEN_WORLD: //3
  875. $is_allowed_in_course = true;
  876. break;
  877. case COURSE_VISIBILITY_OPEN_PLATFORM : //2
  878. if (isset($user_id) && !api_is_anonymous($user_id)) {
  879. $is_allowed_in_course = true;
  880. }
  881. break;
  882. case COURSE_VISIBILITY_REGISTERED: //1
  883. if ($is_platformAdmin || $is_courseMember) {
  884. $is_allowed_in_course = true;
  885. }
  886. break;
  887. case COURSE_VISIBILITY_CLOSED: //0
  888. if ($is_platformAdmin || $is_courseAdmin) {
  889. $is_allowed_in_course = true;
  890. }
  891. break;
  892. }
  893. }
  894. if (!$is_platformAdmin) {
  895. if (!$is_courseMember && isset($_course['registration_code']) && !empty($_course['registration_code'])) {
  896. $is_courseMember = false;
  897. $is_courseAdmin = false;
  898. $is_courseTutor = false;
  899. $is_courseCoach = false;
  900. $is_sessionAdmin = false;
  901. $is_allowed_in_course = false;
  902. }
  903. }
  904. // check the session visibility
  905. if ($is_allowed_in_course == true) {
  906. //if I'm in a session
  907. if ($session_id != 0) {
  908. if (!$is_platformAdmin) {
  909. // admin is not affected to the invisible session mode
  910. $session_visibility = api_get_session_visibility($session_id);
  911. switch ($session_visibility) {
  912. case SESSION_INVISIBLE:
  913. $is_allowed_in_course = false;
  914. break;
  915. }
  916. //checking date
  917. }
  918. }
  919. }
  920. // save the states
  921. Session::write('is_courseAdmin', $is_courseAdmin);
  922. Session::write('is_courseMember', $is_courseMember);
  923. Session::write('is_courseTutor', $is_courseTutor);
  924. Session::write('is_courseCoach', $is_courseCoach);
  925. Session::write('is_allowed_in_course', $is_allowed_in_course);
  926. Session::write('is_sessionAdmin', $is_sessionAdmin);
  927. } else { // continue with the previous values
  928. if (isset($_SESSION['_courseUser'])) {
  929. $_courseUser = $_SESSION ['_courseUser'];
  930. }
  931. $is_courseAdmin = isset($_SESSION ['is_courseAdmin']) ? $_SESSION ['is_courseAdmin'] : false;
  932. $is_courseTutor = isset($_SESSION ['is_courseTutor']) ? $_SESSION ['is_courseTutor'] : false;
  933. $is_courseCoach = isset($_SESSION ['is_courseCoach']) ? $_SESSION ['is_courseCoach'] : false;
  934. $is_courseMember = isset($_SESSION ['is_courseMember']) ? $_SESSION ['is_courseMember'] : false;
  935. $is_allowed_in_course = isset($_SESSION ['is_allowed_in_course']) ? $_SESSION ['is_allowed_in_course'] : false;
  936. }
  937. //set variable according to student_view_enabled choices
  938. if (api_get_setting('student_view_enabled') == "true") {
  939. if (isset($_GET['isStudentView'])) {
  940. if ($_GET['isStudentView'] == 'true') {
  941. if (isset($_SESSION['studentview'])) {
  942. if (!empty($_SESSION['studentview'])) {
  943. // switching to studentview
  944. $_SESSION['studentview'] = 'studentview';
  945. }
  946. }
  947. } elseif ($_GET['isStudentView'] == 'false') {
  948. if (isset($_SESSION['studentview'])) {
  949. if (!empty($_SESSION['studentview'])) {
  950. // switching to teacherview
  951. $_SESSION['studentview'] = 'teacherview';
  952. }
  953. }
  954. }
  955. } elseif (!empty($_SESSION['studentview'])) {
  956. //all is fine, no change to that, obviously
  957. } elseif (empty($_SESSION['studentview'])) {
  958. // We are in teacherview here
  959. $_SESSION['studentview'] = 'teacherview';
  960. }
  961. }
  962. if (isset($_cid)) {
  963. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  964. $time = api_get_utc_datetime();
  965. $sql="UPDATE $tbl_course SET last_visit= '$time' WHERE code='$_cid'";
  966. Database::query($sql);
  967. }
  968. Redirect::session_request_uri($logging_in, $user_id);