local.inc.php 50 KB

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