local.inc.php 48 KB

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