local.inc.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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 = '".trim(addslashes($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 = '".trim(addslashes($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. if (isset($_GET['sso_referer']) ? $_GET['sso_referer'] === $master['protocol']. $master_url : FALSE) {
  422. //make all the process of checking
  423. //if the user exists (delegated to the sso class)
  424. $osso->check_user();
  425. } else {
  426. //Request comes from unknown source
  427. $loginFailed = true;
  428. api_session_unregister('_uid');
  429. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=unrecognize_sso_origin');
  430. exit;
  431. }
  432. }
  433. }//end logout
  434. } elseif (api_get_setting('openid_authentication')=='true') {
  435. if (!empty($_POST['openid_url'])) {
  436. include('main/auth/openid/login.php');
  437. openid_begin(trim($_POST['openid_url']),api_get_path(WEB_PATH).'index.php');
  438. //this last function should trigger a redirect, so we can die here safely
  439. die('Openid login redirection should be in progress');
  440. } elseif (!empty($_GET['openid_identity'])) {
  441. //it's usual for PHP to replace '.' (dot) by '_' (underscore) in URL parameters
  442. include('main/auth/openid/login.php');
  443. $res = openid_complete($_GET);
  444. if ($res['status'] == 'success') {
  445. $id1 = Database::escape_string($res['openid.identity']);
  446. //have another id with or without the final '/'
  447. $id2 = (substr($id1,-1,1)=='/'?substr($id1,0,-1):$id1.'/');
  448. //lookup the user in the main database
  449. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  450. $sql = "SELECT user_id, username, password, auth_source, active, expiration_date
  451. FROM $user_table
  452. WHERE openid = '$id1'
  453. OR openid = '$id2' ";
  454. $result = Database::query($sql);
  455. if ($result !== false) {
  456. if (Database::num_rows($result)>0) {
  457. //$row = Database::fetch_array($res);
  458. $uData = Database::fetch_array($result);
  459. if ($uData['auth_source'] == PLATFORM_AUTH_SOURCE) {
  460. //the authentification of this user is managed by Chamilo itself
  461. // check if the account is active (not locked)
  462. if ($uData['active']=='1') {
  463. // check if the expiration date has not been reached
  464. if ($uData['expiration_date']>date('Y-m-d H:i:s') OR $uData['expiration_date']=='0000-00-00 00:00:00') {
  465. $_user['user_id'] = $uData['user_id'];
  466. api_session_register('_user');
  467. event_login();
  468. } else {
  469. $loginFailed = true;
  470. api_session_unregister('_uid');
  471. header('Location: index.php?loginFailed=1&error=account_expired');
  472. exit;
  473. }
  474. } else {
  475. $loginFailed = true;
  476. api_session_unregister('_uid');
  477. header('Location: index.php?loginFailed=1&error=account_inactive');
  478. exit;
  479. }
  480. if (isset($uData['creator_id']) && $_user['user_id'] != $uData['creator_id']) {
  481. //first login for a not self registred
  482. //e.g. registered by a teacher
  483. //do nothing (code may be added later)
  484. }
  485. }
  486. } else {
  487. //Redirect to the subscription form
  488. 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');
  489. //$loginFailed = true;
  490. }
  491. } else {
  492. $loginFailed = true;
  493. }
  494. } else {
  495. $loginFailed = true;
  496. }
  497. }
  498. }
  499. // else {} => continue as anonymous user
  500. $uidReset = true;
  501. // $cidReset = true;
  502. // $gidReset = true;
  503. } // end else
  504. //Now check for anonymous user mode
  505. if ($use_anonymous) {
  506. //if anonymous mode is set, then try to set the current user as anonymous
  507. //if he doesn't have a login yet
  508. api_set_anonymous();
  509. } else {
  510. //if anonymous mode is not set, then check if this user is anonymous. If it
  511. //is, clean it from being anonymous (make him a nobody :-))
  512. api_clear_anonymous();
  513. }
  514. // if there is a cDir parameter in the URL (coming from courses/.htaccess redirection)
  515. if (!empty($cDir)) {
  516. require_once api_get_path(LIBRARY_PATH).'course.lib.php';
  517. $c = CourseManager::get_course_id_from_path($cDir);
  518. if ($c) { $cidReq = $c; }
  519. }
  520. // if the requested course is different from the course in session
  521. if (!empty($cidReq) && (!isset($_SESSION['_cid']) or (isset($_SESSION['_cid']) && $cidReq != $_SESSION['_cid']))) {
  522. $cidReset = true;
  523. $gidReset = true; // As groups depend from courses, group id is reset
  524. }
  525. // if the requested group is different from the group in session
  526. $gid = isset($_SESSION['_gid'])?$_SESSION['_gid']:'';
  527. if ($gidReq && $gidReq != $gid) {
  528. $gidReset = true;
  529. }
  530. /* USER INIT */
  531. if (isset($uidReset) && $uidReset) { // session data refresh requested
  532. $is_platformAdmin = false; $is_allowedCreateCourse = false;
  533. if (isset($_user['user_id']) && $_user['user_id']) // a uid is given (log in succeeded)
  534. {
  535. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  536. $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
  537. if ($_configuration['tracking_enabled']) {
  538. $sql = "SELECT user.*, a.user_id is_admin, UNIX_TIMESTAMP(login.login_date) login_date
  539. FROM $user_table
  540. LEFT JOIN $admin_table a
  541. ON user.user_id = a.user_id
  542. LEFT JOIN ".$_configuration['statistics_database'].".track_e_login login
  543. ON user.user_id = login.login_user_id
  544. WHERE user.user_id = '".$_user['user_id']."'
  545. ORDER BY login.login_date DESC LIMIT 1";
  546. } else {
  547. $sql = "SELECT user.*, a.user_id is_admin
  548. FROM $user_table
  549. LEFT JOIN $admin_table a
  550. ON user.user_id = a.user_id
  551. WHERE user.user_id = '".$_user['user_id']."'";
  552. }
  553. $result = Database::query($sql);
  554. if (Database::num_rows($result) > 0) {
  555. // Extracting the user data
  556. $uData = Database::fetch_array($result);
  557. $_user ['firstName'] = $uData ['firstname' ];
  558. $_user ['lastName' ] = $uData ['lastname' ];
  559. $_user ['mail' ] = $uData ['email' ];
  560. $_user ['lastLogin'] = $uData ['login_date'];
  561. $_user ['official_code'] = $uData ['official_code'];
  562. $_user ['picture_uri'] = $uData ['picture_uri'];
  563. $_user ['user_id'] = $uData ['user_id'];
  564. $_user ['language'] = $uData ['language'];
  565. $_user ['auth_source'] = $uData ['auth_source'];
  566. $_user ['theme'] = $uData ['theme'];
  567. $_user ['status'] = $uData ['status'];
  568. $is_platformAdmin = (bool) (! is_null( $uData['is_admin']));
  569. $is_allowedCreateCourse = (bool) (($uData ['status'] == 1) or (api_get_setting('drhCourseManagerRights') and $uData['status'] == 4));
  570. api_session_register('_user');
  571. } else {
  572. header('location:'.api_get_path(WEB_PATH));
  573. //exit("WARNING UNDEFINED UID !! ");
  574. }
  575. } else { // no uid => logout or Anonymous
  576. api_session_unregister('_user');
  577. api_session_unregister('_uid');
  578. }
  579. api_session_register('is_platformAdmin');
  580. api_session_register('is_allowedCreateCourse');
  581. } else { // continue with the previous values
  582. $_user = $_SESSION['_user'];
  583. $is_platformAdmin = $_SESSION['is_platformAdmin'];
  584. $is_allowedCreateCourse = $_SESSION['is_allowedCreateCourse'];
  585. }
  586. /* COURSE INIT */
  587. if (isset($cidReset) && $cidReset) { // course session data refresh requested or empty data
  588. if ($cidReq) {
  589. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  590. $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  591. $sql = "SELECT course.*, course_category.code faCode, course_category.name faName
  592. FROM $course_table
  593. LEFT JOIN $course_cat_table
  594. ON course.category_code = course_category.code
  595. WHERE course.code = '$cidReq'";
  596. $result = Database::query($sql);
  597. if (Database::num_rows($result)>0) {
  598. $cData = Database::fetch_array($result);
  599. //@TODO real_cid should be cid, for working with numeric course id
  600. $_real_cid = $cData['id'];
  601. $_cid = $cData['code'];
  602. $_course = array();
  603. $_course['real_id'] = $cData['id'];
  604. $_course['id'] = $cData['code']; //auto-assigned integer
  605. $_course['name'] = $cData['title'];
  606. $_course['official_code'] = $cData['visual_code']; // use in echo
  607. $_course['sysCode'] = $cData['code']; // use as key in db
  608. $_course['path'] = $cData['directory']; // use as key in path
  609. $_course['dbName'] = $cData['db_name']; // use as key in db list
  610. $_course['dbNameGlu'] = $_configuration['table_prefix'] . $cData['db_name'] . $_configuration['db_glue']; // use in all queries
  611. $_course['titular'] = $cData['tutor_name'];
  612. $_course['language'] = $cData['course_language'];
  613. $_course['extLink']['url' ] = $cData['department_url'];
  614. $_course['extLink']['name'] = $cData['department_name'];
  615. $_course['categoryCode'] = $cData['faCode'];
  616. $_course['categoryName'] = $cData['faName'];
  617. $_course['visibility'] = $cData['visibility'];
  618. $_course['subscribe_allowed'] = $cData['subscribe'];
  619. $_course['unubscribe_allowed'] = $cData['unsubscribe'];
  620. api_session_register('_cid');
  621. api_session_register('_course');
  622. //@TODO real_cid should be cid, for working with numeric course id
  623. api_session_register('_real_cid');
  624. // if a session id has been given in url, we store the session
  625. if (api_get_setting('use_session_mode')=='true') {
  626. // Database Table Definitions
  627. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  628. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  629. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  630. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  631. if (!empty($_GET['id_session'])) {
  632. $_SESSION['id_session'] = intval($_GET['id_session']);
  633. $sql = 'SELECT name FROM '.$tbl_session . ' WHERE id="'.intval($_SESSION['id_session']) . '"';
  634. $rs = Database::query($sql);
  635. list($_SESSION['session_name']) = Database::fetch_array($rs);
  636. } else {
  637. api_session_unregister('session_name');
  638. api_session_unregister('id_session');
  639. }
  640. }
  641. if ($_configuration['tracking_enabled'] && !isset($_SESSION['login_as'])) {
  642. //We add a new record in the course tracking table
  643. $course_tracking_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  644. $time = api_get_datetime();
  645. $sql="INSERT INTO $course_tracking_table(course_code, user_id, login_course_date, logout_course_date, counter, session_id)" .
  646. "VALUES('".$_course['sysCode']."', '".$_user['user_id']."', '$time', '$time', '1', '".api_get_session_id()."')";
  647. //error_log($sql);
  648. Database::query($sql);
  649. }
  650. } else {
  651. //exit("WARNING UNDEFINED CID !! ");
  652. header('location:'.api_get_path(WEB_PATH));
  653. }
  654. } else {
  655. api_session_unregister('_cid');
  656. api_session_unregister('_real_cid');
  657. api_session_unregister('_course');
  658. //Deleting session info
  659. if (api_get_session_id()) {
  660. api_session_unregister('id_session');
  661. api_session_unregister('session_name');
  662. }
  663. }
  664. } else { // continue with the previous values
  665. if (empty($_SESSION['_course']) OR empty($_SESSION['_cid'])) { //no previous values...
  666. $_cid = -1; //set default values that will be caracteristic of being unset
  667. $_course = -1;
  668. } else {
  669. $_cid = $_SESSION['_cid' ];
  670. $_course = $_SESSION['_course'];
  671. // these lines are usefull for tracking. Indeed we can have lost the id_session and not the cid.
  672. // Moreover, if we want to track a course with another session it can be usefull
  673. if (!empty($_GET['id_session'])) {
  674. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  675. $_SESSION['id_session'] = intval($_GET['id_session']);
  676. $sql = 'SELECT name FROM '.$tbl_session . ' WHERE id="'.intval($_SESSION['id_session']). '"';
  677. $rs = Database::query($sql);
  678. list($_SESSION['session_name']) = Database::fetch_array($rs);
  679. }
  680. if ($_configuration['tracking_enabled'] && !isset($_SESSION['login_as'])) {
  681. $course_tracking_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  682. if (isset($_configuration['session_lifetime'])) {
  683. $session_lifetime = $_configuration['session_lifetime'];
  684. } else {
  685. $session_lifetime = 3600;
  686. }
  687. $course_code=$_course['sysCode'];
  688. $time = api_get_datetime();
  689. //We select the last record for the current course in the course tracking table
  690. // But only if the login date is < thant now + max_life_time
  691. $sql="SELECT course_access_id FROM $course_tracking_table
  692. WHERE user_id=".intval($_user ['user_id'])."
  693. AND course_code='$course_code' AND session_id = ".api_get_session_id()."
  694. AND login_course_date > now() - INTERVAL $session_lifetime SECOND
  695. ORDER BY login_course_date DESC LIMIT 0,1";
  696. $result=Database::query($sql);
  697. //error_log($sql);
  698. if (Database::num_rows($result)>0) {
  699. $i_course_access_id = Database::result($result,0,0);
  700. //We update the course tracking table
  701. $sql="UPDATE $course_tracking_table SET logout_course_date = '$time', counter = counter+1 ".
  702. "WHERE course_access_id=".intval($i_course_access_id)." AND session_id = ".api_get_session_id();
  703. //error_log($sql);
  704. Database::query($sql);
  705. } else {
  706. $sql="INSERT INTO $course_tracking_table (course_code, user_id, login_course_date, logout_course_date, counter, session_id)" .
  707. "VALUES('".$course_code."', '".$_user['user_id']."', '$time', '$time', '1','".api_get_session_id()."')";
  708. //error_log($sql);
  709. Database::query($sql);
  710. }
  711. }
  712. }
  713. }
  714. /* COURSE / USER REL. INIT */
  715. if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset)) { // session data refresh requested
  716. if (isset($_user['user_id']) && $_user['user_id'] && isset($_cid) && $_cid) { // have keys to search data
  717. if (api_get_setting('use_session_mode') != 'true') {
  718. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  719. $sql = "SELECT * FROM $course_user_table
  720. WHERE user_id = '".$_user['user_id']."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH."
  721. AND course_code = '$cidReq'";
  722. $result = Database::query($sql);
  723. if (Database::num_rows($result) > 0) { // this user have a recorded state for this course
  724. $cuData = Database::fetch_array($result);
  725. $is_courseMember = true;
  726. $is_courseTutor = (bool) ($cuData['tutor_id' ] == 1 );
  727. $is_courseAdmin = (bool) ($cuData['status'] == 1 );
  728. api_session_register('_courseUser');
  729. } else { // this user has no status related to this course
  730. $is_courseMember = false;
  731. $is_courseAdmin = false;
  732. $is_courseTutor = false;
  733. }
  734. $is_courseAdmin = (bool) ($is_courseAdmin || $is_platformAdmin);
  735. } else {
  736. $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  737. $sql = "SELECT * FROM ".$tbl_course_user."
  738. WHERE user_id = '".$_user['user_id']."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH."
  739. AND course_code = '$cidReq'";
  740. $result = Database::query($sql);
  741. if (Database::num_rows($result) > 0) { // this user have a recorded state for this course
  742. $cuData = Database::fetch_array($result);
  743. $_courseUser['role'] = $cuData['role' ];
  744. $is_courseMember = true;
  745. $is_courseTutor = (bool) ($cuData['tutor_id' ] == 1 );
  746. $is_courseAdmin = (bool) ($cuData['status'] == 1 );
  747. api_session_register('_courseUser');
  748. }
  749. if (!isset($is_courseAdmin)) { // this user has no status related to this course
  750. // is it the session coach or the session admin ?
  751. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  752. $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
  753. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  754. $sql = " SELECT session.id_coach, session_admin_id FROM $tbl_session session,$tbl_session_course_user session_rcru
  755. 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";
  756. /*$sql = "SELECT session.id_coach, session_admin_id
  757. FROM ".$tbl_session." as session
  758. INNER JOIN ".$tbl_session_course_user."
  759. ON session_rel_course.id_session = session.id
  760. AND session_rel_course.course_code='$_cid'";
  761. */
  762. $result = Database::query($sql);
  763. $row = Database::store_result($result);
  764. if ($row[0]['id_coach']==$_user['user_id']) {
  765. $_courseUser['role'] = 'Professor';
  766. $is_courseMember = true;
  767. $is_courseTutor = true;
  768. $is_courseCoach = true;
  769. $is_sessionAdmin = false;
  770. if (api_get_setting('extend_rights_for_coach')=='true') {
  771. $is_courseAdmin = true;
  772. } else {
  773. $is_courseAdmin = false;
  774. }
  775. api_session_register('_courseUser');
  776. } elseif ($row[0]['session_admin_id']==$_user['user_id']) {
  777. $_courseUser['role'] = 'Professor';
  778. $is_courseMember = false;
  779. $is_courseTutor = false;
  780. $is_courseAdmin = false;
  781. $is_courseCoach = false;
  782. $is_sessionAdmin = true;
  783. } else {
  784. // Check if the current user is the course coach
  785. $sql = "SELECT 1
  786. FROM ".$tbl_session_course_user."
  787. WHERE course_code='$_cid'
  788. AND id_user = '".$_user['user_id']."'
  789. AND id_session = '".api_get_session_id()."'
  790. AND status = 2";
  791. $result = Database::query($sql);
  792. if ($row = Database::fetch_array($result)) {
  793. $_courseUser['role'] = 'Professor';
  794. $is_courseMember = true;
  795. $is_courseTutor = true;
  796. $is_courseCoach = true;
  797. $is_sessionAdmin = false;
  798. if (api_get_setting('extend_rights_for_coach')=='true') {
  799. $is_courseAdmin = true;
  800. } else {
  801. $is_courseAdmin = false;
  802. }
  803. api_session_register('_courseUser');
  804. } else {
  805. if (api_get_session_id() != 0) {
  806. // Check if the user is a student is this session
  807. $sql = "SELECT * FROM ".$tbl_session_course_user."
  808. WHERE id_user = '".$_user['user_id']."'
  809. AND id_session = '".api_get_session_id()."'
  810. AND course_code = '$cidReq' AND status NOT IN(2)";
  811. $result = Database::query($sql);
  812. if (Database::num_rows($result) > 0) { // this user have a recorded state for this course
  813. while($row = Database::fetch_array($result)){
  814. $is_courseMember = true;
  815. $is_courseTutor = false;
  816. $is_courseAdmin = false;
  817. $is_sessionAdmin = false;
  818. api_session_register('_courseUser');
  819. }
  820. }
  821. } else {
  822. //unregister user
  823. $is_courseMember = false;
  824. $is_courseTutor = false;
  825. $is_courseAdmin = false;
  826. $is_sessionAdmin = false;
  827. api_session_unregister('_courseUser');
  828. //$_course['visibility'] = 0; this depends the
  829. }
  830. }
  831. }
  832. }
  833. }
  834. } else { // keys missing => not anymore in the course - user relation
  835. // course
  836. $is_courseMember = false;
  837. $is_courseAdmin = false;
  838. $is_courseTutor = false;
  839. $is_courseCoach = false;
  840. $is_sessionAdmin = false;
  841. api_session_unregister('_courseUser');
  842. }
  843. //DEPRECATED
  844. //$is_courseAllowed=($_cid && ($_course['visibility'] || $is_courseMember || $is_platformAdmin))?true:false;
  845. //NEW
  846. if (isset($_course)) {
  847. if ($_course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD)
  848. $is_allowed_in_course = true;
  849. elseif ($_course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM && isset($_user['user_id']) && !api_is_anonymous($_user['user_id']))
  850. $is_allowed_in_course = true;
  851. elseif ($_course['visibility'] == COURSE_VISIBILITY_REGISTERED && ($is_platformAdmin || $is_courseMember))
  852. $is_allowed_in_course = true;
  853. elseif ($_course['visibility'] == COURSE_VISIBILITY_CLOSED && ($is_platformAdmin || $is_courseAdmin))
  854. $is_allowed_in_course = true;
  855. else $is_allowed_in_course = false;
  856. }
  857. // requires testing!!!
  858. // check the session visibility
  859. if (!empty($is_allowed_in_course)) {
  860. $my_session_id = api_get_session_id();
  861. //if I'm in a session
  862. //var_dump($is_platformAdmin, $is_courseTutor,api_is_coach());
  863. if ($my_session_id!=0)
  864. if (!$is_platformAdmin) {
  865. // admin and session coach are *not* affected to the invisible session mode
  866. // the coach is not affected because he can log in some days after the end date of a session
  867. $session_visibility = api_get_session_visibility($my_session_id);
  868. if ($session_visibility==SESSION_INVISIBLE)
  869. $is_allowed_in_course =false;
  870. }
  871. }
  872. // save the states
  873. api_session_register('is_courseMember');
  874. api_session_register('is_courseAdmin');
  875. //api_session_register('is_courseAllowed'); //deprecated old permission var
  876. api_session_register('is_courseTutor');
  877. api_session_register('is_allowed_in_course'); //new permission var
  878. api_session_register('is_courseCoach');
  879. api_session_register('is_sessionAdmin');
  880. } else { // continue with the previous values
  881. if (isset($_SESSION ['_courseUser'])) {
  882. $_courseUser = $_SESSION ['_courseUser'];
  883. }
  884. $is_courseMember = $_SESSION ['is_courseMember' ];
  885. $is_courseAdmin = $_SESSION ['is_courseAdmin' ];
  886. //$is_courseAllowed = $_SESSION ['is_courseAllowed']; //deprecated
  887. $is_allowed_in_course = $_SESSION ['is_allowed_in_course'];
  888. $is_courseTutor = $_SESSION ['is_courseTutor' ];
  889. $is_courseCoach = $_SESSION ['is_courseCoach' ];
  890. }
  891. /* GROUP INIT */
  892. if ((isset($gidReset) && $gidReset) || (isset($cidReset) && $cidReset)) { // session data refresh requested
  893. if ($gidReq && $_cid ) { // have keys to search data
  894. $group_table = Database::get_course_table(TABLE_GROUP);
  895. $sql = "SELECT * FROM $group_table WHERE id = '$gidReq'";
  896. $result = Database::query($sql);
  897. if (Database::num_rows($result) > 0) { // This group has recorded status related to this course
  898. $gpData = Database::fetch_array($result);
  899. $_gid = $gpData ['id' ];
  900. api_session_register('_gid');
  901. } else {
  902. exit("WARNING UNDEFINED GID !! ");
  903. }
  904. } elseif (isset($_SESSION['_gid']) or isset($_gid)) { // Keys missing => not anymore in the group - course relation
  905. api_session_unregister('_gid');
  906. }
  907. } elseif (isset($_SESSION['_gid'])) { // continue with the previous values
  908. $_gid = $_SESSION ['_gid' ];
  909. } else { //if no previous value, assign caracteristic undefined value
  910. $_gid = -1;
  911. }
  912. //set variable according to student_view_enabled choices
  913. if (api_get_setting('student_view_enabled') == "true") {
  914. if (isset($_GET['isStudentView'])) {
  915. if ($_GET['isStudentView'] == 'true') {
  916. if (isset($_SESSION['studentview'])) {
  917. if (!empty($_SESSION['studentview'])) {
  918. // switching to studentview
  919. $_SESSION['studentview'] = 'studentview';
  920. }
  921. }
  922. } elseif ($_GET['isStudentView'] == 'false') {
  923. if (isset($_SESSION['studentview'])) {
  924. if (!empty($_SESSION['studentview'])) {
  925. // switching to teacherview
  926. $_SESSION['studentview'] = 'teacherview';
  927. }
  928. }
  929. }
  930. } elseif (!empty($_SESSION['studentview'])) {
  931. //all is fine, no change to that, obviously
  932. } elseif (empty($_SESSION['studentview'])) {
  933. // We are in teacherview here
  934. $_SESSION['studentview'] = 'teacherview';
  935. }
  936. }
  937. if (isset($_cid)) {
  938. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  939. $time = api_get_datetime();
  940. $sql="UPDATE $tbl_course SET last_visit= '$time' WHERE code='$_cid'";
  941. Database::query($sql);
  942. }