local.inc.php 36 KB

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